Example #1
0
int
pkg_perform(const char *pkg)
{
	char   *cp;
	FILE   *pkg_in;
	package_t plist;
	const char *full_pkg, *suffix;
	char *allocated_pkg;
	int retval;

	/* Break the package name into base and desired suffix (if any) */
	if ((cp = strrchr(pkg, '.')) != NULL) {
		if ((allocated_pkg = malloc(cp - pkg + 1)) == NULL)
			err(2, "malloc failed");
		memcpy(allocated_pkg, pkg, cp - pkg);
		allocated_pkg[cp - pkg] = '\0';
		suffix = cp + 1;
		full_pkg = pkg;
		pkg = allocated_pkg;
	} else {
		allocated_pkg = NULL;
		full_pkg = pkg;
		suffix = "tgz";
	}

	/* Preliminary setup */
	sanity_check();
	if (Verbose && !PlistOnly)
		printf("Creating package %s\n", pkg);
	get_dash_string(&Comment);
	get_dash_string(&Desc);
	if (IS_STDIN(Contents))
		pkg_in = stdin;
	else {
		pkg_in = fopen(Contents, "r");
		if (!pkg_in)
			errx(2, "unable to open contents file '%s' for input", Contents);
	}
	plist.head = plist.tail = NULL;

	/* If a SrcDir override is set, add it now */
	if (SrcDir) {
		if (Verbose && !PlistOnly)
			printf("Using SrcDir value of %s\n", (realprefix) ? realprefix : SrcDir);
		add_plist(&plist, PLIST_SRC, SrcDir);
	}

	/* Stick the dependencies, if any, at the top */
	if (Pkgdeps)
		register_depends(&plist, Pkgdeps, 0);

	/*
	 * Put the build dependencies after the dependencies.
	 * This works due to the evaluation order in pkg_add.
	 */
	if (BuildPkgdeps)
		register_depends(&plist, BuildPkgdeps, 1);

	/* Put the conflicts directly after the dependencies, if any */
	if (Pkgcfl) {
		if (Verbose && !PlistOnly)
			printf("Registering conflicts:");
		while (Pkgcfl) {
			cp = strsep(&Pkgcfl, " \t\n");
			if (*cp) {
				add_plist(&plist, PLIST_PKGCFL, cp);
				if (Verbose && !PlistOnly)
					printf(" %s", cp);
			}
		}
		if (Verbose && !PlistOnly)
			printf(".\n");
	}

	/* Slurp in the packing list */
	read_plist(&plist, pkg_in);

	if (pkg_in != stdin)
		fclose(pkg_in);

	/* Prefix should override the packing list */
	if (Prefix) {
		delete_plist(&plist, FALSE, PLIST_CWD, NULL);
		add_plist_top(&plist, PLIST_CWD, Prefix);
	}
	/*
         * Run down the list and see if we've named it, if not stick in a name
         * at the top.
         */
	if (find_plist(&plist, PLIST_NAME) == NULL) {
		add_plist_top(&plist, PLIST_NAME, basename_of(pkg));
	}

	/* Make first "real contents" pass over it */
	check_list(&plist, basename_of(pkg));

	/*
         * We're just here for to dump out a revised plist for the FreeBSD ports
         * hack.  It's not a real create in progress.
         */
	if (PlistOnly) {
		write_plist(&plist, stdout, realprefix);
		retval = TRUE;
	} else {
#ifdef BOOTSTRAP
		warnx("Package building is not supported in bootstrap mode");
		retval = FALSE;
#else
		retval = pkg_build(pkg, full_pkg, suffix, &plist);
#endif
	}

	/* Cleanup */
	free(Comment);
	free(Desc);
	free_plist(&plist);

	free(allocated_pkg);

	return retval;
}
Example #2
0
static int
parse_prime(int linenum, char *line, struct dhgroup *dhg)
{
	char *cp, *arg;
	char *strsize, *gen, *prime;
	const char *errstr = NULL;
	long long n;

	dhg->p = dhg->g = NULL;
	cp = line;
	if ((arg = strdelim(&cp)) == NULL)
		return 0;
	/* Ignore leading whitespace */
	if (*arg == '\0')
		arg = strdelim(&cp);
	if (!arg || !*arg || *arg == '#')
		return 0;

	/* time */
	if (cp == NULL || *arg == '\0')
		goto truncated;
	arg = strsep(&cp, " "); /* type */
	if (cp == NULL || *arg == '\0')
		goto truncated;
	/* Ensure this is a safe prime */
	n = strtonum(arg, 0, 5, &errstr);
	if (errstr != NULL || n != MODULI_TYPE_SAFE) {
		error("moduli:%d: type is not %d", linenum, MODULI_TYPE_SAFE);
		goto fail;
	}
	arg = strsep(&cp, " "); /* tests */
	if (cp == NULL || *arg == '\0')
		goto truncated;
	/* Ensure prime has been tested and is not composite */
	n = strtonum(arg, 0, 0x1f, &errstr);
	if (errstr != NULL ||
	    (n & MODULI_TESTS_COMPOSITE) || !(n & ~MODULI_TESTS_COMPOSITE)) {
		error("moduli:%d: invalid moduli tests flag", linenum);
		goto fail;
	}
	arg = strsep(&cp, " "); /* tries */
	if (cp == NULL || *arg == '\0')
		goto truncated;
	n = strtonum(arg, 0, 1<<30, &errstr);
	if (errstr != NULL || n == 0) {
		error("moduli:%d: invalid primality trial count", linenum);
		goto fail;
	}
	strsize = strsep(&cp, " "); /* size */
	if (cp == NULL || *strsize == '\0' ||
	    (dhg->size = (int)strtonum(strsize, 0, 64*1024, &errstr)) == 0 ||
	    errstr) {
		error("moduli:%d: invalid prime length", linenum);
		goto fail;
	}
	/* The whole group is one bit larger */
	dhg->size++;
	gen = strsep(&cp, " "); /* gen */
	if (cp == NULL || *gen == '\0')
		goto truncated;
	prime = strsep(&cp, " "); /* prime */
	if (cp != NULL || *prime == '\0') {
 truncated:
		error("moduli:%d: truncated", linenum);
		goto fail;
	}

	if ((dhg->g = BN_new()) == NULL ||
	    (dhg->p = BN_new()) == NULL) {
		error("parse_prime: BN_new failed");
		goto fail;
	}
	if (BN_hex2bn(&dhg->g, gen) == 0) {
		error("moduli:%d: could not parse generator value", linenum);
		goto fail;
	}
	if (BN_hex2bn(&dhg->p, prime) == 0) {
		error("moduli:%d: could not parse prime value", linenum);
		goto fail;
	}
	if (BN_num_bits(dhg->p) != dhg->size) {
		error("moduli:%d: prime has wrong size: actual %d listed %d",
		    linenum, BN_num_bits(dhg->p), dhg->size - 1);
		goto fail;
	}
	if (BN_cmp(dhg->g, BN_value_one()) <= 0) {
		error("moduli:%d: generator is invalid", linenum);
		goto fail;
	}
	return 1;

 fail:
	BN_clear_free(dhg->g);
	BN_clear_free(dhg->p);
	dhg->g = dhg->p = NULL;
	return 0;
}
Example #3
0
static int
doit(gzFile *infp)
{
	int		i, skip = 0;
	time_t		curtime, ll_time;
	char		*user, node[TBDB_FLEN_NODEID * 2], prog[128];
	char		buf[BUFSIZ], *bp, uid_idx[128], tmp[BUFSIZ];
	struct tm	tm;
	MYSQL_RES	*dbres;
	MYSQL_ROW	dbrow;
	
	while (1) {
		if (gzgets(infp, buf, BUFSIZ) == NULL)
			break;

		/*
		 * If the line does not contain a newline, then we skip it
		 * and try to sync up again. We consider ourselves synced
		 * when the buffer contains a newline in it.
		 */
		if (buf[strlen(buf) - 1] != '\n') {
			skip = 1;
			continue;
		}
		if (skip) {
			skip = 0;
			continue;
 		}

		/*
		 * Thank dog for strptime! Convert the syslog timestamp
		 * into a tm, and then into regular unix time.
		 */
		time(&curtime);
		localtime_r(&curtime, &tm);
		if ((bp = strptime(buf, "%b %e %T", &tm)) == NULL) {
			continue;
		}
		ll_time = mktime(&tm);

		/*
		 * If the constructed time is in the future, then we have
		 * year off by one (cause we are possibly looking at files
		 * created in the previous year). Set the year back by one,
		 * and redo.
		 */
		if (ll_time > curtime) {
			tm.tm_year--;
			ll_time = mktime(&tm);
		}

		/*
		 * Scanf the next part, which looks like:
		 *
		 *	node progname[pid]:
		 *
		 * Ensure we match the proper number of items.
		 */
		bzero(node, sizeof(node));
		if ((sscanf(bp, "%s %s:", node, prog) != 2))
			continue;

		/*
		 * Only sshd matters to us.
		 */
		if (strncmp(prog, SSHD, strlen(SSHD)))
			continue;

		/*
		 * Okay, these kinds of strings matter.
		 *
		 *	FreeBSD:	"Accepted rsa for USER" 
		 *	Linux 6.2:	"log: RSA authentication for USER"
		 *	Linux 7.1:	"session opened for user USER"
		 *      (several ssh2): "Accepted publickey for USER"
		 *      (several ssh2): "Accepted password for USER"
		 *      (several ssh2): "Accepted keyboard-interactive for USER"
		 */
#define L1	"Accepted rsa for "
#define L2	"session opened for user "
#define L3	"log: RSA authentication for "
#define L4	"Accepted publickey for "
#define L5	"Accepted password for "
#define L6	"Accepted keyboard-interactive for "
		
		/* Skip to end of program[pid]: and trailing space */
		bp = strchr(bp, ':');
		bp += 2;

		if (strncmp(bp, L1, strlen(L1)) == 0) {
		  /*fprintf(stdout,"Hit L1: ");*/
			bp += strlen(L1);
		}
		else if (strncmp(bp, L2, strlen(L2)) == 0) {
		  /*fprintf(stdout,"Hit L2: ");*/
			bp += strlen(L2);
		}
		else if (strncmp(bp, L3, strlen(L3)) == 0) {
		  /*fprintf(stdout,"Hit L3: ");*/
			bp += strlen(L3);
		}
		else if (strncmp(bp, L4, strlen(L4)) == 0) {
		  /*fprintf(stdout,"Hit L4: ");*/
			bp += strlen(L4);
		}
		else if (strncmp(bp, L5, strlen(L5)) == 0) {
		  /*fprintf(stdout,"Hit L5: ");*/
			bp += strlen(L5);
		}
		else if (strncmp(bp, L6, strlen(L6)) == 0) {
		  /*fprintf(stdout,"Hit L6: ");*/
			bp += strlen(L6);
		}
		else {
			continue;
		}

		/*
		 * The login name is the next token.
		 */
		if (! (user = strsep(&bp, " ")))
			continue;
		/*fprintf(stdout,"%s on %s\n",user,node);*/

		/* We do not care about ROOT logins. */
		if (strcasecmp(user, "ROOT") == 0)
			continue;

		dbres = mydb_query("select uid_idx from users where uid='%s' "
				   "and status!='archived' and status!='nonlocal'",
				   1, user);

		if (!dbres) {
			syslog(LOG_ERR, "DB error getting user %s", user);
			continue;
		}

		if (!mysql_num_rows(dbres)) {
			syslog(LOG_INFO, "No DB record for user %s", user);
			mysql_free_result(dbres);
			continue;
		}
		dbrow = mysql_fetch_row(dbres);
		strncpy(uid_idx, dbrow[0], sizeof(uid_idx));
		mysql_free_result(dbres);

		/*
		 * Safety first. 
		 */
		mydb_escape_string(tmp, uid_idx, strlen(uid_idx));
		strcpy(uid_idx, tmp);
		mydb_escape_string(tmp, node, strlen(node));
		strcpy(node, tmp);

		if (mydb_update("replace into uidnodelastlogin "
				"(uid, uid_idx, node_id, date, time) "
				"values ('%s', '%s', '%s', "
				"        FROM_UNIXTIME(%ld, '%%Y-%%m-%%d'), "
				"        FROM_UNIXTIME(%ld, '%%T')) ",
				user, uid_idx, node, ll_time, ll_time) == 0)
			break;

		if (strncmp(node, opshostname, strlen(node)) == 0 ||
		    strncmp(node, "ops", strlen(node)) == 0) {
			if (mydb_update("replace into userslastlogin "
					"(uid, uid_idx, date, time) "
					"values ('%s', '%s', "
					"  FROM_UNIXTIME(%ld, '%%Y-%%m-%%d'), "
					"  FROM_UNIXTIME(%ld, '%%T')) ",
					user, uid_idx, ll_time, ll_time) == 0)
				break;
		}
		else {
			if (mydb_update("replace into nodeuidlastlogin "
					"(node_id, uid_idx, uid, date, time) "
					"values ('%s', '%s', '%s', "
					"  FROM_UNIXTIME(%ld, '%%Y-%%m-%%d'), "
					"  FROM_UNIXTIME(%ld, '%%T')) ",
					node, uid_idx, user, ll_time, ll_time) == 0)
				break;
		}
	}
	return 0;
}
Example #4
0
static int parse_setup_cpu_list(void)
{
	struct thread_data *td;
	char *str0, *str;
	int t;

	if (!g->p.cpu_list_str)
		return 0;

	dprintf("g->p.nr_tasks: %d\n", g->p.nr_tasks);

	str0 = str = strdup(g->p.cpu_list_str);
	t = 0;

	BUG_ON(!str);

	tprintf("# binding tasks to CPUs:\n");
	tprintf("#  ");

	while (true) {
		int bind_cpu, bind_cpu_0, bind_cpu_1;
		char *tok, *tok_end, *tok_step, *tok_len, *tok_mul;
		int bind_len;
		int step;
		int mul;

		tok = strsep(&str, ",");
		if (!tok)
			break;

		tok_end = strstr(tok, "-");

		dprintf("\ntoken: {%s}, end: {%s}\n", tok, tok_end);
		if (!tok_end) {
			/* Single CPU specified: */
			bind_cpu_0 = bind_cpu_1 = atol(tok);
		} else {
			/* CPU range specified (for example: "5-11"): */
			bind_cpu_0 = atol(tok);
			bind_cpu_1 = atol(tok_end + 1);
		}

		step = 1;
		tok_step = strstr(tok, "#");
		if (tok_step) {
			step = atol(tok_step + 1);
			BUG_ON(step <= 0 || step >= g->p.nr_cpus);
		}

		/*
		 * Mask length.
		 * Eg: "--cpus 8_4-16#4" means: '--cpus 8_4,12_4,16_4',
		 * where the _4 means the next 4 CPUs are allowed.
		 */
		bind_len = 1;
		tok_len = strstr(tok, "_");
		if (tok_len) {
			bind_len = atol(tok_len + 1);
			BUG_ON(bind_len <= 0 || bind_len > g->p.nr_cpus);
		}

		/* Multiplicator shortcut, "0x8" is a shortcut for: "0,0,0,0,0,0,0,0" */
		mul = 1;
		tok_mul = strstr(tok, "x");
		if (tok_mul) {
			mul = atol(tok_mul + 1);
			BUG_ON(mul <= 0);
		}

		dprintf("CPUs: %d_%d-%d#%dx%d\n", bind_cpu_0, bind_len, bind_cpu_1, step, mul);

		if (bind_cpu_0 >= g->p.nr_cpus || bind_cpu_1 >= g->p.nr_cpus) {
			printf("\nTest not applicable, system has only %d CPUs.\n", g->p.nr_cpus);
			return -1;
		}

		BUG_ON(bind_cpu_0 < 0 || bind_cpu_1 < 0);
		BUG_ON(bind_cpu_0 > bind_cpu_1);

		for (bind_cpu = bind_cpu_0; bind_cpu <= bind_cpu_1; bind_cpu += step) {
			int i;

			for (i = 0; i < mul; i++) {
				int cpu;

				if (t >= g->p.nr_tasks) {
					printf("\n# NOTE: ignoring bind CPUs starting at CPU#%d\n #", bind_cpu);
					goto out;
				}
				td = g->threads + t;

				if (t)
					tprintf(",");
				if (bind_len > 1) {
					tprintf("%2d/%d", bind_cpu, bind_len);
				} else {
					tprintf("%2d", bind_cpu);
				}

				CPU_ZERO(&td->bind_cpumask);
				for (cpu = bind_cpu; cpu < bind_cpu+bind_len; cpu++) {
					BUG_ON(cpu < 0 || cpu >= g->p.nr_cpus);
					CPU_SET(cpu, &td->bind_cpumask);
				}
				t++;
			}
		}
	}
out:

	tprintf("\n");

	if (t < g->p.nr_tasks)
		printf("# NOTE: %d tasks bound, %d tasks unbound\n", t, g->p.nr_tasks - t);

	free(str0);
	return 0;
}
Example #5
0
int
main(int ac, char **av)
{
	int ch;
	int res;
	char *sched = NULL;
	char *cpustr = NULL;
	char *sched_cpustr = NULL;
	char *p = NULL;
	cpumask_t cpumask;
	int cpuid;
	pid_t pid = getpid();  /* See usched_set(2) - BUGS */

	CPUMASK_ASSZERO(cpumask);

	while ((ch = getopt(ac, av, "d")) != -1) {
		switch (ch) {
		case 'd':
			DebugOpt = 1;
			break;
		default:
			usage();
			/* NOTREACHED */
		}
	}
	ac -= optind;
	av += optind;

	if (ac < 2) {
		usage();
		/* NOTREACHED */
	}
	sched_cpustr = strdup(av[0]);
	sched = strsep(&sched_cpustr, ":");
	if (strcmp(sched, "default") == 0)
		fprintf(stderr, "Ignoring scheduler == \"default\": not implemented\n");
	cpustr = strsep(&sched_cpustr, "");
	if (strlen(sched) == 0 && cpustr == NULL) {
		usage();
		/* NOTREACHED */
	}

	/*
	 * XXX needs expanded support for > 64 cpus
	 */
	if (cpustr != NULL) {
		uint64_t v;

		v = (uint64_t)strtoull(cpustr, NULL, 0);
		for (cpuid = 0; cpuid < (int)sizeof(v) * 8; ++cpuid) {
			if (v & (1LU << cpuid))
				CPUMASK_ORBIT(cpumask, cpuid);
		}
	}

	if (strlen(sched) != 0) {
		if (DebugOpt)
			fprintf(stderr, "DEBUG: USCHED_SET_SCHEDULER: scheduler: %s\n", sched);
		res = usched_set(pid, USCHED_SET_SCHEDULER, sched, strlen(sched));
		if (res != 0) {
			asprintf(&p, "usched_set(%d, USCHED_SET_SCHEDULER, \"%s\", %d)",
				pid, sched, (int)strlen(sched));
			perror(p);
			exit(1);
		}
	}
	if (CPUMASK_TESTNZERO(cpumask)) {
		for (cpuid = 0; cpuid < (int)sizeof(cpumask) * 8; ++cpuid) {
			if (CPUMASK_TESTBIT(cpumask, cpuid))
				break;
		}
		if (DebugOpt) {
			fprintf(stderr, "DEBUG: USCHED_SET_CPU: cpuid: %d\n",
				cpuid);
		}
		res = usched_set(pid, USCHED_SET_CPU, &cpuid, sizeof(int));
		if (res != 0) {
			asprintf(&p, "usched_set(%d, USCHED_SET_CPU, &%d, %d)",
				pid, cpuid, (int)sizeof(int));
			perror(p);
			exit(1);
		}
		CPUMASK_NANDBIT(cpumask, cpuid);
		while (CPUMASK_TESTNZERO(cpumask)) {
			++cpuid;
			if (CPUMASK_TESTBIT(cpumask, cpuid) == 0)
				continue;
			CPUMASK_NANDBIT(cpumask, cpuid);
			if (DebugOpt) {
				fprintf(stderr,
					"DEBUG: USCHED_ADD_CPU: cpuid: %d\n",
					cpuid);
			}
			res = usched_set(pid, USCHED_ADD_CPU, &cpuid, sizeof(int));
			if (res != 0) {
				asprintf(&p, "usched_set(%d, USCHED_ADD_CPU, &%d, %d)",
					pid, cpuid, (int)sizeof(int));
				perror(p);
				exit(1);
			}
		}
	}
	execvp(av[1], av + 1);
	exit(1);
}
Example #6
0
/*
 * Load module stuff
 */
static int ind_load_module(void)
{
	struct ast_config *cfg;
	struct ast_variable *v;
	char *cxt;
	char *c;
	struct tone_zone *tones;
	const char *country = NULL;

	/* that the following cast is needed, is yuk! */
	/* yup, checked it out. It is NOT written to. */
	cfg = ast_config_load((char *)config);
	if (!cfg)
		return -1;

	/* Use existing config to populate the Indication table */
	cxt = ast_category_browse(cfg, NULL);
	while(cxt) {
		/* All categories but "general" are considered countries */
		if (!strcasecmp(cxt, "general")) {
			cxt = ast_category_browse(cfg, cxt);
			continue;
		}		
		if (!(tones = ast_calloc(1, sizeof(*tones)))) {
			ast_config_destroy(cfg);
			return -1;
		}
		ast_copy_string(tones->country,cxt,sizeof(tones->country));

		v = ast_variable_browse(cfg, cxt);
		while(v) {
			if (!strcasecmp(v->name, "description")) {
				ast_copy_string(tones->description, v->value, sizeof(tones->description));
			} else if ((!strcasecmp(v->name,"ringcadence"))||(!strcasecmp(v->name,"ringcadance"))) {
				char *ring,*rings = ast_strdupa(v->value);
				c = rings;
				ring = strsep(&c,",");
				while (ring) {
					int *tmp, val;
					if (!isdigit(ring[0]) || (val=atoi(ring))==-1) {
						ast_log(LOG_WARNING,"Invalid ringcadence given '%s' at line %d.\n",ring,v->lineno);
						ring = strsep(&c,",");
						continue;
					}					
					if (!(tmp = ast_realloc(tones->ringcadence, (tones->nrringcadence + 1) * sizeof(int)))) {
						ast_config_destroy(cfg);
						return -1;
					}
					tones->ringcadence = tmp;
					tmp[tones->nrringcadence] = val;
					tones->nrringcadence++;
					/* next item */
					ring = strsep(&c,",");
				}
			} else if (!strcasecmp(v->name,"alias")) {
				char *countries = ast_strdupa(v->value);
				c = countries;
				country = strsep(&c,",");
				while (country) {
					struct tone_zone* azone;
					if (!(azone = ast_calloc(1, sizeof(*azone)))) {
						ast_config_destroy(cfg);
						return -1;
					}
					ast_copy_string(azone->country, country, sizeof(azone->country));
					ast_copy_string(azone->alias, cxt, sizeof(azone->alias));
					if (ast_register_indication_country(azone)) {
						ast_log(LOG_WARNING, "Unable to register indication alias at line %d.\n",v->lineno);
						free(tones);
					}
					/* next item */
					country = strsep(&c,",");
				}
			} else {
				/* add tone to country */
				struct tone_zone_sound *ps,*ts;
				for (ps=NULL,ts=tones->tones; ts; ps=ts, ts=ts->next) {
					if (strcasecmp(v->name,ts->name)==0) {
						/* already there */
						ast_log(LOG_NOTICE,"Duplicate entry '%s', skipped.\n",v->name);
						goto out;
					}
				}
				/* not there, add it to the back */				
				if (!(ts = ast_malloc(sizeof(*ts)))) {
					ast_config_destroy(cfg);
					return -1;
				}
				ts->next = NULL;
				ts->name = strdup(v->name);
				ts->data = strdup(v->value);
				if (ps)
					ps->next = ts;
				else
					tones->tones = ts;
			}
out:			v = v->next;
		}
		if (tones->description[0] || tones->alias[0] || tones->tones) {
			if (ast_register_indication_country(tones)) {
				ast_log(LOG_WARNING, "Unable to register indication at line %d.\n",v->lineno);
				free(tones);
			}
		} else free(tones);

		cxt = ast_category_browse(cfg, cxt);
	}

	/* determine which country is the default */
	country = ast_variable_retrieve(cfg,"general","country");
	if (!country || !*country || ast_set_indication_country(country))
		ast_log(LOG_WARNING,"Unable to set the default country (for indication tones)\n");

	ast_config_destroy(cfg);
	return 0;
}
Example #7
0
/*
 *Join a chat room
 */
void join(packet *pkt, int fd) {
   int i = 0;
   char *args[16];
   char *tmp = pkt->buf;
   packet ret;

   // Split command args
   args[i] = strsep(&tmp, " \t");
   while ((i < sizeof(args) - 1) && (args[i] != '\0')) {
      args[++i] = strsep(&tmp, " \t");
   }
   if (i > 1 && validRoomname(args[0], fd)) {
      // check if room exists
      printf("Checking if room exists . . .\n");
      if (Rget_ID(&room_list, args[0], rooms_mutex) == -1) {
         // create if it does not exist
         createRoom(&room_list, numRooms, args[0], rooms_mutex);
      }
      RprintList(&room_list, rooms_mutex);
      printf("Receiving room node for requested room.\n");
      Room *newRoom = Rget_roomFNAME(&room_list, args[0], rooms_mutex);

      int currRoomNum = atoi(args[1]);
      // Should check if current room exists
      printf("Receiving room node for users current room.\n");
      Room *currentRoom = Rget_roomFID(&room_list, currRoomNum, rooms_mutex);//pkt->options);
      printf("Getting user node from current room user list.\n");
      if(currentRoom == NULL) {
         printf("Could not remove user: current room is NULL\n");
      }
      else {
         User *currUser = get_user(&(currentRoom->user_list), pkt->username, currentRoom->user_list_mutex);
         printf("Removing user from his current rooms user list\n");
         removeUser(&(currentRoom->user_list), currUser, currentRoom->user_list_mutex);
         printf("User removed from current room\n");
         
         //Create node to add user to other room list.
         Node *new_node = (Node *)malloc(sizeof(Node));
         new_node->data = currUser;
         currUser->roomID = newRoom->ID;
         printf("Inserting user into new rooms user list\n");
         insertUser(&(newRoom->user_list), currUser, newRoom->user_list_mutex);

         RprintList(&room_list, rooms_mutex);

         ret.options = JOINSUC;
         strcpy(ret.realname, SERVER_NAME);
         strcpy(ret.username, SERVER_NAME);
         ret.timestamp = time(NULL);
         sprintf(ret.buf, "%s %d", args[0], newRoom->ID);
         send(fd, (void *)&ret, sizeof(packet), MSG_NOSIGNAL);
         memset(&ret, 0, sizeof(ret));

         ret.options = currRoomNum;
         strcpy(ret.realname, SERVER_NAME);
         strcpy(ret.username, SERVER_NAME);
         strncpy(ret.buf, currUser->real_name, sizeof(currUser->real_name));
         strcat(ret.buf, " has left the room.");
         ret.timestamp = time(NULL);
         send_message(&ret, -1);
         memset(&ret, 0, sizeof(ret));

         ret.options = newRoom->ID;
         strcpy(ret.realname, SERVER_NAME);
         strcpy(ret.username, SERVER_NAME);
         strncpy(ret.buf, currUser->real_name, sizeof(currUser->real_name));
         strcat(ret.buf, " has joined the room.");
         ret.timestamp = time(NULL);
         send_message(&ret, -1);
      }
   }
   else {
      printf("Problem in join.\n");
      sendError("We were unable to put you in that room, sorry.", fd);
   }
}
struct if_options *
read_config(const char *file,
    const char *ifname, const char *ssid, const char *profile)
{
	struct if_options *ifo;
	FILE *f;
	char *line, *option, *p, *platform;
	int skip = 0, have_profile = 0;
	struct utsname utn;

	/* Seed our default options */
	ifo = xzalloc(sizeof(*ifo));
	ifo->options |= DHCPCD_GATEWAY | DHCPCD_DAEMONISE | DHCPCD_LINK;
	ifo->options |= DHCPCD_ARP | DHCPCD_IPV4LL;
	ifo->options |= DHCPCD_IPV6RS | DHCPCD_IPV6RA_REQRDNSS;
	ifo->timeout = DEFAULT_TIMEOUT;
	ifo->reboot = DEFAULT_REBOOT;
	ifo->metric = -1;
	strlcpy(ifo->script, SCRIPT, sizeof(ifo->script));
	gethostname(ifo->hostname, HOSTNAME_MAX_LEN);
	/* Ensure that the hostname is NULL terminated */
	ifo->hostname[HOSTNAME_MAX_LEN] = '\0';
	if (strcmp(ifo->hostname, "(none)") == 0 ||
	    strcmp(ifo->hostname, "localhost") == 0)
		ifo->hostname[0] = '\0';

	platform = hardware_platform();
#ifndef ANDROID
	if (uname(&utn) == 0)
		ifo->vendorclassid[0] = snprintf((char *)ifo->vendorclassid + 1,
		    VENDORCLASSID_MAX_LEN,
	            "%s-%s:%s-%s:%s%s%s", PACKAGE, VERSION,
		    utn.sysname, utn.release, utn.machine,
		    platform ? ":" : "", platform ? platform : "");
	else
#endif
		ifo->vendorclassid[0] = snprintf((char *)ifo->vendorclassid + 1,
		    VENDORCLASSID_MAX_LEN, "%s-%s", PACKAGE, VERSION);

	/* Parse our options file */
	f = fopen(file ? file : CONFIG, "r");
	if (f == NULL) {
		if (file != NULL)
			syslog(LOG_ERR, "fopen `%s': %m", file);
		return ifo;
	}

	while ((line = get_line(f))) {
		option = strsep(&line, " \t");
		/* Trim trailing whitespace */
		if (line && *line) {
			p = line + strlen(line) - 1;
			while (p != line &&
			    (*p == ' ' || *p == '\t') &&
			    *(p - 1) != '\\')
				*p-- = '\0';
		}
		/* Start of an interface block, skip if not ours */
		if (strcmp(option, "interface") == 0) {
			if (ifname && line && strcmp(line, ifname) == 0)
				skip = 0;
			else
				skip = 1;
			continue;
		}
		/* Start of an ssid block, skip if not ours */
		if (strcmp(option, "ssid") == 0) {
			if (ssid && line && strcmp(line, ssid) == 0)
				skip = 0;
			else
				skip = 1;
			continue;
		}
		/* Start of a profile block, skip if not ours */
		if (strcmp(option, "profile") == 0) {
			if (profile && line && strcmp(line, profile) == 0) {
				skip = 0;
				have_profile = 1;
			} else
				skip = 1;
			continue;
		}
		if (skip)
			continue;
		parse_config_line(ifo, option, line);
	}
	fclose(f);

	if (profile && !have_profile) {
		free_options(ifo);
		errno = ENOENT;
		ifo = NULL;
	}

	/* Terminate the encapsulated options */
	if (ifo && ifo->vendor[0] && !(ifo->options & DHCPCD_VENDORRAW)) {
		ifo->vendor[0]++;
		ifo->vendor[ifo->vendor[0]] = DHO_END;
	}
	return ifo;
}
Example #9
0
/* @internal
 * @brief During gateway restart, connects to the parent process via the internal socket
 * Downloads from it the active client list
 */
void get_clients_from_parent(void) {
	int sock;
	struct sockaddr_un	sa_un;
	s_config * config = NULL;
	char linebuffer[MAX_BUF];
	int len = 0;
	char *running1 = NULL;
	char *running2 = NULL;
	char *token1 = NULL;
	char *token2 = NULL;
	char onechar;
	char *command = NULL;
	char *key = NULL;
	char *value = NULL;
	t_client * client = NULL;
	t_client * lastclient = NULL;

	config = config_get_config();

	debug(LOG_INFO, "Connecting to parent to download clients");

	/* Connect to socket */
	sock = socket(AF_UNIX, SOCK_STREAM, 0);
	memset(&sa_un, 0, sizeof(sa_un));
	sa_un.sun_family = AF_UNIX;
	strncpy(sa_un.sun_path, config->internal_sock, (sizeof(sa_un.sun_path) - 1));

	if (connect(sock, (struct sockaddr *)&sa_un, strlen(sa_un.sun_path) + sizeof(sa_un.sun_family))) {
		debug(LOG_ERR, "Failed to connect to parent (%s) - client list not downloaded", strerror(errno));
		return;
	}

	debug(LOG_INFO, "Connected to parent.  Downloading clients");

	LOCK_CLIENT_LIST();

	command = NULL;
	memset(linebuffer, 0, sizeof(linebuffer));
	len = 0;
	client = NULL;
	/* Get line by line */
	while (read(sock, &onechar, 1) == 1) {
		if (onechar == '\n') {
			/* End of line */
			onechar = '\0';
		}
		linebuffer[len++] = onechar;

		if (!onechar) {
			/* We have a complete entry in linebuffer - parse it */
			debug(LOG_DEBUG, "Received from parent: [%s]", linebuffer);
			running1 = linebuffer;
			while ((token1 = strsep(&running1, "|")) != NULL) {
				if (!command) {
					/* The first token is the command */
					command = token1;
				}
				else {
				/* Token1 has something like "foo=bar" */
					running2 = token1;
					key = value = NULL;
					while ((token2 = strsep(&running2, "=")) != NULL) {
						if (!key) {
							key = token2;
						}
						else if (!value) {
							value = token2;
						}
					}
				}

				if (strcmp(command, "CLIENT") == 0) {
					/* This line has info about a client in the client list */
					if (!client) {
						/* Create a new client struct */
						client = safe_malloc(sizeof(t_client));
						memset(client, 0, sizeof(t_client));
					}
				}

				if (key && value) {
					if (strcmp(command, "CLIENT") == 0) {
						/* Assign the key into the appropriate slot in the connection structure */
						if (strcmp(key, "ip") == 0) {
							client->ip = safe_strdup(value);
						}
						else if (strcmp(key, "mac") == 0) {
							client->mac = safe_strdup(value);
						}
						else if (strcmp(key, "token") == 0) {
							client->token = safe_strdup(value);
						}
						else if (strcmp(key, "fw_connection_state") == 0) {
							client->fw_connection_state = atoi(value);
						}
						else if (strcmp(key, "fd") == 0) {
							client->fd = atoi(value);
						}
						else if (strcmp(key, "counters_incoming") == 0) {
							client->counters.incoming_history = atoll(value);
							client->counters.incoming = client->counters.incoming_history;
						}
						else if (strcmp(key, "counters_outgoing") == 0) {
							client->counters.outgoing_history = atoll(value);
							client->counters.outgoing = client->counters.outgoing_history;
						}
						else if (strcmp(key, "counters_last_updated") == 0) {
							client->counters.last_updated = atol(value);
						}
						else {
							debug(LOG_NOTICE, "I don't know how to inherit key [%s] value [%s] from parent", key, value);
						}
					}
				}
			}

			/* End of parsing this command */
			if (client) {
				/* Add this client to the client list */
				if (!firstclient) {
					firstclient = client;
					lastclient = firstclient;
				}
				else {
					lastclient->next = client;
					lastclient = client;
				}
			}

			/* Clean up */
			command = NULL;
			memset(linebuffer, 0, sizeof(linebuffer));
			len = 0;
			client = NULL;
		}
	}

	UNLOCK_CLIENT_LIST();
	debug(LOG_INFO, "Client list downloaded successfully from parent");

	close(sock);
}
Example #10
0
/**
* 입력된 한 줄을 파싱하는 함수입니다. 오류가 있으면 1을 반환합니다.
*/
int parse_string(int line_index)
{
	char * copied_string = NULL; //strsep함수를 사용하기위해서는 내용이 변해도 문제없는 문자열이 필요합니다. 이를 위해 strdup함수를 이용해서 문자열을 복제할 것입니다.
	char * seperated_string = NULL; //strsep함수로 분리된 문자열은 여기에 저장됩니다. 이후에 값을 parse_str_array의 원소에 저장할 것입니다.
	char * delimiter = " "; //구분자 변수입니다.
	
	int check_result = 0; //파싱후의 구문을 검사한 결과 값입니다.
	
	copied_string = strdup(input_string_array[line_index]);
	remove_string_space(copied_string);

	//형식에 맞는지 검사합니다. 형식은 ' '가 3개 있는 형태여야합니다.
	if (letter_cnt(input_string_array[line_index],*delimiter) != 3)
	{
		fprintf(stderr,"invalid format in line %d, ignored\n",line_index + 1);
	}
	
	seperated_string = strsep(&copied_string, delimiter);
	remove_string_space(seperated_string);
	if ((check_result = check_id(seperated_string))) //먼저 id의 형식이 맞는지 확인합니다. 문제가 있으면 if는 참입니다.
	{
		if (check_result == 1)
			fprintf(stderr,"invalid process id ‘%s’ in line %d, ignored\n",seperated_string, line_index + 1);
		else if (check_result == 2)
			fprintf(stderr,"duplicate process id ‘%s’ in line %d, ignored\n",seperated_string,line_index + 1);
		parsed_str_array[line_index].program_id[0] = '#'; //오류가 있는 칸임을 알리는 값으로 id의 맨 앞을 #으로 지정합니다.
		return 1;
	}
	
	//문제가 없으면 id를 구조체에 저장합니다.
	strcpy(parsed_str_array[line_index].program_id,seperated_string);
	
	seperated_string = strsep(&copied_string,delimiter);
	remove_string_space(seperated_string);
	
	if (check_arrive_time(seperated_string))
	{
		fprintf(stderr,"invalid arrive-time ‘%s’ in line %d, ignored\n",seperated_string, line_index + 1);
		parsed_str_array[line_index].program_id[0] = '#'; //오류가 있는 칸임을 알리는 값으로 id의 맨 앞을 #으로 지정합니다.
		return 1;
	}
	
	parsed_str_array[line_index].arrive_time = atoi(seperated_string);
	
	seperated_string = strsep(&copied_string,delimiter);
	remove_string_space(seperated_string);
	if (check_service_time(seperated_string))
	{
		fprintf(stderr,"invalid service-time ‘%s’ in line %d, ignored\n",seperated_string, line_index + 1);
		parsed_str_array[line_index].program_id[0] = '#'; //오류가 있는 칸임을 알리는 값으로 id의 맨 앞을 #으로 지정합니다.
		return 1;
	}
	
	parsed_str_array[line_index].service_time = atoi(seperated_string);
	parsed_str_array[line_index].remain_time = parsed_str_array[line_index].service_time;
	
	seperated_string = strsep(&copied_string,delimiter);
	remove_string_space(seperated_string);
	if (check_priority(seperated_string))
	{
		fprintf(stderr,"invalid priority ‘%s’ in line %d, ignored\n",seperated_string, line_index + 1);
		parsed_str_array[line_index].program_id[0] = '#'; //오류가 있는 칸임을 알리는 값으로 id의 맨 앞을 #으로 지정합니다.
		return 1;
	}
	
	parsed_str_array[line_index].priority = atoi(seperated_string);
	
	
	correct_process_many++;
	last_process_index = line_index;
	
	return 0;
}
Example #11
0
void
mangle(char *options, struct cpa *a)
{
	char *p, *s, *val;

	for (s = options; (p = strsep(&s, ",")) != NULL;)
		if (*p != '\0') {
			if (strcmp(p, "noauto") == 0) {
				/*
				 * Do not pass noauto option to nmount().
				 * or external mount program.  noauto is
				 * only used to prevent mounting a filesystem
				 * when 'mount -a' is specified, and is
				 * not a real mount option.
				 */
				continue;
			} else if (strcmp(p, "late") == 0) {
				/*
				 * "late" is used to prevent certain file
				 * systems from being mounted before late
				 * in the boot cycle; for instance,
				 * loopback NFS mounts can't be mounted
				 * before mountd starts.
				 */
				continue;
			} else if (strcmp(p, "failok") == 0) {
				/*
				 * "failok" is used to prevent certain file
				 * systems from being causing the system to
				 * drop into single user mode in the boot
				 * cycle, and is not a real mount option.
				 */
				continue;
			} else if (strncmp(p, "mountprog", 9) == 0) {
				/*
				 * "mountprog" is used to force the use of
				 * userland mount programs.
				 */
				val = strchr(p, '=');
                        	if (val != NULL) {
                                	++val;
					if (*val != '\0')
						mountprog = strdup(val);
				}

				if (mountprog == NULL) {
					errx(1, "Need value for -o mountprog");
				}
				continue;
			} else if (strcmp(p, "userquota") == 0) {
				continue;
			} else if (strncmp(p, userquotaeq,
			    sizeof(userquotaeq) - 1) == 0) {
				continue;
			} else if (strcmp(p, "groupquota") == 0) {
				continue;
			} else if (strncmp(p, groupquotaeq,
			    sizeof(groupquotaeq) - 1) == 0) {
				continue;
			} else if (*p == '-') {
				append_arg(a, p);
				p = strchr(p, '=');
				if (p != NULL) {
					*p = '\0';
					append_arg(a, p + 1);
				}
			} else {
				append_arg(a, strdup("-o"));
				append_arg(a, p);
			}
		}
}
Example #12
0
static int parse_options(char *options, int *pipefd, uid_t *uid, gid_t *gid,
			 pid_t *pgrp, unsigned int *type,
			 int *minproto, int *maxproto)
{
	char *p;
	substring_t args[MAX_OPT_ARGS];
	int option;

	*uid = current->uid;
	*gid = current->gid;
	*pgrp = process_group(current);

	*minproto = AUTOFS_MIN_PROTO_VERSION;
	*maxproto = AUTOFS_MAX_PROTO_VERSION;

	*pipefd = -1;

	if (!options)
		return 1;

	while ((p = strsep(&options, ",")) != NULL) {
		int token;
		if (!*p)
			continue;

		token = match_token(p, tokens, args);
		switch (token) {
		case Opt_fd:
			if (match_int(args, pipefd))
				return 1;
			break;
		case Opt_uid:
			if (match_int(args, &option))
				return 1;
			*uid = option;
			break;
		case Opt_gid:
			if (match_int(args, &option))
				return 1;
			*gid = option;
			break;
		case Opt_pgrp:
			if (match_int(args, &option))
				return 1;
			*pgrp = option;
			break;
		case Opt_minproto:
			if (match_int(args, &option))
				return 1;
			*minproto = option;
			break;
		case Opt_maxproto:
			if (match_int(args, &option))
				return 1;
			*maxproto = option;
			break;
		case Opt_indirect:
			*type = AUTOFS_TYPE_INDIRECT;
			break;
		case Opt_direct:
			*type = AUTOFS_TYPE_DIRECT;
			break;
		case Opt_offset:
			*type = AUTOFS_TYPE_OFFSET;
			break;
		default:
			return 1;
		}
	}
	return (*pipefd < 0);
}
Example #13
0
int
main(int argc, char *argv[])
{
	struct stat	 sb;
	struct timeval	 start;
	fstype_t	*fstype;
	fsinfo_t	 fsoptions;
	fsnode		*root;
	int	 	 ch, i, len;
	const char	*subtree;
	const char	*specfile;

	setprogname(argv[0]);

	debug = 0;
	if ((fstype = get_fstype(DEFAULT_FSTYPE)) == NULL)
		errx(1, "Unknown default fs type `%s'.", DEFAULT_FSTYPE);

		/* set default fsoptions */
	(void)memset(&fsoptions, 0, sizeof(fsoptions));
	fsoptions.fd = -1;
	fsoptions.sectorsize = -1;

	if (fstype->prepare_options)
		fstype->prepare_options(&fsoptions);

	specfile = NULL;
#ifdef CLOCK_REALTIME
	ch = clock_gettime(CLOCK_REALTIME, &start_time);
#else
	ch = gettimeofday(&start, NULL);
	start_time.tv_sec = start.tv_sec;
	start_time.tv_nsec = start.tv_usec * 1000;
#endif
	if (ch == -1)
		err(1, "Unable to get system time");


	while ((ch = getopt(argc, argv, "B:b:Dd:f:F:M:m:N:O:o:pR:s:S:t:T:xZ")) != -1) {
		switch (ch) {

		case 'B':
			if (strcmp(optarg, "be") == 0 ||
			    strcmp(optarg, "4321") == 0 ||
			    strcmp(optarg, "big") == 0) {
#if BYTE_ORDER == LITTLE_ENDIAN
				fsoptions.needswap = 1;
#endif
			} else if (strcmp(optarg, "le") == 0 ||
			    strcmp(optarg, "1234") == 0 ||
			    strcmp(optarg, "little") == 0) {
#if BYTE_ORDER == BIG_ENDIAN
				fsoptions.needswap = 1;
#endif
			} else {
				warnx("Invalid endian `%s'.", optarg);
				usage(fstype, &fsoptions);
			}
			break;

		case 'b':
			len = strlen(optarg) - 1;
			if (optarg[len] == '%') {
				optarg[len] = '\0';
				fsoptions.freeblockpc =
				    strsuftoll("free block percentage",
					optarg, 0, 99);
			} else {
				fsoptions.freeblocks =
				    strsuftoll("free blocks",
					optarg, 0, LLONG_MAX);
			}
			break;

		case 'D':
			dupsok = 1;
			break;

		case 'd':
			debug = strtoll(optarg, NULL, 0);
			break;

		case 'f':
			len = strlen(optarg) - 1;
			if (optarg[len] == '%') {
				optarg[len] = '\0';
				fsoptions.freefilepc =
				    strsuftoll("free file percentage",
					optarg, 0, 99);
			} else {
				fsoptions.freefiles =
				    strsuftoll("free files",
					optarg, 0, LLONG_MAX);
			}
			break;

		case 'F':
			specfile = optarg;
			break;

		case 'M':
			fsoptions.minsize =
			    strsuftoll("minimum size", optarg, 1LL, LLONG_MAX);
			break;

		case 'N':
			if (! setup_getid(optarg))
				errx(1,
			    "Unable to use user and group databases in `%s'",
				    optarg);
			break;

		case 'm':
			fsoptions.maxsize =
			    strsuftoll("maximum size", optarg, 1LL, LLONG_MAX);
			break;

		case 'O':
			fsoptions.offset =
			    strsuftoll("offset", optarg, 0LL, LLONG_MAX);
			break;

		case 'o':
		{
			char *p;

			while ((p = strsep(&optarg, ",")) != NULL) {
				if (*p == '\0')
					errx(1, "Empty option");
				if (! fstype->parse_options(p, &fsoptions))
					usage(fstype, &fsoptions);
			}
			break;
		}
		case 'p':
			/* Deprecated in favor of 'Z' */
			fsoptions.sparse = 1;
			break;

		case 'R':
			/* Round image size up to specified block size */
			fsoptions.roundup =
			    strsuftoll("roundup-size", optarg, 0, LLONG_MAX);
			break;

		case 's':
			fsoptions.minsize = fsoptions.maxsize =
			    strsuftoll("size", optarg, 1LL, LLONG_MAX);
			break;

		case 'S':
			fsoptions.sectorsize =
			    (int)strsuftoll("sector size", optarg,
				1LL, INT_MAX);
			break;

		case 't':
			/* Check current one and cleanup if necessary. */
			if (fstype->cleanup_options)
				fstype->cleanup_options(&fsoptions);
			fsoptions.fs_specific = NULL;
			if ((fstype = get_fstype(optarg)) == NULL)
				errx(1, "Unknown fs type `%s'.", optarg);
			fstype->prepare_options(&fsoptions);
			break;

		case 'T':
			if (get_tstamp(optarg, &stampst) == -1)
				errx(1, "Cannot get timestamp from `%s'",
				    optarg);
			break;

		case 'x':
			fsoptions.onlyspec = 1;
			break;

		case 'Z':
			/* Superscedes 'p' for compatibility with NetBSD makefs(8) */
			fsoptions.sparse = 1;
			break;

		case '?':
		default:
			usage(fstype, &fsoptions);
			/* NOTREACHED */

		}
	}
	if (debug) {
		printf("debug mask: 0x%08x\n", debug);
		printf("start time: %ld.%ld, %s",
		    (long)start_time.tv_sec, (long)start_time.tv_nsec,
		    ctime(&start_time.tv_sec));
	}
	argc -= optind;
	argv += optind;

	if (argc < 2)
		usage(fstype, &fsoptions);

	/* -x must be accompanied by -F */
	if (fsoptions.onlyspec != 0 && specfile == NULL)
		errx(1, "-x requires -F mtree-specfile.");

	/* Accept '-' as meaning "read from standard input". */
	if (strcmp(argv[1], "-") == 0)
		sb.st_mode = S_IFREG;
	else {
		if (stat(argv[1], &sb) == -1)
			err(1, "Can't stat `%s'", argv[1]);
	}

	switch (sb.st_mode & S_IFMT) {
	case S_IFDIR:		/* walk the tree */
		subtree = argv[1];
		TIMER_START(start);
		root = walk_dir(subtree, ".", NULL, NULL);
		TIMER_RESULTS(start, "walk_dir");
		break;
	case S_IFREG:		/* read the manifest file */
		subtree = ".";
		TIMER_START(start);
		root = read_mtree(argv[1], NULL);
		TIMER_RESULTS(start, "manifest");
		break;
	default:
		errx(1, "%s: not a file or directory", argv[1]);
		/* NOTREACHED */
	}

	/* append extra directory */
	for (i = 2; i < argc; i++) {
		if (stat(argv[i], &sb) == -1)
			err(1, "Can't stat `%s'", argv[i]);
		if (!S_ISDIR(sb.st_mode))
			errx(1, "%s: not a directory", argv[i]);
		TIMER_START(start);
		root = walk_dir(argv[i], ".", NULL, root);
		TIMER_RESULTS(start, "walk_dir2");
	}

	if (specfile) {		/* apply a specfile */
		TIMER_START(start);
		apply_specfile(specfile, subtree, root, fsoptions.onlyspec);
		TIMER_RESULTS(start, "apply_specfile");
	}

	if (debug & DEBUG_DUMP_FSNODES) {
		printf("\nparent: %s\n", subtree);
		dump_fsnodes(root);
		putchar('\n');
	}

				/* build the file system */
	TIMER_START(start);
	fstype->make_fs(argv[0], subtree, root, &fsoptions);
	TIMER_RESULTS(start, "make_fs");

	free_fsnodes(root);

	exit(0);
	/* NOTREACHED */
}
void traduction() {
    element * curseur = affichage;

    char * nomFonction = "";
    char * parametresFonction = "";
    char * typeRetourFonction = "";

    int declaration_variables = 0;
    int est_fonction = 0;
    int est_procedure = 0;
    int est_main = 0;

    curseur = curseur->nxt;
    printf("#include <stdio.h>\n\n");
    while(curseur != NULL)
    {

        char * duplicata = strdup(curseur->code);
        char * tokens = strsep(&duplicata, " ");

        if (declaration_variables == 0) {
            if (strcmp("function", tokens) == 0) {
                nomFonction = strsep(&duplicata, " ");
                est_fonction = 1;
            } else if (strcmp("procedure", tokens) == 0) {
                nomFonction = strsep(&duplicata, " ");
                typeRetourFonction = "void";
                printf("%s %s ()\n{\n",typeRetourFonction,nomFonction);
                est_fonction = 1;
            } else if (strcmp("appel_procedure", tokens) == 0) {
                char * nomProcedure = strsep(&duplicata, " ");
                printf("%s ();\n",nomProcedure);
                est_fonction = 1;
            } else if (strcmp("fin_fonction", tokens) == 0) {
                printf("\n");
                est_fonction = 0;
            } else if (strcmp("fin_procedure", tokens) == 0) {
                printf("\n");
                est_fonction = 0;
            } else if (strcmp("param", tokens) == 0) {
                char * variables = strsep(&duplicata, ":");
                char * type = strsep(&duplicata, ":");
                char * dupvar = strdup(variables);
                char * token = strsep(&dupvar, ",");
                int nbParam = 0;
                while(token != NULL) {
                    if (nbParam == 0) {
                        char * unParametre = concat_trois_chaines(conversionType(type)," ",token);
                        parametresFonction = concat_deux_chaines(parametresFonction,unParametre); 
                        nbParam++;
                    } else {
                        char * unParametre = concat_trois_chaines(conversionType(type)," ",token);
                        parametresFonction = concat_trois_chaines(parametresFonction,",",unParametre); 
                        nbParam++;
                    }
                    
                    token = strsep(&dupvar, ",");
                }
            } else if (strcmp("type_return", tokens) == 0) {
                typeRetourFonction = conversionType(strsep(&duplicata, " "));
            } else if (strcmp("fin_declaration", tokens) == 0) {
                printf("%s %s (%s) \n{\n",typeRetourFonction,nomFonction,parametresFonction);
            } else if (strcmp("declaration_variables", tokens) == 0) {
                if (est_fonction == 0) {
                    printf("int main()\n{\n");
                    est_main = 1;
                }
                declaration_variables = 1;
            } else if (strcmp("begin", tokens) == 0) {
                // DEBUT D'UN BLOC
            } else if (strcmp("end", tokens) == 0) {
                // FIN D'UN BLOC
                if (est_main == 1) {
                    printf("return 0;\n");
                }
                printf("}\n");
            } else if (strcmp("else", tokens) == 0) {
                // FIN D'UN BLOC
                printf("else\n{\n");
            } else if (strcmp("if", tokens) == 0) {
                char * condition = strsep(&duplicata, " ");
                printf("if (%s) \n{\n",condition);
            } else if (strcmp("while", tokens) == 0) {
                char * condition = strsep(&duplicata, " ");
                printf("while (%s) \n{\n",condition);
            } else if (strcmp("assignation", tokens) == 0) {
                char * assignation = strsep(&duplicata, " ");
                char * partie_gauche = strdup(assignation);
                partie_gauche = strsep(&partie_gauche, ":=");
                if (strcmp(partie_gauche,nomFonction) == 0) {
                    char * partie_droite = strdup(assignation);
                    strsep(&partie_droite,":");
                    strsep(&partie_droite,"=");
                    partie_droite = replace_str(partie_droite, "'", "\"");
                    assignation = replace_str(assignation, "'", "\"");
                    printf("return %s;\n",partie_droite);
                } else {
                    assignation = replace_str(assignation, ":=", " = ");
                    assignation = replace_str(assignation, "'", "\"");
                    assignation = replace_str(assignation, "'", "\"");
                    assignation = concat_deux_chaines(assignation,";");
                    printf("%s\n",assignation);
                }
            } else if (strcmp("affichage", tokens) == 0) {
                char * affichage = strsep(&duplicata, " ");
                strsep(&affichage,"w");
                strsep(&affichage,"r");
                strsep(&affichage,"i");
                strsep(&affichage,"t");
                strsep(&affichage,"e");
                strsep(&affichage,"l");
                strsep(&affichage,"n");
                strsep(&affichage,"(");
                char * temporaire = malloc(256);
                temporaire = strncpy(temporaire,affichage,1);
                if (strcmp(temporaire,"'") == 0) {
                    printf("printf(\"%%s\\n\",");
                    affichage = replace_str(affichage, "'", "\"");
                    affichage = replace_str(affichage, "'", "\"");
                    printf("%s;\n",affichage);
                } else {
                    printf("printf(\"%%d\\n\",");
                    printf("%s;\n",affichage);
                }
            } else {
                printf("\nERREUR : %s\n",curseur->code);
            }
        } else {
            // Mode déclaration de variables;

            char * types = strsep(&tokens, ";");

            while (types != NULL) {
                char * variables = strsep(&types, ":");
                char * type = strsep(&types, ":");
                printf("%s;\n",concat_trois_chaines(conversionType(type)," ",variables));
                types = strsep(&tokens, ";");
            }

            declaration_variables = 0;
        }
        

        curseur = curseur->nxt;
    }
}
Example #15
0
/* Line oriented parser that extracts tokens from the shared
 * parse_buffer.
 *
 * FIXME: Add callback mechanism to actually act on commands and preset ids.
 */
static int parse(void *cb_ctx)
{
	char *cur, *tok;
	u16 w;
	u32 cmd;
	int err;
	int id;

	cur = parse_buffer;
	cmd = 0;
	err = 0;
	while ((tok = strsep(&cur, " \t\r\n")) != cur) {
		/* Comments extend to eol. */
		if (*tok == ';') {
			while (*cur != 0 && *cur != '\n')
				cur++;
			continue;
		}

		switch (last_token) {
		case PT_NIL:
			if (*tok == '0' &&
			    sscanf(tok, "0x%hx", &w) == 1) {
				last_token = PT_HEXWORD;
				cmd = w << 16;
			} else if (strnicmp("!Preset", tok, 7) == 0) {
				last_token = PT_PRESET;
			} else if (*tok != 0) {
				pr_debug("invalid token: '%s'", tok);
				err = -EINVAL;
				goto EXIT;
			}
			break;
		case PT_PRESET:
			if (strnicmp(tok, "id:", 3) == 0) {
				last_token = PT_ID;
			} else {
				pr_debug("expecting 'id:' got '%s'\n", tok);
				err = -EINVAL;
				goto EXIT;
			}
			break;
		case PT_ID:
			if (sscanf(tok, "%d", &id) == 1) {
				parse_cb_preset(cb_ctx, id);
				last_token = PT_NIL;
			} else {
				pr_debug("expecting preset id: got '%s'\n",
					 tok);
				err = -EINVAL;
				goto EXIT;
			}
			break;
		case PT_HEXWORD:
			if (last_token == PT_HEXWORD &&
			    sscanf(tok, "0x%hx", &w) == 1) {
				parse_cb_cmd(cb_ctx, cmd | w);
				last_token = PT_NIL;
			} else {
				pr_debug("expecting hex word: got '%s'\n",
					 tok);
				err = -EINVAL;
				goto EXIT;
			}
			break;
		}
	}

EXIT:
	return err;
}
Example #16
0
/*
 * parse the dirs= mount argument
 *
 * We don't need to lock the superblock private data's rwsem, as we get
 * called only by unionfs_read_super - it is still a long time before anyone
 * can even get a reference to us.
 */
static int parse_dirs_option(struct super_block *sb, struct unionfs_dentry_info
			     *lower_root_info, char *options)
{
	struct nameidata nd;
	char *name;
	int err = 0;
	int branches = 1;
	int bindex = 0;
	int i = 0;
	int j = 0;
	struct dentry *dent1;
	struct dentry *dent2;

	if (options[0] == '\0') {
		printk(KERN_ERR "unionfs: no branches specified\n");
		err = -EINVAL;
		goto out_return;
	}

	/*
	 * Each colon means we have a separator, this is really just a rough
	 * guess, since strsep will handle empty fields for us.
	 */
	for (i = 0; options[i]; i++)
		if (options[i] == ':')
			branches++;

	/* allocate space for underlying pointers to lower dentry */
	UNIONFS_SB(sb)->data =
		kcalloc(branches, sizeof(struct unionfs_data), GFP_KERNEL);
	if (unlikely(!UNIONFS_SB(sb)->data)) {
		err = -ENOMEM;
		goto out_return;
	}

	lower_root_info->lower_paths =
		kcalloc(branches, sizeof(struct path), GFP_KERNEL);
	if (unlikely(!lower_root_info->lower_paths)) {
		err = -ENOMEM;
		/* free the underlying pointer array */
		kfree(UNIONFS_SB(sb)->data);
		UNIONFS_SB(sb)->data = NULL;
		goto out_return;
	}

	/* now parsing a string such as "b1:b2=rw:b3=ro:b4" */
	branches = 0;
	while ((name = strsep(&options, ":")) != NULL) {
		int perms;
		char *mode = strchr(name, '=');

		if (!name)
			continue;
		if (!*name) {	/* bad use of ':' (extra colons) */
			err = -EINVAL;
			goto out;
		}

		branches++;

		/* strip off '=' if any */
		if (mode)
			*mode++ = '\0';

		err = parse_branch_mode(mode, &perms);
		if (err) {
			printk(KERN_ERR "unionfs: invalid mode \"%s\" for "
			       "branch %d\n", mode, bindex);
			goto out;
		}
		/* ensure that leftmost branch is writeable */
		if (!bindex && !(perms & MAY_WRITE)) {
			printk(KERN_ERR "unionfs: leftmost branch cannot be "
			       "read-only (use \"-o ro\" to create a "
			       "read-only union)\n");
			err = -EINVAL;
			goto out;
		}

		err = path_lookup(name, LOOKUP_FOLLOW, &nd);
		if (err) {
			printk(KERN_ERR "unionfs: error accessing "
			       "lower directory '%s' (error %d)\n",
			       name, err);
			goto out;
		}

		err = check_branch(&nd);
		if (err) {
			printk(KERN_ERR "unionfs: lower directory "
			       "'%s' is not a valid branch\n", name);
			path_put(&nd.path);
			goto out;
		}

		lower_root_info->lower_paths[bindex].dentry = nd.path.dentry;
		lower_root_info->lower_paths[bindex].mnt = nd.path.mnt;

		set_branchperms(sb, bindex, perms);
		set_branch_count(sb, bindex, 0);
		new_branch_id(sb, bindex);

		if (lower_root_info->bstart < 0)
			lower_root_info->bstart = bindex;
		lower_root_info->bend = bindex;
		bindex++;
	}

	if (branches == 0) {
		printk(KERN_ERR "unionfs: no branches specified\n");
		err = -EINVAL;
		goto out;
	}

	BUG_ON(branches != (lower_root_info->bend + 1));

	/*
	 * Ensure that no overlaps exist in the branches.
	 *
	 * This test is required because the Linux kernel has no support
	 * currently for ensuring coherency between stackable layers and
	 * branches.  If we were to allow overlapping branches, it would be
	 * possible, for example, to delete a file via one branch, which
	 * would not be reflected in another branch.  Such incoherency could
	 * lead to inconsistencies and even kernel oopses.  Rather than
	 * implement hacks to work around some of these cache-coherency
	 * problems, we prevent branch overlapping, for now.  A complete
	 * solution will involve proper kernel/VFS support for cache
	 * coherency, at which time we could safely remove this
	 * branch-overlapping test.
	 */
	for (i = 0; i < branches; i++) {
		dent1 = lower_root_info->lower_paths[i].dentry;
		for (j = i + 1; j < branches; j++) {
			dent2 = lower_root_info->lower_paths[j].dentry;
			if (is_branch_overlap(dent1, dent2)) {
				printk(KERN_ERR "unionfs: branches %d and "
				       "%d overlap\n", i, j);
				err = -EINVAL;
				goto out;
			}
		}
	}

out:
	if (err) {
		for (i = 0; i < branches; i++)
			path_put(&lower_root_info->lower_paths[i]);

		kfree(lower_root_info->lower_paths);
		kfree(UNIONFS_SB(sb)->data);

		/*
		 * MUST clear the pointers to prevent potential double free if
		 * the caller dies later on
		 */
		lower_root_info->lower_paths = NULL;
		UNIONFS_SB(sb)->data = NULL;
	}
out_return:
	return err;
}
Example #17
0
static int
__ypparse(struct passwd *pw, char *s, int yp_pw_flags)
{
	char *bp, *cp, *endp;
	u_long ul;
	int count = 0;

	/* count the colons. */
	bp = s;
	while (*bp != '\0') {
		if (*bp++ == ':')
			count++;
	}

	/* since this is currently using strsep(), parse it first */
	bp = s;
	pw->pw_name = strsep(&bp, ":\n");
	pw->pw_passwd = strsep(&bp, ":\n");
	if (!(cp = strsep(&bp, ":\n")))
		return (1);
	ul = strtoul(cp, &endp, 10);
	if (endp == cp || *endp != '\0' || ul >= UID_MAX)
		return (1);
	pw->pw_uid = (uid_t)ul;
	if (!(cp = strsep(&bp, ":\n")))
		return (1);
	ul = strtoul(cp, &endp, 10);
	if (endp == cp || *endp != '\0' || ul >= GID_MAX)
		return (1);
	pw->pw_gid = (gid_t)ul;
	if (count == 9) {
		long l;

		/* If the ypserv gave us all the fields, use them. */
		pw->pw_class = strsep(&bp, ":\n");
		if (!(cp = strsep(&bp, ":\n")))
			return (1);
		l = strtol(cp, &endp, 10);
		if (endp == cp || *endp != '\0' || l >= INT_MAX || l <= INT_MIN)
			return (1);
		pw->pw_change = (time_t)l;
		if (!(cp = strsep(&bp, ":\n")))
			return (1);
		l = strtol(cp, &endp, 10);
		if (endp == cp || *endp != '\0' || l >= INT_MAX || l <= INT_MIN)
			return (1);
		pw->pw_expire = (time_t)l;
	} else {
		/* ..else it is a normal ypserv. */
		pw->pw_class = "";
		pw->pw_change = 0;
		pw->pw_expire = 0;
	}
	pw->pw_gecos = strsep(&bp, ":\n");
	pw->pw_dir = strsep(&bp, ":\n");
	pw->pw_shell = strsep(&bp, ":\n");

	/* now let the prototype override, if set. */
	if (__ypproto) {
		if (!(yp_pw_flags & _PASSWORD_NOUID))
			pw->pw_uid = __ypproto->pw_uid;
		if (!(yp_pw_flags & _PASSWORD_NOGID))
			pw->pw_gid = __ypproto->pw_gid;
		if (__ypproto->pw_gecos)
			pw->pw_gecos = __ypproto->pw_gecos;
		if (__ypproto->pw_dir)
			pw->pw_dir = __ypproto->pw_dir;
		if (__ypproto->pw_shell)
			pw->pw_shell = __ypproto->pw_shell;
	}
	return (0);
}
Example #18
0
/*
 * Parse mount options.  See the manual page for usage instructions.
 *
 * Returns the dentry object of the lower-level (lower) directory;
 * We want to mount our stackable file system on top of that lower directory.
 */
static struct unionfs_dentry_info *unionfs_parse_options(
					 struct super_block *sb,
					 char *options)
{
	struct unionfs_dentry_info *lower_root_info;
	char *optname;
	int err = 0;
	int bindex;
	int dirsfound = 0;

	/* allocate private data area */
	err = -ENOMEM;
	lower_root_info =
		kzalloc(sizeof(struct unionfs_dentry_info), GFP_KERNEL);
	if (unlikely(!lower_root_info))
		goto out_error;
	lower_root_info->bstart = -1;
	lower_root_info->bend = -1;
	lower_root_info->bopaque = -1;

	while ((optname = strsep(&options, ",")) != NULL) {
		char *optarg;

		if (!optname || !*optname)
			continue;

		optarg = strchr(optname, '=');
		if (optarg)
			*optarg++ = '\0';

		/*
		 * All of our options take an argument now. Insert ones that
		 * don't, above this check.
		 */
		if (!optarg) {
			printk(KERN_ERR "unionfs: %s requires an argument\n",
			       optname);
			err = -EINVAL;
			goto out_error;
		}

		if (!strcmp("dirs", optname)) {
			if (++dirsfound > 1) {
				printk(KERN_ERR
				       "unionfs: multiple dirs specified\n");
				err = -EINVAL;
				goto out_error;
			}
			err = parse_dirs_option(sb, lower_root_info, optarg);
			if (err)
				goto out_error;
			continue;
		}

		err = -EINVAL;
		printk(KERN_ERR
		       "unionfs: unrecognized option '%s'\n", optname);
		goto out_error;
	}
	if (dirsfound != 1) {
		printk(KERN_ERR "unionfs: dirs option required\n");
		err = -EINVAL;
		goto out_error;
	}
	goto out;

out_error:
	if (lower_root_info && lower_root_info->lower_paths) {
		for (bindex = lower_root_info->bstart;
		     bindex >= 0 && bindex <= lower_root_info->bend;
		     bindex++)
			path_put(&lower_root_info->lower_paths[bindex]);
	}

	kfree(lower_root_info->lower_paths);
	kfree(lower_root_info);

	kfree(UNIONFS_SB(sb)->data);
	UNIONFS_SB(sb)->data = NULL;

	lower_root_info = ERR_PTR(err);
out:
	return lower_root_info;
}
Example #19
0
/*
 *Login
 */
int login(packet *pkt, int fd) {
   int i = 0;
   char *args[16];
   char cpy[BUFFERSIZE];
   char *tmp = cpy;
   unsigned char *arg_pass_hash = (unsigned char *)malloc(SHA256_DIGEST);
   strcpy(tmp, pkt->buf);

   args[i] = strsep(&tmp, " \t");
   while ((i < sizeof(args) - 1) && (args[i] != '\0')) {
       args[++i] = strsep(&tmp, " \t");
   }
   // Check there are enough arguements to safely inspect them
   if (i > 2) {
      packet ret;
      // Check if user exists as registered user
      if (strcmp(get_real_name(&registered_users_list, args[1], registered_users_mutex), "ERROR") == 0) {
         sendError("Username not found.", fd);
         return 0;
      }
      // Retreive password for requested user
      unsigned char *password = get_password(&registered_users_list, args[1], registered_users_mutex);
      // Hash login password arg
      SHA256_CTX sha256;
      SHA256_Init(&sha256);
      SHA256_Update(&sha256, args[2], strlen(args[2]));
      SHA256_Final(arg_pass_hash, &sha256);

      // Compare pass arg and stored pass
      if (comparePasswords(password, arg_pass_hash, 32) != 0) {
         sendError("Incorrect password.", fd);
         free(arg_pass_hash);
         return 0;
      }
      free(arg_pass_hash);

      // Login input is valid, read user data from registered users
      User *user = get_user(&registered_users_list, args[1], registered_users_mutex);

      //Create node for active users list
      Node *new_usr_act = (Node *)malloc(sizeof(Node));
      new_usr_act->data = (void *)user;
      new_usr_act->next = NULL;

      //Create node for room list
      Node *new_usr_rm = (Node *)malloc(sizeof(Node));
      new_usr_rm->data = (void *)user;
      new_usr_rm->next = NULL;

      // Check if the user is already logged in
      if(insertUser(&active_users_list, user, active_users_mutex) == 1) {
         user->sock = fd;
         user->roomID = 1000;

         // Login successful, add user to default room
         Room *defaultRoom = Rget_roomFID(&room_list, DEFAULT_ROOM, rooms_mutex);
         insertNode(&(defaultRoom->user_list), new_usr_rm, defaultRoom->user_list_mutex);

         // Inform client of successful login
         strcpy(ret.realname, get_real_name(&registered_users_list, args[1], registered_users_mutex));
         strcpy(ret.username, args[1]);
         ret.options = LOGSUC;
         //printf("%s logged in\n", ret.username);
         ret.timestamp = time(NULL);
         send(fd, &ret, sizeof(packet), MSG_NOSIGNAL);

         // Inform lobby of successful login
         memset(&ret, 0, sizeof(packet));
         ret.options = DEFAULT_ROOM;
         strcpy(ret.realname, SERVER_NAME);
         strcpy(ret.username, SERVER_NAME);
         sprintf(ret.buf, "%s has joined the lobby.", user->real_name);
         ret.timestamp = time(NULL);
         send_message(&ret, -1);

         // Send MOTD to client
         sendMOTD(fd);
         return 1;
      }
      // Valid login data received, but user is already in active users
      else {
         sendError("User already logged in.", fd);
         printf("%s log in failed: already logged in", args[1]);
         free(user);
         return 0;
      }
   }
   // Not enough arguements received to properly parse input, ignore it
   else {
      printf("%s --- %sError:%s Malformed login packet received from %s on %d, ignoring.\n", \
             WHITE, RED, NORMAL, args[1], fd);
   }
   return 0;
}
Example #20
0
int main(int argc, char* argv[])
{
	struct sockaddr_in srv_addr;	/* server's socket address */
	struct sockaddr_in clnt_addr;	/* client's socket address */
	socklen_t len;
	int ssd;	/* listening socket descriptor */
	int new_ssd;	/* connected socket descriptor */
	int fd;		/* file descriptor for reading file data */
	char *ptr_buf;	/* ptr to buffer */
	char buf[BUF_SIZE];	/* buffer to hold file data */
	char *in_buf;		/* buffer to hold request from client */
	char *user_token, *file_token, *filename;
	ssize_t in_buf_count;
	size_t count_read;	/* number of bytes read from file */
	ssize_t count_write;	/* number of bytes that must be written to socket */
	ssize_t total;	/* total number of bytes that must be written to socket */
	int optval = 1;	/* specifies that socket address should be reused */
	struct sigaction act, oact; /* structures for various signal actions */

	if (argc != 2) {
		fprintf(stderr, "usage: %s serv_port\n", argv[0]);
		exit(1);
	}

	daemon(0,0);

	/*
	 * Send error information to /var/log/messages for daemon
	 */ 
	openlog(argv[0], LOG_PID, LOG_DAEMON);

	/* create socket */
	if ((ssd = socket(PF_INET, SOCK_STREAM, 0)) == -1 ) {
		syslog(LOG_DAEMON|LOG_CRIT, "Failed to create socket: %m");
		exit(1);
	}
	if (setsockopt(ssd, SOL_SOCKET, SO_REUSEADDR, (void *) &optval, sizeof(optval)) < 0) {
		syslog(LOG_DAEMON|LOG_CRIT, "setsockopt(SO_RUSEADDR) failed: %m");
		exit(2);
	}

	bzero(&srv_addr, sizeof(srv_addr));
	srv_addr.sin_family = AF_INET;
	srv_addr.sin_port = htons(atoi(argv[1]));
	srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	/* bind the address to the socket */
	if (bind(ssd, (struct sockaddr *) &srv_addr, sizeof(srv_addr)) == -1) {
		syslog(LOG_DAEMON|LOG_CRIT, "Error binding server addresses: %m");
		exit(3);
	}

	bzero(&clnt_addr, sizeof(clnt_addr));

	/* set up the server's listening queue */
	if (listen(ssd, 5) == -1) {
		syslog(LOG_DAEMON|LOG_CRIT, "Error establishing backlog: %m");
		exit(4);
	}

	/* ignore the SIGCHLD signal so that zombies
	 * don't develop or are cleaned up.
	 */
	act.sa_handler = SIG_IGN;
	sigemptyset(&act.sa_mask);
	act.sa_flags = SA_NOCLDWAIT;

	if (sigaction(SIGCHLD, &act, &oact) < 0) {
		syslog(LOG_DAEMON|LOG_CRIT, "Error creating the SIGCHLD signal handler: %m");
		exit(5);
	}

	/*
	 * create a concurrent server
	 */
	for (;;) {
		/* accept a new connection */
		if ((new_ssd = accept(ssd, (struct sockaddr *) &clnt_addr, &len)) == -1) {
			syslog(LOG_DAEMON|LOG_CRIT, " Error accepting connection: %m");
			exit(6);
		}

		switch (fork()) {
			case -1:
				{
					/* fork error occurred */
					syslog(LOG_DAEMON|LOG_CRIT, "fork failed: %m");
					exit(7);
					break;
				}

			case 0:
				{
					/* in child process */
					close(ssd); /* close listening socket descriptor */

					if(read(new_ssd, &in_buf_count, 4) < 4) {
						syslog(LOG_DAEMON|LOG_CRIT, "No request read from client: %m");
						exit(8);
					}
					in_buf_count = ntohl(in_buf_count);
					if(in_buf_count < 0) {
						syslog(LOG_DAEMON|LOG_CRIT, "Client Error: %m, %d", in_buf_count);
						exit(9);
					}
					in_buf = malloc(in_buf_count);
					if(!in_buf) {
						syslog(LOG_DAEMON|LOG_CRIT, "Client Error: %m");
						exit(10);

					}
					if(read(new_ssd, in_buf, in_buf_count) < in_buf_count) {
						free(in_buf);
						syslog(LOG_DAEMON|LOG_CRIT, "Client Error: %m couldn't read from stream");
						exit(11);
					}
					user_token = strsep(&in_buf," ");
					file_token = strsep(&in_buf," ");
					
					if(!user_token || !file_token) {
						free(in_buf);
						syslog(LOG_DAEMON|LOG_CRIT, "Client Error: Invalid request string %m");
						exit(12);
					}
					
					asprintf(&filename,"/home/%s/public_ftransfer/%s",user_token,file_token);
					if(!filename) {
						free(in_buf);
						syslog(LOG_DAEMON|LOG_CRIT, "Couldn't form filename from components: %m");
						exit(13);
					}
					/* open the file for reading */
					if ((fd = open(filename, O_RDONLY)) < 0) {
						syslog(LOG_DAEMON|LOG_CRIT, "Unable to open  %s for reading: %m", filename);
						exit(14);
					}

					/*
					 * read file and write data socket; repeat until
					 * all data has been read from the file
					 */
					while ((count_read = read(fd, buf, BUF_SIZE)) > 0) {
						total = count_read;
						ptr_buf = buf;

						while ((count_write = write(new_ssd, ptr_buf, total)) != -1) {
							total -= count_write;
							ptr_buf += count_write;
							if (total == 0)
								break;
						}

						if (count_write == -1) {
							syslog(LOG_DAEMON|LOG_CRIT, "Error writing to socket: %m");
							exit(15);
						}
					}

					/* print a log message */
					syslog(LOG_DAEMON|LOG_INFO, "File Transfer Server: %s was downloaded\n", filename);

					/* clean up */
					close(fd);
					close(new_ssd);
					return(0);
				}
			default:
				{
					/* in parent */
					close(new_ssd); /* close the connected socket descriptor */
					break;
				}
		}	
	} 
}
Example #21
0
/* Remove a user from their current room and move them to lobby */
void leave(packet *pkt, int fd) {
   int i = 0, roomNum;
   char *args[16];
   char *tmp = pkt->buf;
   packet ret;

   // Split command args
   args[i] = strsep(&tmp, " \t");
   while ((i < sizeof(args) - 1) && (args[i] != '\0')) {
      args[++i] = strsep(&tmp, " \t");
   }
   if (i > 1) {
      roomNum = atoi(args[1]);
      // If user is not in the lobby
      if (roomNum != DEFAULT_ROOM) {
         // Get current room information
         Room *currRoom = Rget_roomFID(&room_list, roomNum, rooms_mutex);
         if (currRoom != NULL) {
            // Find users node in room
            User *currUser = get_user(&(currRoom->user_list), pkt->username, currRoom->user_list_mutex);
            if (currUser != NULL) {
               // Remove user from their current room
               removeUser(&(currRoom->user_list), currUser, currRoom->user_list_mutex);

               //Create node to add user back to lobby
               Node *new_node = (Node *)malloc(sizeof(Node));
               new_node->data = currUser;

               // Place user in lobby room
               Room *defaultRoom = Rget_roomFID(&room_list, DEFAULT_ROOM, rooms_mutex);
               currUser->roomID = 1000;
               insertUser(&(defaultRoom->user_list), currUser, defaultRoom->user_list_mutex);

               // Send user leave message to room
               ret.options = roomNum;
               strcpy(ret.realname, SERVER_NAME);
               strcpy(ret.username, SERVER_NAME);
               strncpy(ret.buf, currUser->real_name, sizeof(currUser->real_name));
               strcat(ret.buf, " has left the room.");
               ret.timestamp = time(NULL);
               send_message(&ret, -1);
               memset(&ret, 0, sizeof(ret));

               // Send join success to client
               ret.options = JOINSUC;
               strcpy(ret.realname, SERVER_NAME);
               strcpy(ret.username, SERVER_NAME);
               sprintf(ret.buf, "%s %d", defaultRoom->name, defaultRoom->ID);
               strcat(ret.buf, " has joined the room.");
               ret.timestamp = time(NULL);
               send(fd, (void *)&ret, sizeof(packet), MSG_NOSIGNAL);
               memset(&ret, 0, sizeof(ret));

               // Send join notification to lobby room
               ret.options = defaultRoom->ID;
               strcpy(ret.realname, SERVER_NAME);
               strcpy(ret.username, SERVER_NAME);
               strncpy(ret.buf, currUser->real_name, sizeof(currUser->real_name));
               strcat(ret.buf, " has joined the room.");
               ret.timestamp = time(NULL);
               send_message(&ret, -1);
            }
         }
      }
   }
}
Example #22
0
INT Set_BeaconReq_Proc(
	IN PRTMP_ADAPTER pAd,
	IN PSTRING arg)
{
	INT Loop;
	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;
	UCHAR ifIndex = pObj->ioctl_if;
	UINT Aid = 1;
	UINT ArgIdx;
	PSTRING thisChar;

	RRM_MLME_BCN_REQ_INFO BcnReq;

	ArgIdx = 0;
	NdisZeroMemory(&BcnReq, sizeof(RRM_MLME_BCN_REQ_INFO));

	while ((thisChar = strsep((char **)&arg, "-")) != NULL)
	{
		switch(ArgIdx)
		{
			case 0:	/* Aid. */
				Aid = (UINT8) simple_strtol(thisChar, 0, 16);
				if (!VALID_WCID(Aid))
				{
					DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow sta of Aid(%d)\n", __FUNCTION__, Aid));
					return TRUE;
				}
				break;

			case 1: /* Meausre Duration. */
				BcnReq.MeasureDuration = (UINT8) simple_strtol(thisChar, 0, 10);

			case 2: /* Regulator Class */
				BcnReq.RegulatoryClass = (UINT8) simple_strtol(thisChar, 0, 10);
				break;

			case 3: /* BSSID */
				if(strlen(thisChar) != 17)
				{
					DBGPRINT(RT_DEBUG_ERROR,
						("%s: invalid value BSSID.\n", 	__FUNCTION__));
					return TRUE;
				}

				if(strlen(thisChar) == 17)  /*Mac address acceptable format 01:02:03:04:05:06 length 17 */
				{
					PSTRING value;
					for (Loop=0, value = rstrtok(thisChar,":"); value; value = rstrtok(NULL,":"))
					{
						if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) ) 
							return FALSE;  /*Invalid */

						AtoH(value, &BcnReq.Bssid[Loop++], 1);
					}

					if(Loop != 6)
						return TRUE;
				}
				break;

			case 4: /* SSID */
				BcnReq.pSsid = (PUINT8)thisChar;
				BcnReq.SsidLen = strlen(thisChar);
				break;

			case 5: /* measure channel */
				BcnReq.MeasureCh = (UINT8) simple_strtol(thisChar, 0, 10);
				break;

			case 6: /* measure mode. */
				BcnReq.MeasureMode = (UINT8) simple_strtol(thisChar, 0, 10);
				if (BcnReq.MeasureMode > RRM_BCN_REQ_MODE_BCNTAB)
				{
					DBGPRINT(RT_DEBUG_ERROR,
						("%s: invalid Measure Mode. %d\n", 	__FUNCTION__, BcnReq.MeasureMode));
					return TRUE;
				}
			case 7: /* regulatory class. */
				{
					PSTRING RegClassString;
					int RegClassIdx;

					RegClassIdx = 0;
					while ((RegClassString = strsep((char **)&thisChar, "+")) != NULL)
					{
						BcnReq.ChRepRegulatoryClass[RegClassIdx] =
							(UINT8) simple_strtol(RegClassString, 0, 10);
						RegClassIdx++;
					}
				}
				break;
			
		}
		ArgIdx++;
	}	

	if (ArgIdx < 7 || ArgIdx > 8)
	{
		DBGPRINT(RT_DEBUG_ERROR,
			("%s: invalid args (%d).\n", __FUNCTION__, ArgIdx));
		DBGPRINT(RT_DEBUG_ERROR,
			("eg: iwpriv ra0 set BcnReq=<Aid>-<Duration>-<RegulatoryClass>-<BSSID>-<SSID>-<MeasureCh>-<MeasureMode>-<ChRegClass>\n"));
		return TRUE;
	}

#ifdef RELEASE_EXCLUDE
	DBGPRINT(RT_DEBUG_ERROR, ("%s::Aid = %d\n", __FUNCTION__, Aid));


	DBGPRINT(RT_DEBUG_ERROR, ("%s::Bssid = %02x:%02x:%02x:%02x:%02x:%02x\n",
		__FUNCTION__, BcnReq.Bssid[0], BcnReq.Bssid[1],
		BcnReq.Bssid[2], BcnReq.Bssid[3],
		BcnReq.Bssid[4], BcnReq.Bssid[5]));
	DBGPRINT(RT_DEBUG_ERROR, ("%s::SsidLen = %d\n", __FUNCTION__,
		BcnReq.SsidLen));
	DBGPRINT(RT_DEBUG_ERROR, ("%s::MeasureCh = %d\n", __FUNCTION__,
		BcnReq.MeasureCh));
	DBGPRINT(RT_DEBUG_ERROR, ("%s::RegulatoryDuration=%d\n", __FUNCTION__, BcnReq.MeasureDuration));
	DBGPRINT(RT_DEBUG_ERROR, ("%s::MeasureMode=%d\n", __FUNCTION__, BcnReq.MeasureMode));

	DBGPRINT(RT_DEBUG_ERROR, ("RegulatoryClass="));
	for (ArgIdx=0; ArgIdx<MAX_NUM_OF_REGULATORY_CLASS; ArgIdx++)
	{
		if (BcnReq.ChRepRegulatoryClass[ArgIdx] == 0)
			break;
		DBGPRINT(RT_DEBUG_ERROR, ("%d ", \
		BcnReq.ChRepRegulatoryClass[ArgIdx]));
	}
	DBGPRINT(RT_DEBUG_ERROR, ("\n"));
#endif /* RELEASE_EXCLUDE */

	BcnReq.BcnReqCapFlag.field.ReportCondition = TRUE;
	if (BcnReq.MeasureCh == 255)
		BcnReq.BcnReqCapFlag.field.ChannelRep = TRUE;
	else
		BcnReq.BcnReqCapFlag.field.ChannelRep = FALSE;

	RRM_EnqueueBcnReq(pAd, Aid, ifIndex, &BcnReq);

	return TRUE;
}
Example #23
0
int
main(int argc, char *argv[])
{
        int ch;
        char *dir, *p;
        int status;
        FILE *spec1, *spec2;

        dir = NULL;
        keys = KEYDEFAULT;
        init_patlists();
        spec1 = stdin;
        spec2 = NULL;

        while ((ch = getopt(argc, argv, "cdef:I:iK:k:LnPp:qrs:UuwxX:")) != -1)
                switch((char)ch) {
                case 'c':
                        cflag = 1;
                        break;
                case 'd':
                        dflag = 1;
                        break;
                case 'e':
                        eflag = 1;
                        break;
                case 'f':
                        if (spec1 == stdin) {
                                spec1 = fopen(optarg, "r");
                                if (spec1 == NULL)
                                        err(1, "%s", optarg);
                        } else if (spec2 == NULL) {
                                spec2 = fopen(optarg, "r");
                                if (spec2 == NULL)
                                        err(1, "%s", optarg);
                        } else
                                usage();
                        break;
                case 'I':
                        read_includes_file(optarg);
                        break;
                case 'i':
                        iflag = 1;
                        break;
                case 'K':
                        while ((p = strsep(&optarg, " \t,")) != NULL)
                                if (*p != '\0')
                                        keys |= parsekey(p, NULL);
                        break;
                case 'k':
                        keys = F_TYPE;
                        while ((p = strsep(&optarg, " \t,")) != NULL)
                                if (*p != '\0')
                                        keys |= parsekey(p, NULL);
                        break;
                case 'L':
                        ftsoptions &= ~FTS_PHYSICAL;
                        ftsoptions |= FTS_LOGICAL;
                        break;
                case 'n':
                        nflag = 1;
                        break;
                case 'P':
                        ftsoptions &= ~FTS_LOGICAL;
                        ftsoptions |= FTS_PHYSICAL;
                        break;
                case 'p':
                        dir = optarg;
                        break;
                case 'q':
                        qflag = 1;
                        break;
                case 'r':
                        rflag = 1;
                        break;
                case 's':
                        sflag = 1;
                        crc_total = ~strtoul(optarg, &p, 0);
                        if (*p)
                                errx(1, "illegal seed value -- %s", optarg);
                        break;
                case 'U':
                        Uflag = 1;
                        uflag = 1;
                        break;
                case 'u':
                        uflag = 1;
                        break;
                case 'w':
                        wflag = 1;
                        break;
                case 'x':
                        ftsoptions |= FTS_XDEV;
                        break;
                case 'X':
                        read_excludes_file(optarg);
                        break;
                case '?':
                default:
                        usage();
                }
        argc -= optind;
        argv += optind;

        if (argc)
                usage();

        if (dir && chdir(dir))
                err(1, "%s", dir);

        if ((cflag || sflag) && !getcwd(fullpath, sizeof(fullpath)))
                errx(1, "%s", fullpath);

        if (cflag) {
                cwalk();
                exit(0);
        }
        if (spec2 != NULL)
                status = mtree_specspec(spec1, spec2);
        else
                status = mtree_verifyspec(spec1);
        if (Uflag & (status == MISMATCHEXIT))
                status = 0;
        exit(status);
}
Example #24
0
INT Set_TxStreamMeasureReq_Proc(
	IN PRTMP_ADAPTER pAd,
	IN	PSTRING arg)
{
	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;
	UCHAR ifIndex = pObj->ioctl_if;
	UINT Aid = 1;
	UINT ArgIdx;
	PSTRING thisChar;

	RRM_MLME_TRANSMIT_REQ_INFO TransmitReq;
	PMAC_TABLE_ENTRY pMacEntry;

	ArgIdx = 0;
	NdisZeroMemory(&TransmitReq, sizeof(RRM_MLME_TRANSMIT_REQ_INFO));

	while ((thisChar = strsep((char **)&arg, "-")) != NULL)
	{
		switch(ArgIdx)
		{
			case 0:	/* Aid. */
				Aid = (UINT8) simple_strtol(thisChar, 0, 10);
				if (!VALID_WCID(Aid))
				{
					DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow sta of Aid(%d)\n", __FUNCTION__, Aid));
					return TRUE;
				}
				break;

			case 1: /* DurationMandotory. */
				TransmitReq.bDurationMandatory =
					((UINT16)simple_strtol(thisChar, 0, 10) > 0 ? TRUE : FALSE);
				break;

			case 2: /* Measure Duration */
				TransmitReq.MeasureDuration = (UINT16)simple_strtol(thisChar, 0, 10);
				break;

			case 3: /* TID */
				TransmitReq.Tid = (UINT8) simple_strtol(thisChar, 0, 10);
				break;

			case 4: /* Bin 0 Range */
				TransmitReq.BinRange = (UINT8) simple_strtol(thisChar, 0, 10);
				break;

			case 5: /* Averange Condition */
				TransmitReq.ArvCondition =
					((UINT8) simple_strtol(thisChar, 0, 10)) > 0 ? 1 : 0;
				break;

			case 6: /* Consecutive Condition */
				TransmitReq.ConsecutiveCondition =
					((UINT8) simple_strtol(thisChar, 0, 10)) > 0 ? 1 : 0;
				break;

			case 7: /* Delay Condition */
				TransmitReq.DelayCondition =
					((UINT8) simple_strtol(thisChar, 0, 10)) > 0 ? 1 : 0;
				break;

			case 8: /* Averange Error Threshold */
				TransmitReq.AvrErrorThreshold =
					(UINT8) simple_strtol(thisChar, 0, 10);
				break;

			case 9: /* Consecutive Error Threshold */
				TransmitReq.ConsecutiveErrorThreshold =
					(UINT8) simple_strtol(thisChar, 0, 10);
				break;

			case 10: /* Delay Threshold */
				TransmitReq.DelayThreshold =
					(UINT8) simple_strtol(thisChar, 0, 10);
				break;

			case 11: /* Measure counter  */
				TransmitReq.MeasureCnt =
					(UINT8) simple_strtol(thisChar, 0, 10);

				break;

			case 12: /* Trigger time out */
				TransmitReq.TriggerTimeout =
					(UINT8) simple_strtol(thisChar, 0, 10);
				break;
			
		}
		ArgIdx++;
	}	

	if ((ArgIdx != 13) && (ArgIdx != 5))
	{
		DBGPRINT(RT_DEBUG_ERROR,
			("%s: invalid args (%d).\n", __FUNCTION__, ArgIdx));
		DBGPRINT(RT_DEBUG_ERROR,
			("eg: iwpriv ra0 set txreq=<Aid>-<DurationMandortory>-<Duration>-<TID>-<BinRange>[-<AvrCond>-<ConsecutiveCond>-<DealyCond>-<AvrErrorThreshold>-<ConsecutiveErrorThreshold>-<DelayThreshold>-<MeasureCnt>-<TriggerTimeout>]\n"));
		return TRUE;
	}

	if (ArgIdx == 5)
		TransmitReq.bTriggerReport = 0;
	else
		TransmitReq.bTriggerReport = 1;

	pMacEntry = &pAd->MacTab.Content[Aid];
	DBGPRINT(RT_DEBUG_ERROR, ("%s::Aid=%d, PeerMac=%02x:%02x:%02x:%02x:%02x:%02x\n",
		__FUNCTION__, Aid,	pMacEntry->Addr[0], pMacEntry->Addr[1],
		pMacEntry->Addr[2], pMacEntry->Addr[3], pMacEntry->Addr[4], pMacEntry->Addr[5]));

	DBGPRINT(RT_DEBUG_ERROR, ("Duration=%d, Tid=%d, Bin 0 Range=%d\n",
		TransmitReq.MeasureDuration, TransmitReq.Tid, TransmitReq.BinRange));

	DBGPRINT(RT_DEBUG_ERROR, ("ArvCondition=%d, ConsecutiveCondition=%d, DelayCondition=%d\n",
		TransmitReq.ArvCondition, TransmitReq.ConsecutiveCondition, TransmitReq.DelayCondition));

	DBGPRINT(RT_DEBUG_ERROR, ("AvrErrorThreshold=%d, ConsecutiveErrorThreshold=%d\n",
		TransmitReq.AvrErrorThreshold, TransmitReq.ConsecutiveErrorThreshold));

	DBGPRINT(RT_DEBUG_ERROR, ("DelayThreshold=%d\n", TransmitReq.DelayThreshold));

	DBGPRINT(RT_DEBUG_ERROR, ("MeasureCnt=%d, TriggerTimeout=%d\n",
		TransmitReq.MeasureCnt, TransmitReq.TriggerTimeout));

	RRM_EnqueueTxStreamMeasureReq(pAd, Aid, ifIndex, &TransmitReq);

	return TRUE;
}
int gfs2_mount_args(struct gfs2_args *args, char *options)
{
	char *o;
	int token;
	substring_t tmp[MAX_OPT_ARGS];
	int rv;

	/* Split the options into tokens with the "," character and
	   process them */

	while (1) {
		o = strsep(&options, ",");
		if (o == NULL)
			break;
		if (*o == '\0')
			continue;

		token = match_token(o, tokens, tmp);
		switch (token) {
		case Opt_lockproto:
			match_strlcpy(args->ar_lockproto, &tmp[0],
				      GFS2_LOCKNAME_LEN);
			break;
		case Opt_locktable:
			match_strlcpy(args->ar_locktable, &tmp[0],
				      GFS2_LOCKNAME_LEN);
			break;
		case Opt_hostdata:
			match_strlcpy(args->ar_hostdata, &tmp[0],
				      GFS2_LOCKNAME_LEN);
			break;
		case Opt_spectator:
			args->ar_spectator = 1;
			break;
		case Opt_ignore_local_fs:
			/* Retained for backwards compat only */
			break;
		case Opt_localflocks:
			args->ar_localflocks = 1;
			break;
		case Opt_localcaching:
			/* Retained for backwards compat only */
			break;
		case Opt_debug:
			if (args->ar_errors == GFS2_ERRORS_PANIC) {
				printk(KERN_WARNING "GFS2: -o debug and -o errors=panic "
				       "are mutually exclusive.\n");
				return -EINVAL;
			}
			args->ar_debug = 1;
			break;
		case Opt_nodebug:
			args->ar_debug = 0;
			break;
		case Opt_upgrade:
			/* Retained for backwards compat only */
			break;
		case Opt_acl:
			args->ar_posix_acl = 1;
			break;
		case Opt_noacl:
			args->ar_posix_acl = 0;
			break;
		case Opt_quota_off:
		case Opt_noquota:
			args->ar_quota = GFS2_QUOTA_OFF;
			break;
		case Opt_quota_account:
			args->ar_quota = GFS2_QUOTA_ACCOUNT;
			break;
		case Opt_quota_on:
		case Opt_quota:
			args->ar_quota = GFS2_QUOTA_ON;
			break;
		case Opt_suiddir:
			args->ar_suiddir = 1;
			break;
		case Opt_nosuiddir:
			args->ar_suiddir = 0;
			break;
		case Opt_data_writeback:
			args->ar_data = GFS2_DATA_WRITEBACK;
			break;
		case Opt_data_ordered:
			args->ar_data = GFS2_DATA_ORDERED;
			break;
		case Opt_meta:
			args->ar_meta = 1;
			break;
		case Opt_discard:
			args->ar_discard = 1;
			break;
		case Opt_nodiscard:
			args->ar_discard = 0;
			break;
		case Opt_commit:
			rv = match_int(&tmp[0], &args->ar_commit);
			if (rv || args->ar_commit <= 0) {
				printk(KERN_WARNING "GFS2: commit mount option requires a positive numeric argument\n");
				return rv ? rv : -EINVAL;
			}
			break;
		case Opt_statfs_quantum:
			rv = match_int(&tmp[0], &args->ar_statfs_quantum);
			if (rv || args->ar_statfs_quantum < 0) {
				printk(KERN_WARNING "GFS2: statfs_quantum mount option requires a non-negative numeric argument\n");
				return rv ? rv : -EINVAL;
			}
			break;
		case Opt_quota_quantum:
			rv = match_int(&tmp[0], &args->ar_quota_quantum);
			if (rv || args->ar_quota_quantum <= 0) {
				printk(KERN_WARNING "GFS2: quota_quantum mount option requires a positive numeric argument\n");
				return rv ? rv : -EINVAL;
			}
			break;
		case Opt_statfs_percent:
			rv = match_int(&tmp[0], &args->ar_statfs_percent);
			if (rv || args->ar_statfs_percent < 0 ||
			    args->ar_statfs_percent > 100) {
				printk(KERN_WARNING "statfs_percent mount option requires a numeric argument between 0 and 100\n");
				return rv ? rv : -EINVAL;
			}
			break;
		case Opt_err_withdraw:
			args->ar_errors = GFS2_ERRORS_WITHDRAW;
			break;
		case Opt_err_panic:
			if (args->ar_debug) {
				printk(KERN_WARNING "GFS2: -o debug and -o errors=panic "
					"are mutually exclusive.\n");
				return -EINVAL;
			}
			args->ar_errors = GFS2_ERRORS_PANIC;
			break;
		case Opt_barrier:
			args->ar_nobarrier = 0;
			break;
		case Opt_nobarrier:
			args->ar_nobarrier = 1;
			break;
		case Opt_error:
		default:
			printk(KERN_WARNING "GFS2: invalid mount option: %s\n", o);
			return -EINVAL;
		}
	}

	return 0;
}
Example #26
0
static GHashTable *
group_map_new (GError **error)
{
	GHashTable *map;
	GFile *file;

	GFileInputStream *file_stream;
	GDataInputStream *data_stream;

	gchar *key, *value;
	GError *e = NULL;

	g_debug ("pacman: reading groups from %s", PACMAN_GROUP_LIST);
	file = g_file_new_for_path (PACMAN_GROUP_LIST);
	file_stream = g_file_read (file, NULL, &e);

	if (file_stream == NULL) {
		g_object_unref (file);
		g_propagate_error (error, e);
		return NULL;
	}

	map = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
	data_stream = g_data_input_stream_new (G_INPUT_STREAM (file_stream));

	/* read groups line by line, ignoring comments */
	while ((value = g_data_input_stream_read_line (data_stream, NULL, NULL, &e)) != NULL) {
		PkGroupEnum group;

		g_strstrip (value);
		if (*value == '\0' || *value == '#') {
			g_free (value);
			continue;
		}

		/* line format: alpm-group (space|tab)+ packagekit-group */
		key = strsep (&value, " 	");
		g_strchomp (key);

		if (value == NULL) {
			/* safe to cast as it is never freed or modified */
			value = (gchar *) "other";
			group = PK_GROUP_ENUM_OTHER;
		} else {
			g_strchug (value);
			group = pk_group_enum_from_string (value);
		}

		if (group != PK_GROUP_ENUM_UNKNOWN) {
			/* use replace because key and value are allocated together */
			g_hash_table_replace (map, key, value);
			pk_bitfield_add (groups, group);
		}
	}

	g_object_unref (data_stream);
	g_object_unref (file_stream);
	g_object_unref (file);

	if (e != NULL) {
		g_hash_table_unref (map);
		g_propagate_error (error, e);
		return NULL;
	} else {
		return map;
	}
}
Example #27
0
int main(int argc, char *argv[]) {
  
    DBusConnection *connection;
	DBusMessage *msg;
	DBusMessage *reply;
	DBusMessageIter args;
	DBusError err;
	char* sigvalue;
    int ret;

	dbus_error_init(&err);
	
	connection = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
	if (connection == NULL){
		printf("Failed to open connection to bus: %s\n", err.message);
		dbus_error_free(&err);
		exit(1);
	}
	
	ret = dbus_bus_request_name(connection, "test.signal.usb", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
	
	if (dbus_error_is_set(&err)){
	    fprintf(stderr, "Name error (%s)\n", err.message); 
	    dbus_error_free(&err);
	}
	if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret){
	    printf("not primary owner!!\n");
	    exit(1);
	}
	
	printf("listening for usb additions\n ");
	//dbus_bus_add_match(connection, "type='signal',interface='test.signal.Type'", &err);
	dbus_bus_add_match(connection, "type='signal',interface='test.signal.Type'", &err);
	dbus_connection_flush(connection);

	if (dbus_error_is_set(&err)){
	    fprintf(stderr, "error (%s)\n", err.message); 
	    exit(1);
	}

	macaddrs = ht_create(100);
	
	while(true){
	    printf("creating dbus connection\n");
	    dbus_connection_read_write(connection,-1); //block, waiting on message
	    printf("seen a message!!\n");
	    while( (msg = dbus_connection_pop_message(connection)) != NULL){
            if (dbus_message_is_signal(msg, "test.signal.Type", "device")){
                printf("seen a signal!!\n");
                if (!dbus_message_iter_init(msg, &args)){
                    fprintf(stderr, "message has no parameters!\n");
                }
                else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)){
                     fprintf(stderr, "arg is not a string!\n");
                }
                else{
                    dbus_message_iter_get_basic(&args, &sigvalue);
                    printf("got signal %s\n", sigvalue);
                    int argc = 0;
                    char *token;
                    char command[7];
                    char device[18];
                    
                    if (sigvalue != NULL){
                        while ((token = strsep(&sigvalue, " ")) != NULL){
                            if (argc == 0){
                                sprintf(command, token, 0, 7);
                            }
                            if (argc == 1){
                                sprintf(device, token, 0, 15);
                            }
                            argc++;
                        }
                    }
                    if (argc == 3){
                        printf("read in %s %s args\n", command, device);
                        if (strcmp(command, "add") == 0){
                            handle_usb_plugged(device);
                        }else if (strcmp(command, "remove") == 0){
                            handle_usb_unplugged(device);
                        }
                    }
                }
                    //split up the parameter and call appropriate method (should this not be done with dbus method??)
            }
            dbus_message_unref(msg);
	    }
	}
}
Example #28
0
static int
fstabscan(void)
{
	char *cp, *p;
#define	MAXLINELENGTH	1024
	static char line[MAXLINELENGTH];
	char subline[MAXLINELENGTH];
	int typexx;

	for (;;) {

		if (!(p = fgets(line, sizeof(line), _fs_fp)))
			return (0);
/* OLD_STYLE_FSTAB */
		++LineNo;
		if (*line == '#' || *line == '\n')
			continue;
		if (!strpbrk(p, " \t")) {
			_fs_fstab.fs_spec = strsep(&p, ":\n");
			_fs_fstab.fs_file = strsep(&p, ":\n");
			fixfsfile();
			_fs_fstab.fs_type = strsep(&p, ":\n");
			if (_fs_fstab.fs_type) {
				if (!strcmp(_fs_fstab.fs_type, FSTAB_XX))
					continue;
				_fs_fstab.fs_mntops = _fs_fstab.fs_type;
				_fs_fstab.fs_vfstype =
				    strcmp(_fs_fstab.fs_type, FSTAB_SW) ?
				    "ufs" : "swap";
				if ((cp = strsep(&p, ":\n")) != NULL) {
					_fs_fstab.fs_freq = atoi(cp);
					if ((cp = strsep(&p, ":\n")) != NULL) {
						_fs_fstab.fs_passno = atoi(cp);
						return (1);
					}
				}
			}
			goto bad;
		}
/* OLD_STYLE_FSTAB */
		while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0')
			;
		_fs_fstab.fs_spec = cp;
		if (_fs_fstab.fs_spec == NULL || *_fs_fstab.fs_spec == '#')
			continue;
		if (strunvis(_fs_fstab.fs_spec, _fs_fstab.fs_spec) < 0)
			goto bad;
		while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0')
			;
		_fs_fstab.fs_file = cp;
		if (_fs_fstab.fs_file == NULL)
			goto bad;
		if (strunvis(_fs_fstab.fs_file, _fs_fstab.fs_file) < 0)
			goto bad;
		fixfsfile();
		while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0')
			;
		_fs_fstab.fs_vfstype = cp;
		while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0')
			;
		_fs_fstab.fs_mntops = cp;
		if (_fs_fstab.fs_mntops == NULL)
			goto bad;
		_fs_fstab.fs_freq = 0;
		_fs_fstab.fs_passno = 0;
		while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0')
			;
		if (cp != NULL) {
			_fs_fstab.fs_freq = atoi(cp);
			while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0')
				;
			if (cp != NULL)
				_fs_fstab.fs_passno = atoi(cp);
		}
		(void)strlcpy(subline, _fs_fstab.fs_mntops, sizeof(subline));
		p = subline;
		for (typexx = 0, cp = strsep(&p, ","); cp;
		     cp = strsep(&p, ",")) {
			if (strlen(cp) != 2)
				continue;
			if (!strcmp(cp, FSTAB_RW)) {
				_fs_fstab.fs_type = FSTAB_RW;
				break;
			}
			if (!strcmp(cp, FSTAB_RQ)) {
				_fs_fstab.fs_type = FSTAB_RQ;
				break;
			}
			if (!strcmp(cp, FSTAB_RO)) {
				_fs_fstab.fs_type = FSTAB_RO;
				break;
			}
			if (!strcmp(cp, FSTAB_SW)) {
				_fs_fstab.fs_type = FSTAB_SW;
				break;
			}
			if (!strcmp(cp, FSTAB_XX)) {
				_fs_fstab.fs_type = FSTAB_XX;
				typexx++;
				break;
			}
		}
		if (typexx)
			continue;
		if (cp != NULL)
			return (1);

bad:		/* no way to distinguish between EOF and syntax error */
		error(EFTYPE);
	}
	/* NOTREACHED */
}
Example #29
0
/*
 * Check to see if the requested module is specified as a filename with no
 * path.  If so and if a file by the same name exists in the module path,
 * warn the user that the module in the path will be used in preference.
 */
static int
path_check(const char *kldname, int quiet)
{
	int	mib[5], found;
	size_t	miblen, pathlen;
	char	kldpath[MAXPATHLEN];
	char	*path, *tmppath, *element;
	struct	stat sb;
	dev_t	dev;
	ino_t	ino;

	if (strchr(kldname, '/') != NULL) {
		return (0);
	}
	if (strstr(kldname, ".ko") == NULL) {
		return (0);
	}
	if (stat(kldname, &sb) != 0) {
		return (0);
	}

	found = 0;
	dev = sb.st_dev;
	ino = sb.st_ino;

	miblen = sizeof(mib) / sizeof(mib[0]);
	if (sysctlnametomib(PATHCTL, mib, &miblen) != 0) {
		err(1, "sysctlnametomib(%s)", PATHCTL);
	}
	if (sysctl(mib, miblen, NULL, &pathlen, NULL, 0) == -1) {
		err(1, "getting path: sysctl(%s) - size only", PATHCTL);
	}
	path = malloc(pathlen + 1);
	if (path == NULL) {
		err(1, "allocating %lu bytes for the path",
		    (unsigned long)pathlen + 1);
	}
	if (sysctl(mib, miblen, path, &pathlen, NULL, 0) == -1) {
		err(1, "getting path: sysctl(%s)", PATHCTL);
	}
	tmppath = path;

	while ((element = strsep(&tmppath, ";")) != NULL) {
		strlcpy(kldpath, element, MAXPATHLEN);
		if (kldpath[strlen(kldpath) - 1] != '/') {
			strlcat(kldpath, "/", MAXPATHLEN);
		}
		strlcat(kldpath, kldname, MAXPATHLEN);
				
		if (stat(kldpath, &sb) == -1) {
			continue;
		}	

		found = 1;

		if (sb.st_dev != dev || sb.st_ino != ino) {
			if (!quiet) {
				warnx("%s will be loaded from %s, not the "
				    "current directory", kldname, element);
			}
			break;
		} else if (sb.st_dev == dev && sb.st_ino == ino) {
			break;
		}
	}

	free(path);
	
	if (!found) {
		if (!quiet) {
			warnx("%s is not in the module path", kldname);
		}
		return (-1);
	}
	
	return (0);
}
Example #30
0
void parse_args(char *buffer, char** args, 
                size_t args_size, size_t *nargs)
{
/* 
 * size_t data type is defined in the 1999 ISO C standard (C99).
 * It is used to represent the sizes of objects. size_t is the
 * preferred way to declare arguments or variables that hold the
 * size of an object.
 */
    char *buf_args[args_size]; /* You need C99.  Note that args_size
                                  is normally a constant. */
    char **cp;  /* This is used as a pointer into the string array */
    char *wbuf;  /* String variable that has the command line */
    size_t i, j; 
    
    wbuf=buffer;
    buf_args[0]=buffer; 
    args[0] =buffer;
/*
 * Now 'wbuf' is parsed into the string array 'buf_args'
 *
 * The for-loop uses a string.h function
 *   char *strsep(char **stringp, const char *delim);
 *
 *   Description:  
 *   If *stringp = NULL then it returns NULL and does
 *   nothing else.  Otherwise the function finds the first token in
 *   the string *stringp, where tokens are delimited by symbols
 *   in the string 'delim'.  
 *
 *   In the example below, **stringp is &wbu, and 
 *   the delim = ' ', '\n', and '\t'.  So there are three possible 
 *   delimiters. 
 *
 *   So in the string " Aloha World\n", the spaces and "\n" are
 *   delimiters.  Thus, there are three delimiters.  The tokens
 *   are what's between the delimiters.  So the first token is
 *   "", which is nothing because a space is the first delimiter.
 *   The second token is "Aloha", and the third token is "World".
 *   
 *   The function will scan a character string starting from
 *   *stringp, search for the first delimiter.  It replaces
 *   the delimiter with '\0', and *stringp is updated to point
 *   past the token.  In case no delimiter was found, the
 *   token is taken to be the entire string *stringp, and *stringp
 *   is made NULL.   Strsep returns a pointer to the token. 
 *
 *   Example:  Suppose *stringp -> " Aloha World\n"
 *
 *   The first time strsep is called, the string is "\0Aloha World\n",
 *   and the pointer value returned = 0.  Note the token is nothing.
 *
 *   The second time it is called, the string is "\0Aloha\0World\n",
 *   and the pointer value returned = 1  Note that 'Aloha' is a token.
 *
 *   The third time it is called, the string is '\0Aloha\0World\0', 
 *   and the pointer value returned is 7.  Note that 'World' is a token.
 *
 *   The fourth time it is called, it returns NULL.
 *
 *   The for-loop, goes through buffer starting at the beginning.
 *   wbuf is updated to point to the next token, and cp is
 *   updated to point to the current token, which terminated by '\0'.
 *   Note that pointers to tokens are stored in array buf_args through cp.
 *   The loop stops if there are no more tokens or exceeded the
 *   array buf_args.
 */   
    /* cp is a pointer to buff_args */ 
    for(cp=buf_args; (*cp=strsep(&wbuf, " \n\t")) != NULL ;){
        if ((*cp != '\0') && (++cp >= &buf_args[args_size]))
            break; 
    }

/* 
 * Copy 'buf_args' into 'args'
 */    
    for (j=i=0; buf_args[i]!=NULL; i++){ 
        if(strlen(buf_args[i])>0)  /* Store only non-empty tokens */
            args[j++]=buf_args[i];
    }
    *nargs=j;
    args[j]=NULL;
}