Пример #1
0
/*
 *	Print mail entries
 */
void 
printmail(void)
{
	static char pn[] = "printmail";
	int	flg, curlet, showlet, k, print, aret, stret, rc;
	int	nsmbox = 0;	/* 1 ==> mailbox is in non-standard place */
	int	sav_j = -1;
	char	*p = NULL;
	size_t	psize = 0;
	struct	stat stbuf;
	struct	stat *stbufp;
	int ttyf = isatty(1) ? TTY : ORDINARY;
	char	*readbuf = NULL;/* holds user's response in interactive mode */
	size_t	readbufsize = 0;
	char	*resp;
	gid_t	savedegid;

	(void)&curlet;
	(void)&showlet;
	(void)&print;
	(void)&sav_j;
	(void)&ttyf;

	stbufp = &stbuf;

	/*
	 *	create working directory mbox name
	 */
	cat(&hmbox, &hmboxsize, home, mbox);

	/*
	 *	If we are not using an alternate mailfile, then get
	 *	the $MAIL value and build the filename for the mailfile.
	 *	If $MAIL is set, but is NOT the 'standard' place, then
	 *	use it but set flgf to circumvent :saved processing.
	 */
	if (!flgf) {
		cat(&p, &psize, maildir, my_name);
		if (((mailfile = getenv("MAIL")) == NULL) ||
		    (strlen(mailfile) == 0)) {
			/* $MAIL not set, use standard path to mailfile */
			mailfile = p;
		} else {
			if (strcmp(mailfile, p) != 0) {
			    flgf = 1;
			    nsmbox = 1;
			    Dout(pn, 0, "$MAIL ('%s') != standard path\n",
				mailfile);
			    Dout("", 0, "\tSetting flgf to 1.\n");
			}
			free(p);
		}
	}

	/*
	 *	Get ACCESS and MODIFICATION times of mailfile BEFORE we
	 *	use it. This allows us to put them back when we are
	 *	done. If we didn't, the shell would think NEW mail had
	 *	arrived since the file times would have changed.
	 */
	stret = CERROR;
	if (access(mailfile, A_EXIST) == A_OK) {
		if ((stret = stat(mailfile, stbufp)) != A_OK) {
			errmsg(E_FILE, "Cannot stat mailfile");
			return;
		}
		mf_gid = stbufp->st_gid;
		mf_uid = stbufp->st_uid;
		utimep->actime = stbufp->st_atime;
		utimep->modtime = stbufp->st_mtime;
		file_size = stbufp->st_size;
	}

	/* Open the file as the real gid */
	savedegid = getegid();
	setegid(getgid());
	malf = fopen(mailfile, "r");
	setegid(savedegid);
	/*
	 *	stat succeeded, but we cannot access the mailfile
	 */
	if (stret == CSUCCESS && malf == NULL) {
		char buf[MAXFILENAME+50];
		snprintf(buf, sizeof (buf),
		    "Invalid permissions on %s", mailfile);
		errmsg(E_PERM, buf);
		return;
	} else
	/*
	 *	using an alternate mailfile, but we failed on access
	 */
	if (!nsmbox && flgf && (malf == NULL)) {
		errmsg(E_FILE, "Cannot open mailfile");
		return;
	}
	/*
	 *	we failed to access OR the file is empty
	 */
	else if ((malf == NULL) || (stbuf.st_size == 0)) {
		if (!flge && !flgE) {
			printf("No mail.\n");
		}
		error = E_FLGE;
		Dout(pn, 0, "error set to %d\n", error);
		return;
	}
	if (flge)
		return;

	if (flgE) {
		if (utimep->modtime < utimep->actime) {
			error = E_FLGE_OM;
			Dout(pn, 0, "error set to %d\n", error);
		}
		return;
	}
	/*
	 *	Secure the mailfile to guarantee integrity
	 */
	lockfile = mailfile;
	lock(my_name);

	/*
	 *	copy mail to temp file and mark each letter in the
	 *	let array --- mailfile is still locked !!!
	 */
	mktmp();
	copymt(malf, tmpf);
	onlet = nlet;
	fclose(malf);
	fclose(tmpf);
	tmpf = NULL;
	unlock();	/* All done, OK to unlock now */
	tmpf = doopen(lettmp, "r+", E_TMP);
	changed = 0;
	print = 1;
	curlet = 0;
	while (curlet < nlet) {
		/*
		 *	reverse order ?
		 */
		showlet = flgr ? curlet : nlet - curlet - 1;

		k = setjmp(sjbuf);
		if (k != 0)
			sigrelse(k);
		if (k == 0 && print != 0) {
				/* -h says to print the headers first */
				if (flgh) {
					gethead(showlet, 0);
					flgh = 0;	/* Only once */
					/* set letter # to invalid # */
					curlet--;
					showlet =
					    flgr ? curlet : nlet - curlet - 1;
				} else {
					if (showlet != sav_j) {
						/* Looking at new message. */
						/* Reset flag to override */
						/* non-display of binary */
						/* contents */
						sav_j = showlet;
						pflg = 0;
						Pflg = flgP;
					}
					copylet(showlet, stdout, ttyf);
				}
		}

		/*
		 *	print only
		 */
		if (flgp) {
			curlet++;
			continue;
		}
		/*
		 *	Interactive
		 */
		interactive = 1;
		k = setjmp(sjbuf);
		if (k != 0)
			sigrelse(k);
		stat(mailfile, stbufp);
		if (stbufp->st_size != file_size) {
			/*
			 *	New mail has arrived, load it
			 */
			k = nlet;
			lock(my_name);
			malf = doopen(mailfile, "r", E_FILE);
			fclose(tmpf);
			tmpf = doopen(lettmp, "a", E_TMP);
			fseek(malf, let[nlet].adr, 0);
			copymt(malf, tmpf);
			file_size = stbufp->st_size;
			fclose(malf);
			fclose(tmpf);
			tmpf = NULL;
			unlock();
			tmpf = doopen(lettmp, "r+", E_TMP);
			if (++k < nlet)
				printf("New mail loaded into letters %d - %d\n",
				    k, nlet);
			else
				printf("New mail loaded into letter %d\n",
				    nlet);
		}

		/* read the command */
		printf("? ");
		fflush(stdout);
		fflush(stderr);
		if (fgetline(&readbuf, &readbufsize, NULL, stdin) == NULL)
			break;
		resp = readbuf;
		while (*resp == ' ' || *resp == '\t') resp++;
		print = 1;
		Dout(pn, 0, "resp = '%s'\n", resp);
		if ((rc = atoi(resp)) != 0) {
			if (!validmsg(rc)) print = 0;
			else curlet = flgr ? rc - 1 : nlet - rc;
		} else switch (resp[0]) {
			default:
				printf("Usage:\n");
			/*
			 *	help
			 */
			case '?':
				print = 0;
				for (rc = 0; help[rc]; rc++)
					printf("%s", help[rc]);
				break;
			/*
			 *	print message number of current message
			 */
			case '#':
				print = 0;
				if ((showlet == nlet) || (showlet < 0)) {
					printf("No message selected yet.\n");
				} else {
					printf("Current message number is %d\n",
					    showlet+1);
				}
				break;
			/*
			 *	headers
			 */
			case 'h':
				print = 0;
				if (resp[2] != 'd' &&
				    resp[2] != 'a' &&
				    (rc = getnumbr(resp+1)) > 0) {
					showlet = rc - 1;
					curlet = flgr ? rc - 1 : nlet - rc- 1;
				}
				if (rc == -1 && resp[2] != 'a' &&
				    resp[2] != 'd')
					break;
				if (resp[2] == 'a') rc = 1;
				else if (resp[2] == 'd') rc = 2;
					else rc = 0;

/*
 *				if (!validmsg(showlet)) break;
 */
				gethead(showlet, rc);
				break;
			/*
			 *	skip entry
			 */
			case '+':
			case 'n':
			case '\n':
				curlet++;
				break;
			case 'P':
				Pflg++;
				break;
			case 'p':
				pflg++;
				break;
			case 'x':
				changed = 0;
			case 'q':
				goto donep;
			/*
			 *	Previous entry
			 */
			case '^':
			case '-':
				if (--curlet < 0) curlet = 0;
				break;
			/*
			 *	Save in file without header
			 */
			case 'y':
			case 'w':
			/*
			 *	Save mail with header
			 */
			case 's':
				print = 0;
				if (!validmsg(curlet)) break;
				if (resp[1] == '\n' || resp[1] == '\0') {
					cat(&readbuf, &readbufsize, "s", hmbox);
					resp = readbuf;
				} else if (resp[1] != ' ') {
					printf("Invalid command\n");
					break;
				}
				umask(umsave);
				flg = 0;
				if (getarg(lfil, resp + 1) == NULL) {
					cat(&readbuf, &readbufsize, "s", hmbox);
					resp = readbuf;
				}
				malf = (FILE *)NULL;
				p = resp + 1;
				while ((p = getarg(lfil, p)) != NULL) {
					if (flg) {
					    fprintf(stderr,
						"%s: File '%s' skipped\n",
						program, lfil);
					    continue;
					}
					malf = NULL;
					if ((aret = legal(lfil))) {
						malf = fopen(lfil, "a");
					}
					if ((malf == NULL) || (aret == 0)) {
					    fprintf(stderr,
						"%s: Cannot append to %s\n",
						program, lfil);
					    flg++;
					} else if (aret == 2) {
						chown(lfil, my_euid, my_gid);
					}
					if (!flg &&
					    copylet(showlet, malf, resp[0] ==
					    's'? ORDINARY: ZAP) == FALSE) {
						fprintf(stderr,
					    "%s: Cannot save mail to '%s'\n",
						    program, lfil);
						flg++;
					} else
						Dout(pn, 0, "!saved\n");
					if (malf != (FILE *)NULL) {
						fclose(malf);
					}
				}
				umask(7);
				if (!flg) {
					setletr(showlet, resp[0]);
					print = 1;
					curlet++;
				}
				break;
			/*
			 *	Reply to a letter
			 */
			case 'r':
				print = 0;
				if (!validmsg(curlet)) break;
				replying = 1;
				for (k = 1; resp[k] == ' ' || resp[k] == '\t';
				    ++k);
				resp[strlen(resp)-1] = '\0';
				cpy(&m_sendto, &m_sendtosize, resp+k);
				goback(showlet);
				replying = 0;
				setletr(showlet, resp[0]);
				break;
			/*
			 *	Undelete
			 */
			case 'u':
				print = 0;
				if ((k = getnumbr(resp+1)) <= 0) k = showlet;
				else k--;
				if (!validmsg(k)) break;
				setletr(k, ' ');
				break;
			/*
			 *	Mail letter to someone else
			 */
			case 'm':
				{
				reciplist list;
				print = 0;
				if (!validmsg(curlet)) break;
				new_reciplist(&list);
				flg = 0;
				k = 0;
				if (substr(resp, " -") != -1 ||
					substr(resp, "\t-") != -1) {
					printf("Only users may be specified\n");
					break;
				}
				p = resp + 1;
				while ((p = getarg(lfil, p)) != NULL) {
					char *env;
					if (lfil[0] == '$') {
						if (!(env = getenv(&lfil[1]))) {
							fprintf(stderr,
				"%s: %s has no value or is not exported.\n",
							    program, lfil);
							flg++;
						} else
							add_recip(&list, env,
							    FALSE);
						k++;
					} else if (lfil[0] != '\0') {
						add_recip(&list, lfil, FALSE);
						k++;
					}
				}
				cpy(&Rpath, &Rpathsize, my_name);
				sending = TRUE;
				flg += sendlist(&list, showlet, 0);
				sending = FALSE;
				if (k) {
					if (!flg) {
						setletr(showlet, 'm');
						print = 1;
						curlet++;
					}
				} else
					printf("Invalid command\n");
				del_reciplist(&list);
				break;
				}
			/*
			 *	Read new letters
			 */
			case 'a':
				if (onlet == nlet) {
					printf("No new mail\n");
					print = 0;
					break;
				}
				curlet = 0;
				print = 1;
				break;
			/*
			 *	Escape to shell
			 */
			case '!':
				systm(resp + 1);
				printf("!\n");
				print = 0;
				break;
			/*
			 *	Delete an entry
			 */
			case 'd':
				print = 0;
				k = 0;
				if (strncmp("dq", resp, 2) != SAME &&
					strncmp("dp", resp, 2) != SAME)
					if ((k = getnumbr(resp+1)) == -1) break;
				if (k == 0) {
					k = showlet;
					if (!validmsg(curlet)) break;
					print = 1;
					curlet++;
				} else	k--;

				setletr(k, 'd');
				if (resp[1] == 'p') print = 1;
				else if (resp[1] == 'q') goto donep;
				break;
		}
	}
	/*
	 *	Copy updated mailfile back
	 */
donep:
	if (changed) {
		copyback();
		stamp();
	}
}
Пример #2
0
void
setjobctl(int on)
{
	int i;

	if (on == jobctl || rootshell == 0)
		return;
	if (on) {
		if (ttyfd != -1)
			close(ttyfd);
		if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
			i = 0;
			while (i <= 2 && !isatty(i))
				i++;
			if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
				goto out;
		}
		if (ttyfd < 10) {
			/*
			 * Keep our TTY file descriptor out of the way of
			 * the user's redirections.
			 */
			if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
				close(ttyfd);
				ttyfd = -1;
				goto out;
			}
			close(ttyfd);
			ttyfd = i;
		}
		if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
			close(ttyfd);
			ttyfd = -1;
			goto out;
		}
		do { /* while we are in the background */
			initialpgrp = tcgetpgrp(ttyfd);
			if (initialpgrp < 0) {
out:				out2fmt_flush("sh: can't access tty; job control turned off\n");
				mflag = 0;
				return;
			}
			if (initialpgrp != getpgrp()) {
				kill(0, SIGTTIN);
				continue;
			}
		} while (0);
		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
		setpgid(0, rootpid);
		tcsetpgrp(ttyfd, rootpid);
	} else { /* turning job control off */
		setpgid(0, initialpgrp);
		tcsetpgrp(ttyfd, initialpgrp);
		close(ttyfd);
		ttyfd = -1;
		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
	}
	jobctl = on;
}
Пример #3
0
int main(int argc, char **argv)
{
	int		argval;
	bool		quiet = false;
	bool		done_license = false;
	int		sockfd;
	uint32_t	magic, needed;
	char		*line = NULL;
	ssize_t		len, size;
	char const	*file = NULL;
	char const	*name = "radiusd";
	char		*p, buffer[65536];
	char const	*input_file = NULL;
	FILE		*inputfp = stdin;
	char const	*output_file = NULL;
	char const	*server = NULL;

	char const	*radius_dir = RADIUS_DIR;
	char const	*dict_dir = DICTDIR;

	char *commands[MAX_COMMANDS];
	int num_commands = -1;

#ifndef NDEBUG
	if (fr_fault_setup(getenv("PANIC_ACTION"), argv[0]) < 0) {
		fr_perror("radmin");
		exit(EXIT_FAILURE);
	}
#endif

	talloc_set_log_stderr();

	outputfp = stdout;	/* stdout is not a constant value... */

	if ((progname = strrchr(argv[0], FR_DIR_SEP)) == NULL) {
		progname = argv[0];
	} else {
		progname++;
	}

	while ((argval = getopt(argc, argv, "d:D:hi:e:Ef:n:o:qs:S")) != EOF) {
		switch(argval) {
		case 'd':
			if (file) {
				fprintf(stderr, "%s: -d and -f cannot be used together.\n", progname);
				exit(1);
			}
			if (server) {
				fprintf(stderr, "%s: -d and -s cannot be used together.\n", progname);
				exit(1);
			}
			radius_dir = optarg;
			break;

		case 'D':
			dict_dir = optarg;
			break;

		case 'e':
			num_commands++; /* starts at -1 */
			if (num_commands >= MAX_COMMANDS) {
				fprintf(stderr, "%s: Too many '-e'\n",
					progname);
				exit(1);
			}
			commands[num_commands] = optarg;
			break;

		case 'E':
			echo = true;
			break;

		case 'f':
			radius_dir = NULL;
			file = optarg;
			break;

		default:
		case 'h':
			usage(0);
			break;

		case 'i':
			if (strcmp(optarg, "-") != 0) {
				input_file = optarg;
			}
			quiet = true;
			break;

		case 'n':
			name = optarg;
			break;

		case 'o':
			if (strcmp(optarg, "-") != 0) {
				output_file = optarg;
			}
			quiet = true;
			break;

		case 'q':
			quiet = true;
			break;

		case 's':
			if (file) {
				fprintf(stderr, "%s: -s and -f cannot be used together.\n", progname);
				usage(1);
			}
			radius_dir = NULL;
			server = optarg;
			break;

		case 'S':
			secret = NULL;
			break;
		}
	}

	/*
	 *	Mismatch between the binary and the libraries it depends on
	 */
	if (fr_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) {
		fr_perror("radmin");
		exit(1);
	}

	if (radius_dir) {
		int rcode;
		CONF_SECTION *cs, *subcs;

		file = NULL;	/* MUST read it from the conffile now */

		snprintf(buffer, sizeof(buffer), "%s/%s.conf", radius_dir, name);

		/*
		 *	Need to read in the dictionaries, else we may get
		 *	validation errors when we try and parse the config.
		 */
		if (dict_init(dict_dir, RADIUS_DICTIONARY) < 0) {
			fr_perror("radmin");
			exit(64);
		}

		if (dict_read(radius_dir, RADIUS_DICTIONARY) == -1) {
			fr_perror("radmin");
			exit(64);
		}

		cs = cf_file_read(buffer);
		if (!cs) {
			fprintf(stderr, "%s: Errors reading or parsing %s\n", progname, buffer);
			usage(1);
		}

		subcs = NULL;
		while ((subcs = cf_subsection_find_next(cs, subcs, "listen")) != NULL) {
			char const *value;
			CONF_PAIR *cp = cf_pair_find(subcs, "type");

			if (!cp) continue;

			value = cf_pair_value(cp);
			if (!value) continue;

			if (strcmp(value, "control") != 0) continue;

			/*
			 *	Now find the socket name (sigh)
			 */
			rcode = cf_item_parse(subcs, "socket", FR_ITEM_POINTER(PW_TYPE_STRING, &file), NULL);
			if (rcode < 0) {
				fprintf(stderr, "%s: Failed parsing listen section\n", progname);
				exit(1);
			}

			if (!file) {
				fprintf(stderr, "%s: No path given for socket\n", progname);
				usage(1);
			}
			break;
		}

		if (!file) {
			fprintf(stderr, "%s: Could not find control socket in %s\n", progname, buffer);
			exit(1);
		}
	}

	if (input_file) {
		inputfp = fopen(input_file, "r");
		if (!inputfp) {
			fprintf(stderr, "%s: Failed opening %s: %s\n", progname, input_file, strerror(errno));
			exit(1);
		}
	}

	if (output_file) {
		outputfp = fopen(output_file, "w");
		if (!outputfp) {
			fprintf(stderr, "%s: Failed creating %s: %s\n", progname, output_file, strerror(errno));
			exit(1);
		}
	}

	if (!file && !server) {
		fprintf(stderr, "%s: Must use one of '-d' or '-f' or '-s'\n",
			progname);
		exit(1);
	}

	/*
	 *	Check if stdin is a TTY only if input is from stdin
	 */
	if (input_file && !quiet && !isatty(STDIN_FILENO)) quiet = true;

#ifdef USE_READLINE
	if (!quiet) {
#ifdef USE_READLINE_HISTORY
		using_history();
#endif
		rl_bind_key('\t', rl_insert);
	}
#endif

 reconnect:
	if (file) {
		/*
		 *	FIXME: Get destination from command line, if possible?
		 */
		sockfd = fr_domain_socket(file);
		if (sockfd < 0) {
			exit(1);
		}
	} else {
		sockfd = client_socket(server);
	}

	/*
	 *	Read initial magic && version information.
	 */
	for (size = 0; size < 8; size += len) {
		len = read(sockfd, buffer + size, 8 - size);
		if (len < 0) {
			fprintf(stderr, "%s: Error reading initial data from socket: %s\n",
				progname, strerror(errno));
			exit(1);
		}
	}

	memcpy(&magic, buffer, 4);
	magic = ntohl(magic);
	if (magic != 0xf7eead15) {
		fprintf(stderr, "%s: Socket %s is not FreeRADIUS administration socket\n", progname, file);
		exit(1);
	}

	memcpy(&magic, buffer + 4, 4);
	magic = ntohl(magic);

	if (!server) {
		needed = 1;
	} else {
		needed = 2;
	}

	if (magic != needed) {
		fprintf(stderr, "%s: Socket version mismatch: Need %d, got %d\n",
			progname, needed, magic);
		exit(1);
	}

	if (server && secret) do_challenge(sockfd);

	/*
	 *	Run one command.
	 */
	if (num_commands >= 0) {
		int i;

		for (i = 0; i <= num_commands; i++) {
			size = run_command(sockfd, commands[i],
					   buffer, sizeof(buffer));
			if (size < 0) exit(1);

			if (buffer[0]) {
				fputs(buffer, outputfp);
				fprintf(outputfp, "\n");
				fflush(outputfp);
			}
		}
		exit(0);
	}

	if (!done_license && !quiet) {
		printf("%s - FreeRADIUS Server administration tool.\n", radmin_version);
		printf("Copyright (C) 2008-2014 The FreeRADIUS server project and contributors.\n");
		printf("There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n");
		printf("PARTICULAR PURPOSE.\n");
		printf("You may redistribute copies of FreeRADIUS under the terms of the\n");
		printf("GNU General Public License v2.\n");

		done_license = true;
	}

	/*
	 *	FIXME: Do login?
	 */

	while (1) {
#ifndef USE_READLINE
		if (!quiet) {
			printf("radmin> ");
			fflush(stdout);
		}
#else
		if (!quiet) {
			line = readline("radmin> ");

			if (!line) break;

			if (!*line) {
				free(line);
				continue;
			}

#ifdef USE_READLINE_HISTORY
			add_history(line);
#endif
		} else		/* quiet, or no readline */
#endif
		{
			line = fgets(buffer, sizeof(buffer), inputfp);
			if (!line) break;

			p = strchr(buffer, '\n');
			if (!p) {
				fprintf(stderr, "%s: Input line too long\n",
					progname);
				exit(1);
			}

			*p = '\0';

			/*
			 *	Strip off leading spaces.
			 */
			for (p = line; *p != '\0'; p++) {
				if ((p[0] == ' ') ||
				    (p[0] == '\t')) {
					line = p + 1;
					continue;
				}

				if (p[0] == '#') {
					line = NULL;
					break;
				}

				break;
			}

			/*
			 *	Comments: keep going.
			 */
			if (!line) continue;

			/*
			 *	Strip off CR / LF
			 */
			for (p = line; *p != '\0'; p++) {
				if ((p[0] == '\r') ||
				    (p[0] == '\n')) {
					p[0] = '\0';
					break;
				}
			}
		}

		if (strcmp(line, "reconnect") == 0) {
			close(sockfd);
			line = NULL;
			goto reconnect;
		}

		if (memcmp(line, "secret ", 7) == 0) {
			if (!secret) {
				secret = line + 7;
				do_challenge(sockfd);
			}
			line = NULL;
			continue;
		}

		/*
		 *	Exit, done, etc.
		 */
		if ((strcmp(line, "exit") == 0) ||
		    (strcmp(line, "quit") == 0)) {
			break;
		}

		if (server && !secret) {
			fprintf(stderr, "ERROR: You must enter 'secret <SECRET>' before running any commands\n");
			line = NULL;
			continue;
		}

		size = run_command(sockfd, line, buffer, sizeof(buffer));
		if (size <= 0) break; /* error, or clean exit */

		if (size == 1) continue; /* no output. */

		fputs(buffer, outputfp);
		fflush(outputfp);
		fprintf(outputfp, "\n");
	}

	fprintf(outputfp, "\n");

	return 0;
}
Пример #4
0
/*
 * Note to future maintainers: with the change of wall to use the
 * getutxent() API, the forked children (created by this function)
 * must call _exit as opposed to exit. This is necessary to avoid
 * unwanted fflushing of getutxent's stdio stream (caused by atexit
 * processing).
 */
static void
sendmes(struct utmpx *p, zoneid_t zid)
{
	int i;
	char *s;
	static char device[LMAX + 6];
	char *bp;
	int ibp;
	FILE *f;
	int fd, tmpl_fd;
	boolean_t zoneenter = B_FALSE;

	if (zid != getzoneid()) {
		zoneenter = B_TRUE;
		tmpl_fd = init_template();
		if (tmpl_fd == -1) {
			(void) fprintf(stderr, "Could not initialize "
			    "process contract");
			return;
		}
	}

	while ((i = (int)fork()) == -1) {
		(void) alarm(60);
		(void) wait((int *)0);
		(void) alarm(0);
	}

	if (i)
		return;

	if (zoneenter && zone_enter(zid) == -1) {
		char zonename[ZONENAME_MAX];
		(void) getzonenamebyid(zid, zonename, ZONENAME_MAX);
		(void) fprintf(stderr, "Could not enter zone "
		    "%s\n", zonename);
	}
	if (zoneenter)
		(void) ct_tmpl_clear(tmpl_fd);

	if (gflag)
		if (!chkgrp(p->ut_user))
			_exit(0);

	(void) signal(SIGHUP, SIG_IGN);
	(void) alarm(60);
	s = &device[0];
	(void) snprintf(s, sizeof (device), "/dev/%.*s", LMAX, p->ut_line);

	/* check if the device is really a tty */
	if ((fd = open(s, O_WRONLY|O_NOCTTY|O_NONBLOCK)) == -1) {
		(void) fprintf(stderr, "Cannot send to %.*s on %s\n",
		    NMAX, p->ut_user, s);
		perror("open");
		(void) fflush(stderr);
		_exit(1);
	} else {
		if (!isatty(fd)) {
			(void) fprintf(stderr,
			    "Cannot send to device %.*s %s\n",
			    LMAX, p->ut_line,
			    "because it's not a tty");
			openlog("wall", 0, LOG_AUTH);
			syslog(LOG_CRIT, "%.*s in utmpx is not a tty\n",
			    LMAX, p->ut_line);
			closelog();
			(void) fflush(stderr);
			_exit(1);
		}
	}
#ifdef DEBUG
	(void) close(fd);
	f = fopen("wall.debug", "a");
#else
	f = fdopen(fd, "w");
#endif
	if (f == NULL) {
		(void) fprintf(stderr, "Cannot send to %-.*s on %s\n",
		    NMAX, &p->ut_user[0], s);
		perror("open");
		(void) fflush(stderr);
		_exit(1);
	}
	(void) fprintf(f,
	    "\07\07\07Broadcast Message from %s (%s) on %s %19.19s",
	    who, line, systm, time_buf);
	if (gflag)
		(void) fprintf(f, " to group %s", grpname);
	(void) fprintf(f, "...\n");
#ifdef DEBUG
	(void) fprintf(f, "DEBUG: To %.*s on %s\n", NMAX, p->ut_user, s);
#endif
	i = strlen(mesg);
	for (bp = mesg; --i >= 0; bp++) {
		ibp = (unsigned int)((unsigned char) *bp);
		if (*bp == '\n')
			(void) putc('\r', f);
		if (isprint(ibp) || *bp == '\r' || *bp == '\013' ||
		    *bp == ' ' || *bp == '\t' || *bp == '\n' || *bp == '\007') {
			(void) putc(*bp, f);
		} else {
			if (!isascii(*bp)) {
				(void) fputs("M-", f);
				*bp = toascii(*bp);
			}
			if (iscntrl(*bp)) {
				(void) putc('^', f);
				(void) putc(*bp + 0100, f);
			}
			else
				(void) putc(*bp, f);
		}

		if (*bp == '\n')
			(void) fflush(f);

		if (ferror(f) || feof(f)) {
			(void) printf("\n\007Write failed\n");
			(void) fflush(stdout);
			_exit(1);
		}
	}
	(void) fclose(f);
	(void) close(fd);
	_exit(0);
}
Пример #5
0
int main(int argc, char **argv)
{
	int tty_fd;
	struct termios ts;
	int speed = 0, bits = '-', parity = '-', stop = '-';
	int set_iflag = 0, clr_iflag = 0;
	int ldisc;
	int optc;
	char *dev;
	int intropause = 1;
	char *introparm = NULL;

	static const struct option opttbl[] = {
		{"speed", required_argument, NULL, 's'},
		{"sevenbits", no_argument, NULL, '7'},
		{"eightbits", no_argument, NULL, '8'},
		{"noparity", no_argument, NULL, 'n'},
		{"evenparity", no_argument, NULL, 'e'},
		{"oddparity", no_argument, NULL, 'o'},
		{"onestopbit", no_argument, NULL, '1'},
		{"twostopbits", no_argument, NULL, '2'},
		{"iflag", required_argument, NULL, 'i'},
		{"help", no_argument, NULL, 'h'},
		{"version", no_argument, NULL, 'V'},
		{"debug", no_argument, NULL, 'd'},
	        {"intro-command", no_argument, NULL, 'c'},
	        {"pause", no_argument, NULL, 'p'},
		{NULL, 0, NULL, 0}
	};

	signal(SIGKILL, handler);
	signal(SIGINT, handler);

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	/* parse options */
	if (argc == 0)
		usage(EXIT_SUCCESS);
	while ((optc =
		getopt_long(argc, argv, "dhV78neo12s:i:c:p:", opttbl,
			    NULL)) >= 0) {
		switch (optc) {
		case 'd':
			debug = 1;
			break;
		case '1':
		case '2':
			stop = optc;
			break;
		case '7':
		case '8':
			bits = optc;
			break;
		case 'n':
		case 'e':
		case 'o':
			parity = optc;
			break;
		case 's':
			speed = strtos32_or_err(optarg, _("invalid speed argument"));
			break;
		case 'p':
			intropause = strtou32_or_err(optarg, _("invalid pause argument"));
			if (intropause > 10)
				errx(EXIT_FAILURE, "invalid pause: %s", optarg);
			break;
		case 'c':
			introparm = optarg;
			break;
		case 'i':
			parse_iflag(optarg, &set_iflag, &clr_iflag);
			break;
		case 'V':
			printf(UTIL_LINUX_VERSION);
			return EXIT_SUCCESS;
		case 'h':
			usage(EXIT_SUCCESS);
		default:
			errtryhelp(EXIT_FAILURE);
		}
	}

	if (argc - optind != 2)
		usage(EXIT_FAILURE);

	/* parse line discipline specification */
	ldisc = lookup_table(ld_discs, argv[optind]);
	if (ldisc < 0)
		ldisc = strtos32_or_err(argv[optind], _("invalid line discipline argument"));

	/* ldisc specific option settings */
	if (ldisc == N_GIGASET_M101) {
		/* device specific defaults for line speed and data format */
		if (speed == 0)
			speed = 115200;
		if (bits == '-')
			bits = '8';
		if (parity == '-')
			parity = 'n';
		if (stop == '-')
			stop = '1';
	}

	/* open device */
	dev = argv[optind + 1];
	if ((tty_fd = open(dev, O_RDWR | O_NOCTTY)) < 0)
		err(EXIT_FAILURE, _("cannot open %s"), dev);
	if (!isatty(tty_fd))
		errx(EXIT_FAILURE, _("%s is not a serial line"), dev);

	dbg("opened %s", dev);

	/* set line speed and format */
	if (tcgetattr(tty_fd, &ts) < 0)
		err(EXIT_FAILURE,
		    _("cannot get terminal attributes for %s"), dev);
	cfmakeraw(&ts);
	if (speed && my_cfsetspeed(&ts, speed) < 0)
		errx(EXIT_FAILURE, _("speed %d unsupported"), speed);

	switch (stop) {
	case '1':
		ts.c_cflag &= ~CSTOPB;
		break;
	case '2':
		ts.c_cflag |= CSTOPB;
		break;
	case '-':
		break;
	default:
		abort();
	}
	switch (bits) {
	case '7':
		ts.c_cflag = (ts.c_cflag & ~CSIZE) | CS7;
		break;
	case '8':
		ts.c_cflag = (ts.c_cflag & ~CSIZE) | CS8;
		break;
	case '-':
		break;
	default:
		abort();
	}
	switch (parity) {
	case 'n':
		ts.c_cflag &= ~(PARENB | PARODD);
		break;
	case 'e':
		ts.c_cflag |= PARENB;
		ts.c_cflag &= ~PARODD;
		break;
	case 'o':
		ts.c_cflag |= (PARENB | PARODD);
		break;
	case '-':
		break;
	default:
		abort();
	}

	ts.c_cflag |= CREAD;	/* just to be on the safe side */
	ts.c_iflag |= set_iflag;
	ts.c_iflag &= ~clr_iflag;

	if (tcsetattr(tty_fd, TCSAFLUSH, &ts) < 0)
		err(EXIT_FAILURE,
		    _("cannot set terminal attributes for %s"), dev);

	dbg("set to raw %d %c%c%c: cflag=0x%x",
	    speed, bits, parity, stop, ts.c_cflag);

	if (introparm && *introparm)
	{
		dbg("intro command is '%s'", introparm);
		if (write_all(tty_fd, introparm, strlen(introparm)) != 0)
			err(EXIT_FAILURE,
			    _("cannot write intro command to %s"), dev);

		if (intropause) {
			dbg("waiting for %d seconds", intropause);
			sleep(intropause);
		}
	}

	/* Attach the line discipline. */
	if (ioctl(tty_fd, TIOCSETD, &ldisc) < 0)
		err(EXIT_FAILURE, _("cannot set line discipline"));

	dbg("line discipline set to %d", ldisc);

	/* ldisc specific post-attach actions */
	if (ldisc == N_GSM0710)
		gsm0710_set_conf(tty_fd);

	/* Go into background if not in debug mode. */
	if (!debug && daemon(0, 0) < 0)
		err(EXIT_FAILURE, _("cannot daemonize"));

	/* Sleep to keep the line discipline active. */
	pause();

	exit(EXIT_SUCCESS);
}
Пример #6
0
int
c_read(char **wp)
{
	int c = 0;
	int expand = 1, history = 0;
	int expanding;
	int ecode = 0;
	char *cp;
	int fd = 0;
	struct shf *shf;
	int optc;
	const char *emsg;
	XString cs, xs;
	struct tbl *vp;
	char *xp = NULL;

	while ((optc = ksh_getopt(wp, &builtin_opt, "prsu,")) != -1)
		switch (optc) {
		case 'p':
			if ((fd = coproc_getfd(R_OK, &emsg)) < 0) {
				bi_errorf("-p: %s", emsg);
				return 1;
			}
			break;
		case 'r':
			expand = 0;
			break;
		case 's':
			history = 1;
			break;
		case 'u':
			if (!*(cp = builtin_opt.optarg))
				fd = 0;
			else if ((fd = check_fd(cp, R_OK, &emsg)) < 0) {
				bi_errorf("-u: %s: %s", cp, emsg);
				return 1;
			}
			break;
		case '?':
			return 1;
		}
	wp += builtin_opt.optind;

	if (*wp == NULL)
		*--wp = "REPLY";

	/* Since we can't necessarily seek backwards on non-regular files,
	 * don't buffer them so we can't read too much.
	 */
	shf = shf_reopen(fd, SHF_RD | SHF_INTERRUPT | can_seek(fd), shl_spare);

	if ((cp = strchr(*wp, '?')) != NULL) {
		*cp = 0;
		if (isatty(fd)) {
			/* at&t ksh says it prints prompt on fd if it's open
			 * for writing and is a tty, but it doesn't do it
			 * (it also doesn't check the interactive flag,
			 * as is indicated in the Kornshell book).
			 */
			shellf("%s", cp+1);
		}
	}

	/* If we are reading from the co-process for the first time,
	 * make sure the other side of the pipe is closed first.  This allows
	 * the detection of eof.
	 *
	 * This is not compatible with at&t ksh... the fd is kept so another
	 * coproc can be started with same output, however, this means eof
	 * can't be detected...  This is why it is closed here.
	 * If this call is removed, remove the eof check below, too.
	 * coproc_readw_close(fd);
	 */

	if (history)
		Xinit(xs, xp, 128, ATEMP);
	expanding = 0;
	Xinit(cs, cp, 128, ATEMP);
	for (; *wp != NULL; wp++) {
		for (cp = Xstring(cs, cp); ; ) {
			if (c == '\n' || c == EOF)
				break;
			while (1) {
				c = shf_getc(shf);
				if (c == '\0')
					continue;
				if (c == EOF && shf_error(shf) &&
				    shf_errno(shf) == EINTR) {
					/* Was the offending signal one that
					 * would normally kill a process?
					 * If so, pretend the read was killed.
					 */
					ecode = fatal_trap_check();

					/* non fatal (eg, CHLD), carry on */
					if (!ecode) {
						shf_clearerr(shf);
						continue;
					}
				}
				break;
			}
			if (history) {
				Xcheck(xs, xp);
				Xput(xs, xp, c);
			}
			Xcheck(cs, cp);
			if (expanding) {
				expanding = 0;
				if (c == '\n') {
					c = 0;
					if (Flag(FTALKING_I) && isatty(fd)) {
						/* set prompt in case this is
						 * called from .profile or $ENV
						 */
						set_prompt(PS2, NULL);
						pprompt(prompt, 0);
					}
				} else if (c != EOF)
					Xput(cs, cp, c);
				continue;
			}
			if (expand && c == '\\') {
				expanding = 1;
				continue;
			}
			if (c == '\n' || c == EOF)
				break;
			if (ctype(c, C_IFS)) {
				if (Xlength(cs, cp) == 0 && ctype(c, C_IFSWS))
					continue;
				if (wp[1])
					break;
			}
			Xput(cs, cp, c);
		}
		/* strip trailing IFS white space from last variable */
		if (!wp[1])
			while (Xlength(cs, cp) && ctype(cp[-1], C_IFS) &&
			    ctype(cp[-1], C_IFSWS))
				cp--;
		Xput(cs, cp, '\0');
		vp = global(*wp);
		/* Must be done before setting export. */
		if (vp->flag & RDONLY) {
			shf_flush(shf);
			bi_errorf("%s is read only", *wp);
			return 1;
		}
		if (Flag(FEXPORT))
			typeset(*wp, EXPORT, 0, 0, 0);
		if (!setstr(vp, Xstring(cs, cp), KSH_RETURN_ERROR)) {
		    shf_flush(shf);
		    return 1;
		}
	}

	shf_flush(shf);
	if (history) {
		Xput(xs, xp, '\0');
		source->line++;
		histsave(source->line, Xstring(xs, xp), 1);
		Xfree(xs, xp);
	}
	/* if this is the co-process fd, close the file descriptor
	 * (can get eof if and only if all processes are have died, ie,
	 * coproc.njobs is 0 and the pipe is closed).
	 */
	if (c == EOF && !ecode)
		coproc_read_close(fd);

	return ecode ? ecode : c == EOF;
}
Пример #7
0
/* Encodes terminal modes for the terminal referenced by fd in a
   portable manner, and appends the modes to a buffer being
   constructed. Stores constructed buffers len to buf_len. This call
   always succeeds, but if an error happens during encoding, buf will
   be empty and buf_len will be 0 */
void ssh_encode_tty_flags(int fd, unsigned char **buf, size_t *buf_len)
     /*void tty_make_modes(int fd)*/
{
  SshBuffer buffer;  
#ifdef USING_TERMIOS
  struct termios tio;
#endif
#ifdef USING_SGTTY
  struct sgttyb tio;
  struct tchars tiotc;
  struct ltchars tioltc;
  int tiolm;
#ifdef TIOCGSTAT
  struct tstatus tiots;
#endif /* TIOCGSTAT */
#endif /* USING_SGTTY */
  int baud;

  if (!isatty(fd))
    {
      SSH_TRACE(2, ("Not a tty. (fd = %d)", fd));
      *buf = ssh_xstrdup("");
      *buf_len = 0;
      return;
    }
  
  ssh_buffer_init(&buffer);

  /* Get the modes. */
#ifdef USING_TERMIOS
  if (tcgetattr(fd, &tio) < 0)
    {
      PUT_CHAR(TTY_OP_END);
      ssh_warning("tcgetattr: %.100s", strerror(errno));
      goto error;
    }
#endif /* USING_TERMIOS */
#ifdef USING_SGTTY
  if (ioctl(fd, TIOCGETP, &tio) < 0)
    {
      PUT_CHAR(TTY_OP_END);
      ssh_warning("ioctl(fd, TIOCGETP, ...): %.100s", strerror(errno));
      goto error;
    }
  if (ioctl(fd, TIOCGETC, &tiotc) < 0)
    {
      PUT_CHAR(TTY_OP_END);
      ssh_warning("ioctl(fd, TIOCGETC, ...): %.100s", strerror(errno));
      goto error;
    }
  if (ioctl(fd, TIOCLGET, &tiolm) < 0)
    {
      PUT_CHAR(TTY_OP_END);
      ssh_warning("ioctl(fd, TIOCLGET, ...): %.100s", strerror(errno));
      goto error;
    }
  if (ioctl(fd, TIOCGLTC, &tioltc) < 0)
    {
      PUT_CHAR(TTY_OP_END);
      ssh_warning("ioctl(fd, TIOCGLTC, ...): %.100s", strerror(errno));
      goto error;
    }
#ifdef TIOCGSTAT
  if (ioctl(fd, TIOCGSTAT, &tiots) < 0) 
    {
      PUT_CHAR(TTY_OP_END);
      ssh_warning("ioctl(fd, TIOCGSTAT, ...): %.100s", strerror(errno));
      goto error;
    }
#endif /* TIOCGSTAT */
  /* termio's ECHOE is really both LCRTBS and LCRTERA - so wire them
     together */
  if (tiolm & LCRTBS)
    tiolm |= LCRTERA;
#endif /* USING_SGTTY */

  /* Store input and output baud rates. */
  baud = speed_to_baud(cfgetospeed(&tio));
  PUT_CHAR(TTY_OP_OSPEED);
  PUT_UINT32(baud);
  baud = speed_to_baud(cfgetispeed(&tio));
  PUT_CHAR(TTY_OP_ISPEED);
  PUT_UINT32(baud);

  /* Store values of mode flags. */
#ifdef USING_TERMIOS
#define TTYCHAR(NAME, OP) \
  PUT_CHAR(OP); PUT_UINT32(tio.c_cc[NAME]);
#define TTYMODE(NAME, FIELD, OP) \
  PUT_CHAR(OP); PUT_UINT32((tio.FIELD & NAME) != 0);
#define SGTTYCHAR(NAME, OP)
#define SGTTYMODE(NAME, FIELD, OP)
#define SGTTYMODEN(NAME, FIELD, OP)
#endif /* USING_TERMIOS */

#ifdef USING_SGTTY
#define TTYCHAR(NAME, OP)
#define TTYMODE(NAME, FIELD, OP)
#define SGTTYCHAR(NAME, OP) \
  PUT_CHAR(OP); PUT_UINT32(NAME);
#define SGTTYMODE(NAME, FIELD, OP) \
  PUT_CHAR(OP); PUT_UINT32((FIELD & NAME) != 0);
#define SGTTYMODEN(NAME, FIELD, OP) \
  PUT_CHAR(OP); PUT_UINT32((FIELD & NAME) == 0);
#endif /* USING_SGTTY */

#include "sshttyflagsi.h"

#undef TTYCHAR
#undef TTYMODE
#undef SGTTYCHAR
#undef SGTTYMODE
#undef SGTTYMODEN

  /* Mark end of mode data. */
  PUT_CHAR(TTY_OP_END);

  *buf_len = ssh_buffer_len(&buffer);
  *buf = ssh_xmemdup(ssh_buffer_ptr(&buffer), *buf_len);
  ssh_buffer_uninit(&buffer);

  SSH_DEBUG_HEXDUMP(5, ("encoded tty-flags buffer"), *buf, *buf_len);
  
  return;

 error:
  ssh_buffer_uninit(&buffer);
  *buf = ssh_xstrdup("");
  *buf_len = 0;
}
Пример #8
0
int main(int argc, char **argv)
{
  int c;
  int args;
  int ip=0;
  int verbose=0;
  int node=0;
  int tty=0;
  char lbuf[SZ_LINE];
  char tbuf[SZ_LINE];
  char *p;
  char *image=NULL;
  Finfo cur, tcur;

  /* we want the args in the same order in which they arrived, and
     gnu getopt sometimes changes things without this */
  putenv("POSIXLY_CORRECT=true");
  /* process switch arguments */
  while ((c = getopt(argc, argv, "i:v")) != -1){
    switch(c){
    case 'i':
      image = optarg;
      break;
    case 'v':
      verbose++;
      break;
    }
  }
  /* process remaining args */
  args = argc - optind;
  /* if image was specified, this is a batch job */
  if( image ){
    switch(args){
    case 0:
      /* get image info and exit */
      if( ProcessCmd("image", &image, 0, 0) == 0 ){
	FinfoFree(image);
	return 0;
      } else {
	return 1;
      }
      break;
    case 1:
      /* set image (no info returned) */
      if( ProcessCmd("image_", &image, 0, 0) != 0 ){
	return 1;
      }
      /* process command without args */
      if( ProcessCmd(argv[optind+0], NULL, 0, 0) == 0 ){
	FinfoFree(image);
	return 0;
      } else {
	return 1;
      }
      break;
    default:
      /* set image (no info returned) */
      if( ProcessCmd("image_", &image, 0, 0) != 0 ){
	return 1;
      }
      /* process command with args */
      if( ProcessCmd(argv[optind+0], &(argv[optind+1]), 0, 0) == 0 ){
	FinfoFree(image);
	return 0;
      } else {
	return 1;
      }
      break;
    }
  }
  /* stdout is connected to terminal => not connected to the node helper */
  if( isatty(1) ){
    node = 0;
    tty = 1;
  } else {
    node = 1;
    tty = 0;
  }
  /* initial prompt */
  if( !node ){
    fprintf(stdout, "js9helper> ");
    fflush(stdout);
  }
  /* command loop */
  while( fgets(lbuf, SZ_LINE-1, stdin) ){
    /* first arg: command */
    ip = 0;
    if( !word(lbuf, tbuf, &ip) ) continue;
    /* look for quit */
    if( !node ){
      if( !strcasecmp(tbuf, "quit") ){
	break;
      }
    }
    /* process this command */
    p = &lbuf[ip];
    ProcessCmd(tbuf, &p, node, tty);
    /* re-prompt, if necessary */
    if( !node ){
      fprintf(stdout, "js9helper> ");
      fflush(stdout);
    }
  }
  /* clean up */
  for(cur=finfohead; cur!=NULL; ){
    tcur = cur->next;
    _FinfoFree(cur);
    cur = tcur;
  }
  /* all done */
  return 0;
}
Пример #9
0
Файл: man.c Проект: haggaie/man
/*
 * Search for manual pages.
 *
 * If preformatted manual pages are supported, look for the formatted
 * file first, then the man page source file.  If they both exist and
 * the man page source file is newer, or only the source file exists,
 * try to reformat it and write the results in the cat directory.  If
 * it is not possible to write the cat file, simply format and display
 * the man file.
 *
 * If preformatted pages are not supported, or the troff option is
 * being used, only look for the man page source file.
 *
 * Note that globbing is necessary also if the section is given,
 * since a preformatted man page might be compressed.
 *
 */
static int
man (const char *name, const char *section) {
     int found, type, flags;
     struct manpage *mp;

     found = 0;

     /* allow  man ./manpage  for formatting explicitly given man pages */
     if (index(name, '/')) {
	  char fullname[BUFSIZE];
	  char fullpath[BUFSIZE];
	  char *path;
	  char *cp;
	  FILE *fp = fopen(name, "r");

	  if (!fp) {
	       perror(name);
	       return 0;
	  }
	  fclose (fp);
	  if (*name != '/' && getcwd(fullname, sizeof(fullname))
	      && strlen(fullname) + strlen(name) + 3 < sizeof(fullname)) {
	       strcat (fullname, "/");
	       strcat (fullname, name);
	  } else if (strlen(name) + 2 < sizeof(fullname)) {
	       strcpy (fullname, name);
	  } else {
	       fprintf(stderr, "%s: name too long\n", name);
	       return 0;
	  }

	  strcpy (fullpath, fullname);
	  if ((cp = rindex(fullpath, '/')) != NULL
	      && cp-fullpath+4 < sizeof(fullpath)) {
	       strcpy(cp+1, "..");
	       path = fullpath;
	  } else
	       path = ".";

	  name = ultimate_source (fullname);
	  if (!name)
	       return 0;

	  if (print_where) {
	       printf("%s\n", name);
	       return 1;
	  }
	  return display_man_file (path, name);
     }

     fflush (stdout);
     init_manpath();

     can_use_cache = nocache ? 0 : (preformat || print_where ||
		      (isatty(0) && isatty(1) && !setll()));

     if (do_troff) {
	  const char *t = getval("TROFF");
	  if (!t || !*t)
	       return 0;	/* don't know how to format */
	  type = TYPE_MAN;
     } else {
	  const char *n = getval("NROFF");
	  type = 0;
	  if (can_use_cache)
	       type |= TYPE_CAT;
	  if (n && *n)
	       type |= TYPE_MAN;
	  if (fhs || fsstnd)
	       type |= TYPE_SCAT;

	  n = getval("BROWSER");
	  if (n && *n)
	      type |= TYPE_HTML;
     }

     flags = type;
     if (!findall)
	  flags |= ONLY_ONE;
     if (fsstnd)
	  flags |= FSSTND;
     else if (fhs)
	  flags |= FHS;
     if (dohp)
	  flags |= DO_HP;
     if (do_irix)
	  flags |= DO_IRIX;
     if (do_win32)
	  flags |= DO_WIN32;

     mp = manfile(name, section, flags, section_list, mandirlist,
		  convert_to_cat);
     found = 0;
     while (mp) {
          if (mp->type == TYPE_MAN) {
	       found = format_and_display(mp->filename);
	  } else if (mp->type == TYPE_CAT || mp->type == TYPE_SCAT) {
               if (print_where) {
                    printf ("%s\n", mp->filename);
                    found = 1;
               } else
	            found = display_cat_file(mp->filename);
	  } else if (mp->type == TYPE_HTML) {
               if (print_where) {
                    printf ("%s\n", mp->filename);
                    found = 1;
               } else
	            found = display_html_file(mp->filename);
	  } else
	       /* internal error */
	       break;
	  if (found && !findall)
	       break;
	  mp = mp->next;
     }
     return found;
}
Пример #10
0
int main_vcfcall(int argc, char *argv[])
{
    char *ploidy_fname = NULL, *ploidy = NULL;
    args_t args;
    memset(&args, 0, sizeof(args_t));
    args.argc = argc; args.argv = argv;
    args.aux.prior_type = -1;
    args.aux.indel_frac = -1;
    args.aux.theta      = 1.1e-3;
    args.aux.pref       = 0.5;
    args.aux.min_perm_p = 0.01;
    args.aux.min_lrt    = 1;
    args.flag           = CF_ACGT_ONLY;
    args.output_fname   = "-";
    args.output_type    = FT_VCF;
    args.aux.trio_Pm_SNPs = 1 - 1e-8;
    args.aux.trio_Pm_ins  = args.aux.trio_Pm_del  = 1 - 1e-9;

    int c;
    static struct option loptions[] =
    {
        {"help",0,0,'h'},
        {"gvcf",1,0,'g'},
        {"format-fields",1,0,'f'},
        {"output",1,0,'o'},
        {"output-type",1,0,'O'},
        {"regions",1,0,'r'},
        {"regions-file",1,0,'R'},
        {"samples",1,0,'s'},
        {"samples-file",1,0,'S'},
        {"targets",1,0,'t'},
        {"targets-file",1,0,'T'},
        {"keep-alts",0,0,'A'},
        {"insert-missed",0,0,'i'},
        {"skip-Ns",0,0,'N'},            // now the new default
        {"keep-masked-refs",0,0,'M'},
        {"skip-variants",1,0,'V'},
        {"variants-only",0,0,'v'},
        {"consensus-caller",0,0,'c'},
        {"constrain",1,0,'C'},
        {"multiallelic-caller",0,0,'m'},
        {"pval-threshold",1,0,'p'},
        {"prior",1,0,'P'},
        {"chromosome-X",0,0,'X'},
        {"chromosome-Y",0,0,'Y'},
        {"novel-rate",1,0,'n'},
        {"ploidy",1,0,1},
        {"ploidy-file",1,0,2},
        {0,0,0,0}
    };

    char *tmp = NULL;
    while ((c = getopt_long(argc, argv, "h?o:O:r:R:s:S:t:T:ANMV:vcmp:C:XYn:P:f:ig:", loptions, NULL)) >= 0)
    {
        switch (c)
        {
            case 'g':
                args.flag |= CF_GVCF;
                args.gvcf.min_dp = strtol(optarg,&tmp,10);
                if ( *tmp ) error("Could not parse, expected integer argument: -g %s\n", optarg);
                break;
            case  2 : ploidy_fname = optarg; break;
            case  1 : ploidy = optarg; break;
            case 'X': ploidy = "X"; fprintf(stderr,"Warning: -X will be deprecated, please use --ploidy instead.\n"); break;
            case 'Y': ploidy = "Y"; fprintf(stderr,"Warning: -Y will be deprecated, please use --ploidy instead.\n"); break;
            case 'f': args.aux.output_tags |= parse_format_flag(optarg); break;
            case 'M': args.flag &= ~CF_ACGT_ONLY; break;     // keep sites where REF is N
            case 'N': args.flag |= CF_ACGT_ONLY; break;      // omit sites where first base in REF is N (the new default)
            case 'A': args.aux.flag |= CALL_KEEPALT; break;
            case 'c': args.flag |= CF_CCALL; break;          // the original EM based calling method
            case 'i': args.flag |= CF_INS_MISSED; break;
            case 'v': args.aux.flag |= CALL_VARONLY; break;
            case 'o': args.output_fname = optarg; break;
            case 'O':
                      switch (optarg[0]) {
                          case 'b': args.output_type = FT_BCF_GZ; break;
                          case 'u': args.output_type = FT_BCF; break;
                          case 'z': args.output_type = FT_VCF_GZ; break;
                          case 'v': args.output_type = FT_VCF; break;
                          default: error("The output type \"%s\" not recognised\n", optarg);
                      }
                      break;
            case 'C':
                      if ( !strcasecmp(optarg,"alleles") ) args.aux.flag |= CALL_CONSTR_ALLELES;
                      else if ( !strcasecmp(optarg,"trio") ) args.aux.flag |= CALL_CONSTR_TRIO;
                      else error("Unknown argument to -C: \"%s\"\n", optarg);
                      break;
            case 'V':
                      if ( !strcasecmp(optarg,"snps") ) args.flag |= CF_INDEL_ONLY;
                      else if ( !strcasecmp(optarg,"indels") ) args.flag |= CF_NO_INDEL;
                      else error("Unknown skip category \"%s\" (-S argument must be \"snps\" or \"indels\")\n", optarg);
                      break;
            case 'm': args.flag |= CF_MCALL; break;         // multiallelic calling method
            case 'p':
                args.aux.pref = strtod(optarg,&tmp);
                if ( *tmp ) error("Could not parse: --pval-threshold %s\n", optarg);
                break;
            case 'P': args.aux.theta = strtod(optarg,&tmp);
                      if ( *tmp ) error("Could not parse, expected float argument: -P %s\n", optarg);
                      break;
            case 'n': parse_novel_rate(&args,optarg); break;
            case 'r': args.regions = optarg; break;
            case 'R': args.regions = optarg; args.regions_is_file = 1; break;
            case 't': args.targets = optarg; break;
            case 'T': args.targets = optarg; args.targets_is_file = 1; break;
            case 's': args.samples_fname = optarg; break;
            case 'S': args.samples_fname = optarg; args.samples_is_file = 1; break;
            default: usage(&args);
        }
    }
    // Sanity check options and initialize
    if ( ploidy_fname ) args.ploidy = ploidy_init(ploidy_fname, 2);
    else if ( ploidy ) args.ploidy = init_ploidy(ploidy);

    if ( optind>=argc )
    {
        if ( !isatty(fileno((FILE *)stdin)) ) args.bcf_fname = "-";  // reading from stdin
        else usage(&args);
    }
    else args.bcf_fname = argv[optind++];

    if ( !ploidy_fname && !ploidy )
    {
        fprintf(stderr,"Note: Neither --ploidy nor --ploidy-file given, assuming all sites are diploid\n");
        args.ploidy = ploidy_init_string("",2);
    }

    if ( !args.ploidy ) error("Could not initialize ploidy\n");
    if ( args.flag & CF_GVCF )
    {
        // Force some flags to avoid unnecessary branching
        args.aux.flag &= ~CALL_KEEPALT;
        args.aux.flag |= CALL_VARONLY;
    }
    if ( (args.flag & CF_CCALL ? 1 : 0) + (args.flag & CF_MCALL ? 1 : 0) + (args.flag & CF_QCALL ? 1 : 0) > 1 ) error("Only one of -c or -m options can be given\n");
    if ( !(args.flag & CF_CCALL) && !(args.flag & CF_MCALL) && !(args.flag & CF_QCALL) ) error("Expected -c or -m option\n");
    if ( args.aux.n_perm && args.aux.ngrp1_samples<=0 ) error("Expected -1 with -U\n");    // not sure about this, please fix
    if ( args.aux.flag & CALL_CONSTR_ALLELES )
    {
        if ( !args.targets ) error("Expected -t or -T with \"-C alleles\"\n");
        if ( !(args.flag & CF_MCALL) ) error("The \"-C alleles\" mode requires -m\n");
    }
    if ( args.flag & CF_INS_MISSED && !(args.aux.flag&CALL_CONSTR_ALLELES) ) error("The -i option requires -C alleles\n");
    init_data(&args);

    while ( bcf_sr_next_line(args.aux.srs) )
    {
        bcf1_t *bcf_rec = args.aux.srs->readers[0].buffer[0];
        if ( args.samples_map ) bcf_subset(args.aux.hdr, bcf_rec, args.nsamples, args.samples_map);
        bcf_unpack(bcf_rec, BCF_UN_STR);

        // Skip unwanted sites
        if ( args.aux.flag & CALL_VARONLY )
        {
            int is_ref = 0;
            if ( bcf_rec->n_allele==1 ) is_ref = 1;     // not a variant
            else if ( bcf_rec->n_allele==2 )
            {
                // second allele is mpileup's X, not a variant
                if ( bcf_rec->d.allele[1][0]=='X' ) is_ref = 1;
                else if ( bcf_rec->d.allele[1][0]=='<' && bcf_rec->d.allele[1][1]=='X' && bcf_rec->d.allele[1][2]=='>' ) is_ref = 1;
                else if ( bcf_rec->d.allele[1][0]=='<' && bcf_rec->d.allele[1][1]=='*' && bcf_rec->d.allele[1][2]=='>' ) is_ref = 1;
            }
            if ( is_ref )
            {
                // gVCF output
                if ( args.flag & CF_GVCF ) gvcf_write(args.out_fh, &args.gvcf, args.aux.hdr, bcf_rec, 1);
                continue;
            }
        }
        if ( (args.flag & CF_INDEL_ONLY) && bcf_is_snp(bcf_rec) ) continue;    // not an indel
        if ( (args.flag & CF_NO_INDEL) && !bcf_is_snp(bcf_rec) ) continue;     // not a SNP
        if ( (args.flag & CF_ACGT_ONLY) && (bcf_rec->d.allele[0][0]=='N' || bcf_rec->d.allele[0][0]=='n') ) continue;   // REF[0] is 'N'

        bcf_unpack(bcf_rec, BCF_UN_ALL);
        if ( args.nsex ) set_ploidy(&args, bcf_rec);

        // Various output modes: QCall output (todo)
        if ( args.flag & CF_QCALL )
        {
            qcall(&args.aux, bcf_rec);
            continue;
        }

        // Calling modes which output VCFs
        int ret;
        if ( args.flag & CF_MCALL )
            ret = mcall(&args.aux, bcf_rec);
        else
            ret = ccall(&args.aux, bcf_rec);
        if ( ret==-1 ) error("Something is wrong\n");

        // gVCF output
        if ( args.flag & CF_GVCF )
        {
            gvcf_write(args.out_fh, &args.gvcf, args.aux.hdr, bcf_rec, ret?0:1);
            continue;
        }

        // Normal output
        if ( (args.aux.flag & CALL_VARONLY) && ret==0 ) continue;     // not a variant
        bcf_write1(args.out_fh, args.aux.hdr, bcf_rec);
    }
    if ( args.flag & CF_GVCF ) gvcf_write(args.out_fh, &args.gvcf, args.aux.hdr, NULL, 0);
    if ( args.flag & CF_INS_MISSED ) bcf_sr_regions_flush(args.aux.srs->targets);
    destroy_data(&args);
    return 0;
}
Пример #11
0
/*
 * setup:	Validate command args, initialize and perform sanity
 *		checks on options
 */
int
setup(int argc, char **argv)
{
	int c;
	int d_first;
	int eflag = 0;
	int iflag = 0;
	int wflag = 0;
	int cflag = 0;
	char *Lflag = NULL;

	if (isatty(fileno(stdout))) {
		/*
		 * defer diagnostics until processing is done
		 */
		if ((err = tmpfile()) == NULL) {
			err = stderr;
		       (void)fputs("Cannot defer diagnostic messages\n",stderr);
		       return(1);
		}
	} else
		err = stderr;
	while ((c = egetopt(argc, argv, "#adFfmrte?h:i?L:l:n?o:ps?w:")) != -1) {
		switch (c) {
		case '+':
			if ((pgnm = atoi(eoptarg)) < 1) {
			    (void)fputs("pr: +page number must be 1 or more\n",
				err);
			    return(1);
			}
			break;
		case '-':
			if ((clcnt = atoi(eoptarg)) < 1) {
			    (void)fputs("pr: -columns must be 1 or more\n",err);
			    return(1);
			}
			if (clcnt > 1)
				++cflag;
			break;
		case 'a':
			++across;
			break;
		case 'd':
			++dspace;
			break;
		case 'e':
			++eflag;
			if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
				inchar = *eoptarg++;
			else
				inchar = INCHAR;
			if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
				if ((ingap = atoi(eoptarg)) < 0) {
					(void)fputs(
					"pr: -e gap must be 0 or more\n", err);
					return(1);
				}
				if (ingap == 0)
					ingap = INGAP;
			} else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
				(void)fprintf(err,
				      "pr: invalid value for -e %s\n", eoptarg);
				return(1);
			} else
				ingap = INGAP;
			break;
		case 'f':
			++pausefst;
			/*FALLTHROUGH*/
		case 'F':
			++formfeed;
			break;
		case 'h':
			header = eoptarg;
			break;
		case 'i':
			++iflag;
			if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
				ochar = *eoptarg++;
			else
				ochar = OCHAR;
			if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
				if ((ogap = atoi(eoptarg)) < 0) {
					(void)fputs(
					"pr: -i gap must be 0 or more\n", err);
					return(1);
				}
				if (ogap == 0)
					ogap = OGAP;
			} else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
				(void)fprintf(err,
				      "pr: invalid value for -i %s\n", eoptarg);
				return(1);
			} else
				ogap = OGAP;
			break;
		case 'L':
			Lflag = eoptarg;
			break;
		case 'l':
			if (!isdigit((unsigned char)*eoptarg) || ((lines=atoi(eoptarg)) < 1)) {
				(void)fputs(
				 "pr: Number of lines must be 1 or more\n",err);
				return(1);
			}
			break;
		case 'm':
			++merge;
			break;
		case 'n':
			if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
				nmchar = *eoptarg++;
			else
				nmchar = NMCHAR;
			if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
				if ((nmwd = atoi(eoptarg)) < 1) {
					(void)fputs(
					"pr: -n width must be 1 or more\n",err);
					return(1);
				}
			} else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
				(void)fprintf(err,
				      "pr: invalid value for -n %s\n", eoptarg);
				return(1);
			} else
				nmwd = NMWD;
			break;
		case 'o':
			if (!isdigit((unsigned char)*eoptarg) || ((offst = atoi(eoptarg))< 1)){
				(void)fputs("pr: -o offset must be 1 or more\n",
					err);
				return(1);
			}
			break;
		case 'p':
			++pauseall;
			break;
		case 'r':
			++nodiag;
			break;
		case 's':
			++sflag;
			if (eoptarg == NULL)
				schar = SCHAR;
			else {
				schar = *eoptarg++;
				if (*eoptarg != '\0') {
					(void)fprintf(err,
					    "pr: invalid value for -s %s\n",
					    eoptarg);
					return(1);
				}
			}
			break;
		case 't':
			++nohead;
			break;
		case 'w':
			++wflag;
			if (!isdigit((unsigned char)*eoptarg) || ((pgwd = atoi(eoptarg)) < 1)){
				(void)fputs(
				   "pr: -w width must be 1 or more \n",err);
				return(1);
			}
			break;
		case '?':
		default:
			return(1);
		}
	}

	/*
	 * default and sanity checks
	 */
	if (!clcnt) {
		if (merge) {
			if ((clcnt = argc - eoptind) <= 1) {
				clcnt = CLCNT;
				merge = 0;
			}
		} else
			clcnt = CLCNT;
	}
	if (across) {
		if (clcnt == 1) {
			(void)fputs("pr: -a flag requires multiple columns\n",
				err);
			return(1);
		}
		if (merge) {
			(void)fputs("pr: -m cannot be used with -a\n", err);
			return(1);
		}
	}
	if (!wflag) {
		if (sflag)
			pgwd = SPGWD;
		else
			pgwd = PGWD;
	}
	if (cflag || merge) {
		if (!eflag) {
			inchar = INCHAR;
			ingap = INGAP;
		}
		if (!iflag) {
			ochar = OCHAR;
			ogap = OGAP;
		}
	}
	if (cflag) {
		if (merge) {
			(void)fputs(
			  "pr: -m cannot be used with multiple columns\n", err);
			return(1);
		}
		if (nmwd) {
			colwd = (pgwd + 1 - (clcnt * (nmwd + 2)))/clcnt;
			pgwd = ((colwd + nmwd + 2) * clcnt) - 1;
		} else {
			colwd = (pgwd + 1 - clcnt)/clcnt;
			pgwd = ((colwd + 1) * clcnt) - 1;
		}
		if (colwd < 1) {
			(void)fprintf(err,
			  "pr: page width is too small for %d columns\n",clcnt);
			return(1);
		}
	}
	if (!lines)
		lines = LINES;

	/*
	 * make sure long enough for headers. if not disable
	 */
	if (lines <= HEADLEN + TAILLEN)
		++nohead;
	else if (!nohead)
		lines -= HEADLEN + TAILLEN;

	/*
	 * adjust for double space on odd length pages
	 */
	if (dspace) {
		if (lines == 1)
			dspace = 0;
		else {
			if (lines & 1)
				++addone;
			lines /= 2;
		}
	}

	(void) setlocale(LC_TIME, (Lflag != NULL) ? Lflag : "");

	d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
	timefrmt = d_first ? TIMEFMTD : TIMEFMTM;

	return(0);
}
Пример #12
0
int main(int argc, char *argv[])
{
#ifdef QT_GUI_LIB
	QGuiApplication app(argc, argv);
#else
	QCoreApplication app(argc, argv);
#endif
	QCoreApplication::setApplicationName("Torkelnde Yamyams");
	QCoreApplication::setOrganizationName("Dominic Meiser");
	
	QCommandLineParser parser;
	parser.setApplicationDescription("34. BwInf Aufgabe 3 - Torkelnde Yamyams");
	parser.addHelpOption();
	QCommandLineOption fileOption(QStringList() << "f" << "file", "A file containing the description of a world.", "file");
	parser.addOption(fileOption);
	QCommandLineOption exampleOption(QStringList() << "e" << "example", "Use the given example from the BwInf.", "example");
	parser.addOption(exampleOption);
	parser.process(app);
	
	QString filename;
	if (parser.isSet(exampleOption))
		filename = ":/examples/" + parser.value(exampleOption);
	else if (parser.isSet(fileOption))
		filename = parser.value(fileOption);
	else
	{
		qCritical() << "No action specified. Use --help to display help.";
		return 1;
	}
	
	World *w = World::read(filename);
	if (!w)
	{
		qCritical() << "Failed to read world";
		return 1;
	}
	if (parser.isSet(fileOption))
	{
		QFileInfo info(filename);
		w->write(info.absoluteDir().absoluteFilePath(info.baseName() + ".orig.yyw"), false);
	}
	for (quint32 i = 0; i < w->height(); i++)
	{
		for (quint32 j = 0; j < w->width(); j++)
		{
			if (isatty(STDOUT_FILENO))
				printf("\033[%dm  \033[0m", colorCode(w->field(j, i)->type, World::UnknownState));
			else
				printf("%c ", static_cast<char>(w->field(j, i)->type));
		}
		printf("\n");
	}
	if (w->hasResult())
		qDebug() << "The loaded world already contains a solution";
	else
	{
		QTime t = QTime::currentTime();
		solveWorld(w);
		qDebug() << "solved the world in" << t.elapsed() << "ms";
	}
	for (quint32 i = 0; i < w->height(); i++)
	{
		for (quint32 j = 0; j < w->width(); j++)
		{
			if (isatty(STDOUT_FILENO))
				printf("\033[%dm  \033[0m", colorCode(w->field(j, i)->type, w->field(j, i)->state));
			else
				printf("%c ", static_cast<char>(w->field(j, i)->state == World::UnknownState ? w->field(j, i)->type : w->field(j, i)->state));
		}
		printf("\n");
	}
	if (parser.isSet(fileOption))
	{
		QFileInfo info(filename);
		w->write(info.absoluteDir().absoluteFilePath(info.baseName() + ".solved.yyw"), true);
#ifdef QT_GUI_LIB
		QImage *img = w->draw();
		if (img)
		{
			img->save(info.absoluteDir().absoluteFilePath(info.baseName()) + ".png", "PNG");
			delete img;
		}
#endif
	}
	
	return 0;
}
Пример #13
0
int main(int argc, char **argv)
{
	int ch, longindex, ret;
	unsigned long flags;
	struct option *long_options;
	const struct command *commands;
	const char *short_options;
	char *p;
	const struct sd_option *sd_opts;

	init_commands(&commands);

	if (argc < 3)
		usage(commands, 0);

	flags = setup_commands(commands, argv[1], argv[2]);

	optind = 3;

	sd_opts = build_sd_options(command_opts);
	long_options = build_long_options(sd_opts);
	short_options = build_short_options(sd_opts);

	while ((ch = getopt_long(argc, argv, short_options, long_options,
				&longindex)) >= 0) {

		switch (ch) {
		case 'a':
			sdhost = optarg;
			break;
		case 'p':
			sdport = strtol(optarg, &p, 10);
			if (optarg == p || sdport < 1 || sdport > UINT16_MAX) {
				fprintf(stderr, "Invalid port number '%s'\n", optarg);
				exit(EXIT_USAGE);
			}
			break;
		case 'r':
			raw_output = true;
			break;
		case 'h':
			subcommand_usage(argv[1], argv[2], EXIT_SUCCESS);
			break;
		case '?':
			usage(commands, EXIT_USAGE);
			break;
		default:
			if (command_parser)
				command_parser(ch, optarg);
			else
				usage(commands, EXIT_USAGE);
			break;
		}
	}

	if (!isatty(STDOUT_FILENO) || raw_output)
		highlight = false;

	if (flags & SUBCMD_FLAG_NEED_NODELIST) {
		ret = update_node_list(SD_MAX_NODES, 0);
		if (ret < 0) {
			fprintf(stderr, "Failed to get node list\n");
			exit(EXIT_SYSFAIL);
		}
	}

	if (flags & SUBCMD_FLAG_NEED_THIRD_ARG && argc == optind)
		subcommand_usage(argv[1], argv[2], EXIT_USAGE);

	return command_fn(argc, argv);
}
Пример #14
0
Файл: main.c Проект: 40a/jq
int main(int argc, char* argv[]) {
  jq_state *jq = NULL;
  int ret = 0;
  int compiled = 0;
  int parser_flags = 0;
  int nfiles = 0;
  int badwrite;
  jv program_arguments = jv_array();

#ifdef WIN32
  SetConsoleOutputCP(CP_UTF8);
  fflush(stdout);
  fflush(stderr);
  _setmode(fileno(stdout), _O_TEXT | _O_U8TEXT);
  _setmode(fileno(stderr), _O_TEXT | _O_U8TEXT);
  int wargc;
  wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &wargc);
  assert(wargc == argc);
  size_t arg_sz;
  for (int i = 0; i < argc; i++) {
    argv[i] = alloca((arg_sz = WideCharToMultiByte(CP_UTF8,
                                                   0,
                                                   wargv[i],
                                                   -1, 0, 0, 0, 0)));
    WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], arg_sz, 0, 0);
  }
#endif

  if (argc) progname = argv[0];

  jq = jq_init();
  if (jq == NULL) {
    perror("malloc");
    ret = 2;
    goto out;
  }

  int dumpopts = JV_PRINT_INDENT_FLAGS(2);
  const char* program = 0;

  jq_util_input_state *input_state = jq_util_input_init(NULL, NULL); // XXX add err_cb

  int further_args_are_files = 0;
  int jq_flags = 0;
  size_t short_opts = 0;
  jv lib_search_paths = jv_null();
  for (int i=1; i<argc; i++, short_opts = 0) {
    if (further_args_are_files) {
      jq_util_input_add_input(input_state, argv[i]);
      nfiles++;
    } else if (!strcmp(argv[i], "--")) {
      if (!program) usage(2);
      further_args_are_files = 1;
    } else if (!isoptish(argv[i])) {
      if (program) {
        jq_util_input_add_input(input_state, argv[i]);
        nfiles++;
      } else {
        program = argv[i];
      }
    } else {
      if (argv[i][1] == 'L') {
        if (jv_get_kind(lib_search_paths) == JV_KIND_NULL)
          lib_search_paths = jv_array();
        if (argv[i][2] != 0) { // -Lname (faster check than strlen)
            lib_search_paths = jv_array_append(lib_search_paths, jq_realpath(jv_string(argv[i]+2)));
        } else if (i >= argc - 1) {
          fprintf(stderr, "-L takes a parameter: (e.g. -L /search/path or -L/search/path)\n");
          die();
        } else {
          lib_search_paths = jv_array_append(lib_search_paths, jq_realpath(jv_string(argv[i+1])));
          i++;
        }
        continue;
      }

      if (isoption(argv[i], 's', "slurp", &short_opts)) {
        options |= SLURP;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'r', "raw-output", &short_opts)) {
        options |= RAW_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'c', "compact-output", &short_opts)) {
        dumpopts &= ~(JV_PRINT_TAB | JV_PRINT_INDENT_FLAGS(7));
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'C', "color-output", &short_opts)) {
        options |= COLOR_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'M', "monochrome-output", &short_opts)) {
        options |= NO_COLOR_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'a', "ascii-output", &short_opts)) {
        options |= ASCII_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "unbuffered", &short_opts)) {
        options |= UNBUFFERED_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'S', "sort-keys", &short_opts)) {
        options |= SORTED_OUTPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'R', "raw-input", &short_opts)) {
        options |= RAW_INPUT;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'n', "null-input", &short_opts)) {
        options |= PROVIDE_NULL;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'f', "from-file", &short_opts)) {
        options |= FROM_FILE;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'j', "join-output", &short_opts)) {
        options |= RAW_OUTPUT | RAW_NO_LF;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "tab", &short_opts)) {
        dumpopts &= ~JV_PRINT_INDENT_FLAGS(7);
        dumpopts |= JV_PRINT_TAB | JV_PRINT_PRETTY;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "indent", &short_opts)) {
        if (i >= argc - 1) {
          fprintf(stderr, "%s: --indent takes one parameter\n", progname);
          die();
        }
        dumpopts &= ~(JV_PRINT_TAB | JV_PRINT_INDENT_FLAGS(7));
        int indent = atoi(argv[i+1]);
        if (indent < -1 || indent > 7) {
          fprintf(stderr, "%s: --indent takes a number between -1 and 7\n", progname);
          die();
        }
        dumpopts |= JV_PRINT_INDENT_FLAGS(indent);
        i++;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "seq", &short_opts)) {
        options |= SEQ;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "stream", &short_opts)) {
        parser_flags |= JV_PARSE_STREAMING;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "stream-errors", &short_opts)) {
        parser_flags |= JV_PARSE_STREAM_ERRORS;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'e', "exit-status", &short_opts)) {
        options |= EXIT_STATUS;
        if (!short_opts) continue;
      }
      // FIXME: For --arg* we should check that the varname is acceptable
      if (isoption(argv[i], 0, "arg", &short_opts)) {
        if (i >= argc - 2) {
          fprintf(stderr, "%s: --arg takes two parameters (e.g. --arg varname value)\n", progname);
          die();
        }
        jv arg = jv_object();
        arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1]));
        arg = jv_object_set(arg, jv_string("value"), jv_string(argv[i+2]));
        program_arguments = jv_array_append(program_arguments, arg);
        i += 2; // skip the next two arguments
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "argjson", &short_opts)) {
        if (i >= argc - 2) {
          fprintf(stderr, "%s: --argjson takes two parameters (e.g. --argjson varname text)\n", progname);
          die();
        }
        jv v = jv_parse(argv[i+2]);
        if (!jv_is_valid(v)) {
          fprintf(stderr, "%s: invalid JSON text passed to --argjson\n", progname);
          die();
        }
        jv arg = jv_object();
        arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1]));
        arg = jv_object_set(arg, jv_string("value"), v);
        program_arguments = jv_array_append(program_arguments, arg);
        i += 2; // skip the next two arguments
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 0, "argfile", &short_opts) ||
          isoption(argv[i], 0, "slurpfile", &short_opts)) {
        const char *which;
        if (isoption(argv[i], 0, "argfile", &short_opts))
          which = "argfile";
        else
          which = "slurpfile";
        if (i >= argc - 2) {
          fprintf(stderr, "%s: --%s takes two parameters (e.g. --%s varname filename)\n", progname, which, which);
          die();
        }
        jv arg = jv_object();
        arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1]));
        jv data = jv_load_file(argv[i+2], 0);
        if (!jv_is_valid(data)) {
          data = jv_invalid_get_msg(data);
          fprintf(stderr, "%s: Bad JSON in --%s %s %s: %s\n", progname, which,
                  argv[i+1], argv[i+2], jv_string_value(data));
          jv_free(data);
          jv_free(arg);
          ret = 2;
          goto out;
        }
        if (isoption(argv[i], 0, "argfile", &short_opts) &&
            jv_get_kind(data) == JV_KIND_ARRAY && jv_array_length(jv_copy(data)) == 1)
            data = jv_array_get(data, 0);
        arg = jv_object_set(arg, jv_string("value"), data);
        program_arguments = jv_array_append(program_arguments, arg);
        i += 2; // skip the next two arguments
        if (!short_opts) continue;
      }
      if (isoption(argv[i],  0,  "debug-dump-disasm", &short_opts)) {
        options |= DUMP_DISASM;
        if (!short_opts) continue;
      }
      if (isoption(argv[i],  0,  "debug-trace", &short_opts)) {
        jq_flags |= JQ_DEBUG_TRACE;
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'h', "help", &short_opts)) {
        usage(0);
        if (!short_opts) continue;
      }
      if (isoption(argv[i], 'V', "version", &short_opts)) {
        printf("jq-%s\n", JQ_VERSION);
        ret = 0;
        goto out;
      }
      if (isoption(argv[i], 0, "run-tests", &short_opts)) {
        i++;
        // XXX Pass program_arguments, even a whole jq_state *, through;
        // could be useful for testing
        ret = jq_testsuite(lib_search_paths,
                           (options & DUMP_DISASM) || (jq_flags & JQ_DEBUG_TRACE),
                           argc - i, argv + i);
        goto out;
      }

      // check for unknown options... if this argument was a short option
      if (strlen(argv[i]) != short_opts + 1) {
        fprintf(stderr, "%s: Unknown option %s\n", progname, argv[i]);
        die();
      }
    }
  }

#ifdef USE_ISATTY
  if (isatty(STDOUT_FILENO)) {
    dumpopts |= JV_PRINT_ISATTY;
#ifndef WIN32
  /* Disable color by default on Windows builds as Windows
     terminals tend not to display it correctly */
    dumpopts |= JV_PRINT_COLOR;
#endif
  }
#endif
  if (options & SORTED_OUTPUT) dumpopts |= JV_PRINT_SORTED;
  if (options & ASCII_OUTPUT) dumpopts |= JV_PRINT_ASCII;
  if (options & COLOR_OUTPUT) dumpopts |= JV_PRINT_COLOR;
  if (options & NO_COLOR_OUTPUT) dumpopts &= ~JV_PRINT_COLOR;

  if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) {
    // Default search path list
    lib_search_paths = JV_ARRAY(jv_string("~/.jq"),
                                jv_string("$ORIGIN/../lib/jq"),
                                jv_string("$ORIGIN/lib"));
  }
  jq_set_attr(jq, jv_string("JQ_LIBRARY_PATH"), lib_search_paths);

  char *origin = strdup(argv[0]);
  if (origin == NULL) {
    fprintf(stderr, "Error: out of memory\n");
    exit(1);
  }
  jq_set_attr(jq, jv_string("JQ_ORIGIN"), jv_string(dirname(origin)));
  free(origin);

  if (strchr(JQ_VERSION, '-') == NULL)
    jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string(JQ_VERSION));
  else
    jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string_fmt("%.*s-master", (int)(strchr(JQ_VERSION, '-') - JQ_VERSION), JQ_VERSION));

#ifdef USE_ISATTY
  if (!program && (!isatty(STDOUT_FILENO) || !isatty(STDIN_FILENO)))
    program = ".";
#endif

  if (!program) usage(2);

  if (options & FROM_FILE) {
    char *program_origin = strdup(program);
    if (program_origin == NULL) {
      perror("malloc");
      exit(2);
    }

    jv data = jv_load_file(program, 1);
    if (!jv_is_valid(data)) {
      data = jv_invalid_get_msg(data);
      fprintf(stderr, "%s: %s\n", progname, jv_string_value(data));
      jv_free(data);
      ret = 2;
      goto out;
    }
    jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string(dirname(program_origin))));
    compiled = jq_compile_args(jq, skip_shebang(jv_string_value(data)), jv_copy(program_arguments));
    free(program_origin);
    jv_free(data);
  } else {
    jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string("."))); // XXX is this good?
    compiled = jq_compile_args(jq, program, jv_copy(program_arguments));
  }
  if (!compiled){
    ret = 3;
    goto out;
  }

  if (options & DUMP_DISASM) {
    jq_dump_disassembly(jq, 0);
    printf("\n");
  }

  if ((options & SEQ))
    parser_flags |= JV_PARSE_SEQ;

  if ((options & RAW_INPUT))
    jq_util_input_set_parser(input_state, NULL, (options & SLURP) ? 1 : 0);
  else
    jq_util_input_set_parser(input_state, jv_parser_new(parser_flags), (options & SLURP) ? 1 : 0);

  // Let jq program read from inputs
  jq_set_input_cb(jq, jq_util_input_next_input_cb, input_state);

  // Let jq program call `debug` builtin and have that go somewhere
  jq_set_debug_cb(jq, debug_cb, &dumpopts);

  if (nfiles == 0)
    jq_util_input_add_input(input_state, "-");

  if (options & PROVIDE_NULL) {
    ret = process(jq, jv_null(), jq_flags, dumpopts);
  } else {
    jv value;
    while (jq_util_input_errors(input_state) == 0 &&
           (jv_is_valid((value = jq_util_input_next_input(input_state))) || jv_invalid_has_msg(jv_copy(value)))) {
      if (jv_is_valid(value)) {
        ret = process(jq, value, jq_flags, dumpopts);
        continue;
      }

      // Parse error
      jv msg = jv_invalid_get_msg(value);
      if (!(options & SEQ)) {
        // --seq -> errors are not fatal
        ret = 4;
        fprintf(stderr, "parse error: %s\n", jv_string_value(msg));
        jv_free(msg);
        break;
      }
      fprintf(stderr, "ignoring parse error: %s\n", jv_string_value(msg));
      jv_free(msg);
    }
  }

  if (jq_util_input_errors(input_state) != 0)
    ret = 2;

out:
  badwrite = ferror(stdout);
  if (fclose(stdout)!=0 || badwrite) {
    fprintf(stderr,"Error: writing output failed: %s\n", strerror(errno));
    ret = 2;
  }

  jv_free(program_arguments);
  jq_util_input_free(&input_state);
  jq_teardown(&jq);
  if (ret >= 10 && (options & EXIT_STATUS))
    return ret - 10;
  if (ret >= 10)
    return 0;
  return ret;
}
Пример #15
0
/*
Open up UART port and begin redirect input/output from login shell.
*/
void *ttyS(char *port)
{
   struct termios term,stdIn,stdOut;
   fd_set rset;
   int fd, maxfd,selectval,nbytes;
   int sd=STDIN_FILENO;
   char buf[TRANSFER_BUFFER_SIZE];
   char devname[40];

  int ch,lastchar;
   /* connect to tty device write port */
   sprintf(devname,"/dev/tty%s",port);
   if( (fd=open(devname,O_RDWR | O_NOCTTY |O_NDELAY)) < 0 ){
	  fprintf(stderr,"can't open device %s\n",devname);
     return NULL;
   }
#ifdef DEBUG
   fprintf(stderr,"%s opened, fd=%d\n",devname,fd);
#endif   
   hndl =fd;
   fcntl(fd,F_SETFL,O_NONBLOCK); /* set non-blocking mode */
   if (tcgetattr(fd,&term) ){
      fprintf(stderr,"Can't get device attr.\n");
      close(fd);
      return NULL;
   }
   saved_termios = term; //save original termios
   if(signal(SIGINT,sig_catcher) == SIG_ERR) {
      fprintf(stderr,"Can't install signal SIGINT handler\n");
      close(fd);
      return NULL;
   }
   if(signal(SIGTERM,sig_catcher) == SIG_ERR) {
      fprintf(stderr,"Can't install signal SIGTERM handler\n");
      close(fd);
      return NULL;
   }
   if(signal(SIGHUP,sig_catcher) == SIG_ERR) {
      fprintf(stderr,"Can't install signal SIGHUP handler\n");
      close(fd);
      return NULL;
   }
    /* make the following file descriptors raw */
   
    if (isatty (0)) {
       tcgetattr(0,   &original_stdin);
       tcgetattr(1,   &original_stdout);
       tty_modified = 1;
       stdIn = original_stdin;
       stdOut = original_stdout;
       MAKE_TTY_RAW(0,  original_stdin);
       MAKE_TTY_RAW(1,  original_stdout);
    }
    
   cfmakeraw(&term);	/* raw mode */
   atexit(cleanup);

   cfsetispeed(&term,B115200); //B9600);
   cfsetospeed(&term,B115200); //B9600);
   tcsetattr(fd,TCSANOW,&term);
#ifdef DEBUG
   if (!tcgetattr(fd,&term) ){
	fprintf(stderr,"tty: ispeed=%d, ospeed = %d\n",\
	cfgetispeed(&term),cfgetospeed(&term));
    }
#endif    
   set_noecho(fd);
   set_noecho(STDOUT_FILENO);
   
#ifdef DEBUG
   if (!tcgetattr(STDIN_FILENO,&stdIn) ){
	fprintf(stderr,"STDIN: ispeed=%d, ospeed = %d\n",\
	cfgetispeed(&stdIn),cfgetospeed(&stdIn));
    }
#endif
   tcflush(fd,TCIOFLUSH);
   maxfd = ((sd > fd) ? sd:fd)+1;
  /*
   * Loop to read/write between remote client and host until 'esc  q' is received. 
   */
  for (;;)
    {
     FD_ZERO(&rset); 
      FD_SET (STDIN_FILENO, &rset);
      FD_SET (fd, &rset);
      selectval = select (maxfd, &rset, NULL, NULL, NULL);
      if (selectval == -1)
		{
		  syslog (LOG_ERR, "select(): %m");
		  break;
		}
      
      /*
	   * if client is readable, read from client, write to destination 
       */
      if (FD_ISSET (STDIN_FILENO, &rset))
		{
			  ch = getch();
			  if ((lastchar==0x1b) && (ch=='q')) {
#ifdef DEBUG				  
				  fprintf(stderr,"Esc-q received\n");
#endif				  
				  break;
			  }
			  write(fd,&ch,1);
			  lastchar = ch;
#ifdef DEBUG			  
			  if(lastchar == 0x1b)fprintf(stderr,"0x1b char received\n");
#endif			  
		}
      
      /*
	   * If destination is readable, read from destination, write to client. 
       */
      if (FD_ISSET (fd, &rset))
		{
		  nbytes = read(fd, &buf, TRANSFER_BUFFER_SIZE);
		  if (nbytes <= 0)
		    {
    	      fprintf(stderr,"server close connection\n");
		      break;
		    }
	  
		  if (write (STDOUT_FILENO, &buf, nbytes) != nbytes)
		    syslog(LOG_ERR, "Error on write %m");
	  
		  nbytes -= nbytes;
		}
    }
  
    cleanup();
#ifdef DEBUG    
   fprintf(stderr,"thread exit\n");
#endif   
   tcsetattr(hndl,TCSANOW,&saved_termios);
  return NULL;

}
Пример #16
0
int     main(int argc, char **argv)
{
    char   *script;
    struct stat st;
    char   *slash;
    int     fd;
    int     ch;
    ARGV   *import_env;
    static const CONFIG_STR_TABLE str_table[] = {
	VAR_SENDMAIL_PATH, DEF_SENDMAIL_PATH, &var_sendmail_path, 1, 0,
	VAR_MAILQ_PATH, DEF_MAILQ_PATH, &var_mailq_path, 1, 0,
	VAR_NEWALIAS_PATH, DEF_NEWALIAS_PATH, &var_newalias_path, 1, 0,
	VAR_MANPAGE_DIR, DEF_MANPAGE_DIR, &var_manpage_dir, 1, 0,
	VAR_SAMPLE_DIR, DEF_SAMPLE_DIR, &var_sample_dir, 1, 0,
	VAR_README_DIR, DEF_README_DIR, &var_readme_dir, 1, 0,
	VAR_HTML_DIR, DEF_HTML_DIR, &var_html_dir, 1, 0,
	0,
    };
    int     force_single_instance;
    ARGV   *my_argv;

    /*
     * Fingerprint executables and core dumps.
     */
    MAIL_VERSION_STAMP_ALLOCATE;

    /*
     * Be consistent with file permissions.
     */
    umask(022);

    /*
     * To minimize confusion, make sure that the standard file descriptors
     * are open before opening anything else. XXX Work around for 44BSD where
     * fstat can return EBADF on an open file descriptor.
     */
    for (fd = 0; fd < 3; fd++)
	if (fstat(fd, &st) == -1
	    && (close(fd), open("/dev/null", O_RDWR, 0)) != fd)
	    msg_fatal("open /dev/null: %m");

    /*
     * Set up diagnostics. XXX What if stdin is the system console during
     * boot time? It seems a bad idea to log startup errors to the console.
     * This is UNIX, a system that can run without hand holding.
     */
    if ((slash = strrchr(argv[0], '/')) != 0 && slash[1])
	argv[0] = slash + 1;
    if (isatty(STDERR_FILENO))
	msg_vstream_init(argv[0], VSTREAM_ERR);
    msg_syslog_init(argv[0], LOG_PID, LOG_FACILITY);

    /*
     * Check the Postfix library version as soon as we enable logging.
     */
    MAIL_VERSION_CHECK;

    /*
     * The mail system must be run by the superuser so it can revoke
     * privileges for selected operations. That's right - it takes privileges
     * to toss privileges.
     */
    if (getuid() != 0) {
	msg_error("to submit mail, use the Postfix sendmail command");
	msg_fatal("the postfix command is reserved for the superuser");
    }
    if (unsafe() != 0)
	msg_fatal("the postfix command must not run as a set-uid process");

    /*
     * Parse switches.
     */
    while ((ch = GETOPT(argc, argv, "c:Dv")) > 0) {
	switch (ch) {
	default:
	    msg_fatal("usage: %s [-c config_dir] [-Dv] command", argv[0]);
	case 'c':
	    if (*optarg != '/')
		msg_fatal("-c requires absolute pathname");
	    check_setenv(CONF_ENV_PATH, optarg);
	    break;
	case 'D':
	    check_setenv(CONF_ENV_DEBUG, "");
	    break;
	case 'v':
	    msg_verbose++;
	    check_setenv(CONF_ENV_VERB, "");
	    break;
	}
    }
    force_single_instance = (getenv(CONF_ENV_PATH) != 0);

    /*
     * Copy a bunch of configuration parameters into the environment for easy
     * access by the maintenance shell script.
     */
    mail_conf_read();
    get_mail_conf_str_table(str_table);

    /*
     * Environment import filter, to enforce consistent behavior whether this
     * command is started by hand, or at system boot time. This is necessary
     * because some shell scripts use environment settings to override
     * main.cf settings.
     */
    import_env = argv_split(var_import_environ, ", \t\r\n");
    clean_env(import_env->argv);
    argv_free(import_env);

    check_setenv("PATH", ROOT_PATH);		/* sys_defs.h */
    check_setenv(CONF_ENV_PATH, var_config_dir);/* mail_conf.h */

    check_setenv(VAR_COMMAND_DIR, var_command_dir);	/* main.cf */
    check_setenv(VAR_DAEMON_DIR, var_daemon_dir);	/* main.cf */
    check_setenv(VAR_DATA_DIR, var_data_dir);	/* main.cf */
    check_setenv(VAR_QUEUE_DIR, var_queue_dir);	/* main.cf */
    check_setenv(VAR_CONFIG_DIR, var_config_dir);	/* main.cf */

    /*
     * Do we want to keep adding things here as shell scripts evolve?
     */
    check_setenv(VAR_MAIL_OWNER, var_mail_owner);	/* main.cf */
    check_setenv(VAR_SGID_GROUP, var_sgid_group);	/* main.cf */
    check_setenv(VAR_SENDMAIL_PATH, var_sendmail_path);	/* main.cf */
    check_setenv(VAR_MAILQ_PATH, var_mailq_path);	/* main.cf */
    check_setenv(VAR_NEWALIAS_PATH, var_newalias_path);	/* main.cf */
    check_setenv(VAR_MANPAGE_DIR, var_manpage_dir);	/* main.cf */
    check_setenv(VAR_SAMPLE_DIR, var_sample_dir);	/* main.cf */
    check_setenv(VAR_README_DIR, var_readme_dir);	/* main.cf */
    check_setenv(VAR_HTML_DIR, var_html_dir);	/* main.cf */

    /*
     * Make sure these directories exist. Run the maintenance scripts with as
     * current directory the mail database.
     */
    if (chdir(var_command_dir))
	msg_fatal("chdir(%s): %m", var_command_dir);
    if (chdir(var_daemon_dir))
	msg_fatal("chdir(%s): %m", var_daemon_dir);
    if (chdir(var_queue_dir))
	msg_fatal("chdir(%s): %m", var_queue_dir);

    /*
     * Run the management script.
     */
    if (force_single_instance
	|| argv_split(var_multi_conf_dirs, "\t\r\n, ")->argc == 0) {
	script = concatenate(var_daemon_dir, "/postfix-script", (char *) 0);
	if (optind < 1)
	    msg_panic("bad optind value");
	argv[optind - 1] = script;
	execvp(script, argv + optind - 1);
	msg_fatal("%s: %m", script);
    }

    /*
     * Hand off control to a multi-instance manager.
     */
    else {
	if (*var_multi_wrapper == 0)
	    msg_fatal("multi-instance support is requested, but %s is empty",
		      VAR_MULTI_WRAPPER);
	my_argv = argv_split(var_multi_wrapper, " \t\r\n");
	do {
	    argv_add(my_argv, argv[optind], (char *) 0);
	} while (argv[optind++] != 0);
	execvp(my_argv->argv[0], my_argv->argv);
	msg_fatal("%s: %m", my_argv->argv[0]);
    }
}
Пример #17
0
int main(int argc, char **real_argv, const char * const *envv)
{
	CAP *cap;
	char **argv = (char **)real_argv;
	struct stat sbuf;
	char *s;
	char *t;
	time_t time_rc;
	char *run;
#ifdef __MSDOS__
	char *rundir;
#endif
	SCRN *n;
	int opened = 0;
	int omid;
	int backopt;
	int c;

	joe_iswinit();
	joe_locale();

	mainenv = envv;
	
	vmem = vtmp();
	startup_log = bfind_scratch("* Startup Log *");
	startup_log->internal = 1;
	startup_log->current_dir = vsncpy(NULL, 0, NULL, 0);

#ifdef __MSDOS__
	_fmode = O_BINARY;
	zlcpy(stdbuf, SIZEOF(stdbuf), argv[0]);
	joesep(stdbuf);
	run = namprt(stdbuf);
	rundir = dirprt(stdbuf);
	for (c = 0; run[c]; ++c)
		if (run[c] == '.') {
			run = vstrunc(run, c);
			break;
		}
#else
	run = namprt(argv[0]);
#endif

	if ((s = getenv("LINES")) != NULL)
		env_lines = ztoi(s);
	if ((s = getenv("COLUMNS")) != NULL)
		env_columns = ztoi(s);
	if ((s = getenv("BAUD")) != NULL)
		Baud = ztoi(s);
	if (getenv("DOPADDING"))
		dopadding = 1;
	if (getenv("NOXON"))
		noxon = 1;
	if ((s = getenv("JOETERM")) != NULL)
		joeterm = s;

#ifndef __MSDOS__
	if (!(cap = my_getcap(NULL, 9600, NULL, NULL))) {
		logerror_0(joe_gettext(_("Couldn't load termcap/terminfo entry\n")));
		goto exit_errors;
	}
#endif

#ifdef __MSDOS__

	s = vsncpy(NULL, 0, sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1(joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}

	vsrm(s);
	s = vsncpy(NULL, 0, sv(rundir));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1(joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}
#else

	/* Name of system joerc file.  Try to find one with matching language... */
	
	/* Try full language: like joerc.de_DE */
	t = vsncpy(NULL, 0, sc(JOERC));
	t = vsncpy(sv(t), sv(run));
	t = vsncpy(sv(t), sc("rc."));
	t = vsncpy(sv(t), sz(locale_msgs));
	if (!stat(t,&sbuf))
		time_rc = sbuf.st_mtime;
	else {
		/* Try generic language: like joerc.de */
		if (locale_msgs[0] && locale_msgs[1] && locale_msgs[2]=='_') {
			vsrm(t);
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc."));
			t = vsncpy(sv(t), locale_msgs, 2);
			if (!stat(t,&sbuf))
				time_rc = sbuf.st_mtime;
			else
				goto nope;
		} else {
			nope:
			vsrm(t);
			/* Try Joe's bad english */
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc"));
			if (!stat(t,&sbuf))
				time_rc = sbuf.st_mtime;
			else
				time_rc = 0;
		}
	}

	/* User's joerc file */
	s = getenv("HOME");
	if (s) {
		s = vsncpy(NULL, 0, sz(s));
		s = vsncpy(sv(s), sc("/."));
		s = vsncpy(sv(s), sv(run));
		s = vsncpy(sv(s), sc("rc"));

		if (!stat(s,&sbuf)) {
			if (sbuf.st_mtime < time_rc) {
				logmessage_2(joe_gettext(_("Warning: %s is newer than your %s.\n")),t,s);
			}
		}

		c = procrc(cap, s);
		if (c == 0) {
			vsrm(t);
			goto donerc;
		}
		if (c == 1) {
			logerror_1(joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
		}
	}

	vsrm(s);
	s = t;
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1(joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}

	/* Try built-in joerc */
	s = vsncpy(NULL, 0, sc("*"));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c != 0 && c != 1) {
		/* If *fancyjoerc not present, use *joerc which is always there */
		s = vstrunc(s, 0);
		s = vsncpy(sv(s),sc("*joerc"));
		c = procrc(cap, s);
	}
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1(joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}
#endif

	logerror_1(joe_gettext(_("Couldn't open '%s'\n")), s);
	goto exit_errors;
	return 1;

	donerc:

	if (validate_rc()) {
		logerror_0(joe_gettext(_("rc file has no :main key binding section or no bindings.  Bye.\n")));
		goto exit_errors;
	}

	{
		char buf[10];
		ptrdiff_t x;
		zlcpy(buf, SIZEOF(buf), "\"`\"	`  ");
		type_backtick = mparse(0, buf, &x, 0);
	}

	shell_kbd = mkkbd(kmap_getcontext("shell"));

	if (!isatty(fileno(stdin)))
		idleout = 0;

	for (c = 1; argv[c]; ++c) {
		if (argv[c][0] == '-') {
			if (argv[c][1])
				switch (glopt(argv[c] + 1, argv[c + 1], NULL, 1)) {
				case 0:
					logerror_1(joe_gettext(_("Unknown option '%s'\n")), argv[c]);
					break;
				case 1:
					break;
				case 2:
					++c;
					break;
			} else
				idleout = 0;
		}
	}

	/* initialize mouse support */
	if (xmouse && (s=getenv("TERM")) && zstr(s,"xterm"))
		usexmouse=1;

	if (!(n = nopen(cap)))
		goto exit_errors;
	maint = screate(n);

	load_state();

	/* It would be better if this ran uedit() to load files */

	/* The business with backopt is to load the file first, then apply file
	 * local options afterwords */

	/* orphan is not compatible with exemac()- macros need a window to exist */
	for (c = 1, backopt = 0; argv[c]; ++c)
		if (argv[c][0] == '+' && argv[c][1]>='0' && argv[c][1]<='9') {
			if (!backopt)
				backopt = c;
		} else if (argv[c][0] == '-' && argv[c][1]) {
			if (!backopt)
				backopt = c;
			if (glopt(argv[c] + 1, argv[c + 1], NULL, 0) == 2)
				++c;
		} else {
			B *b = bfind(argv[c]);
			BW *bw = NULL;
			int er = berror;

			/* This is too annoying */
			/* set_current_dir(argv[c],1); */

			setup_history(&filehist);
			append_history(filehist,sz(argv[c]));

			/* wmktw inserts the window before maint->curwin */
			if (!orphan || !opened) {
				bw = wmktw(maint, b);
				if (er)
					msgnwt(bw->parent, joe_gettext(msgs[-er]));
			} else {
				off_t line;
				b->orphan = 1;
				b->oldcur = pdup(b->bof, "main");
				pline(b->oldcur, get_file_pos(b->name));
				p_goto_bol(b->oldcur);
				line = b->oldcur->line - (maint->h - 1) / 2;
				if (line < 0)
					line = 0;
				b->oldtop = pdup(b->oldcur, "main");
				pline(b->oldtop, line);
				p_goto_bol(b->oldtop);
			}
			if (bw) {
				off_t lnum = 0;

				bw->o.readonly = bw->b->rdonly;
				if (backopt) {
					while (backopt != c) {
						if (argv[backopt][0] == '+') {
							lnum = ztoo(argv[backopt] + 1);
							++backopt;
						} else {
							if (glopt(argv[backopt] + 1, argv[backopt + 1], &bw->o, 0) == 2)
								backopt += 2;
							else
								backopt += 1;
							/* lazy_opts(bw->b, &bw->o); */
						}
					}
				}
				/* bw->b->o = bw->o; */
				lazy_opts(bw->b, &bw->o);
				bw->b->rdonly = bw->o.readonly;
				/* Put cursor in window, so macros work properly */
				maint->curwin = bw->parent;
				/* Execute macro */
				if (er == -1 && bw->o.mnew)
					exmacro(bw->o.mnew, 1, NO_MORE_DATA);
				if (er == 0 && bw->o.mold)
					exmacro(bw->o.mold, 1, NO_MORE_DATA);
				/* Hmm... window might not exist any more... depends on what macro does... */
				if (lnum > 0)
					pline(bw->cursor, lnum - 1);
				else
					pline(bw->cursor, get_file_pos(bw->b->name));
				p_goto_bol(bw->cursor);
				/* Go back to first window so windows are in same order as command line  */
				if (opened)
					wnext(maint);
				
			}
			opened = 1;
			backopt = 0;
		}

	

	if (opened) {
		wshowall(maint);
		omid = opt_mid;
		opt_mid = 1;
		dofollows();
		opt_mid = omid;
	} else {
		BW *bw = wmktw(maint, bfind(""));

		if (bw->o.mnew)
			exmacro(bw->o.mnew, 1, NO_MORE_DATA);
	}
	maint->curwin = maint->topwin;

	if (logerrors) {
		B *copied = bcpy(startup_log->bof, startup_log->eof);
		BW *bw = wmktw(maint, copied);
		copied->name = zdup(startup_log->name);
		copied->internal = 1;
		maint->curwin = bw->parent;
		wshowall(maint);
	}

	if (help) {
		help_on(maint);
	}
	if (!nonotice) {
		if (xmsg) {
			xmsg = stagen(NULL, (BW *)(lastw(maint)->object), xmsg, ' ');
			msgnw(((BASE *)lastw(maint)->object)->parent, xmsg);
		} else {
			joe_snprintf_3(msgbuf,JOE_MSGBUFSIZE,joe_gettext(_("\\i** Joe's Own Editor v%s ** (%s) ** Copyright %s 2015 **\\i")),VERSION,locale_map->name,(locale_map->type ? "©" : "(C)"));
			msgnw(((BASE *)lastw(maint)->object)->parent, msgbuf);
		}

	}

	if (!idleout) {
		if (!isatty(fileno(stdin)) && modify_logic((BW *)maint->curwin->object, ((BW *)maint->curwin->object)->b)) {
			/* Start shell going in first window */
			char **a;
			char *cmd;

			a = vamk(10);
			cmd = vsncpy(NULL, 0, sc("/bin/sh"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("-c"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("/bin/cat"));
			a = vaadd(a, cmd);
			
			cstart ((BW *)maint->curwin->object, "/bin/sh", a, NULL, NULL, 0, 1, NULL, 0);
		}
	}

	edloop(0);

	save_state();

	/* Delete all buffer so left over locks get eliminated */
	brmall();

	vclose(vmem);
	nclose(n);

	if  (noexmsg) {
		if (notite)
			fprintf(stderr, "\n");
	} else {
		if (exmsg)
			fprintf(stderr, "\n%s\n", exmsg);
		else if (notite)
			fprintf(stderr, "\n");
	}

	return 0;

exit_errors:

	/* Write out error log to console if we are exiting with errors. */
	if (startup_log && startup_log->eof->byte)
		bsavefd(startup_log->bof, 2, startup_log->eof->byte);
	
	return 1;
}
Пример #18
0
int main (int argc, char *argv[]) {
    Display *dpy;
    int nScreens, screenNum, i;
    enum INFO_FUNC func = LIST;
    char *funcArg = NULL;
    char *dpyName = NULL;

    GetScreenDriver = (glXGetScreenDriver_t *)glXGetProcAddressARB ((const GLubyte *)"glXGetScreenDriver");
    GetDriverConfig = (glXGetDriverConfig_t *)glXGetProcAddressARB ((const GLubyte *)"glXGetDriverConfig");
    if (!GetScreenDriver || !GetDriverConfig) {
	fprintf (stderr, "libGL is too old.\n");
	return 1;
    }

  /* parse the command line */
    for (i = 1; i < argc; ++i) {
	char **argPtr = NULL;
	if (!strcmp (argv[i], "-display"))
	    argPtr = &dpyName;
	else if (!strcmp (argv[i], "nscreens"))
	    func = NSCREENS;
	else if (!strcmp (argv[i], "driver")) {
	    func = DRIVER;
	    argPtr = &funcArg;
	} else if (!strcmp (argv[i], "options")) {
	    func = OPTIONS;
	    argPtr = &funcArg;
	} else {
	    printUsage ();
	    return 1;
	}
	if (argPtr) {
	    if (++i == argc) {
		printUsage ();
		return 1;
	    }
	    *argPtr = argv[i];
	}
    }

  /* parse screen number argument */
    if (func == DRIVER || func == OPTIONS) {
	if (sscanf (funcArg, "%i", &screenNum) != 1)
	    screenNum = -1;
	else if (screenNum < 0) {
	    fprintf (stderr, "Negative screen number \"%s\".\n", funcArg);
	    return 1;
	}
    }
  /* if the argument to the options command is a driver name, we can handle
   * it without opening an X connection */
    if (func == OPTIONS && screenNum == -1) {
	const char *options = (*GetDriverConfig) (funcArg);
	if (!options) {
	    fprintf (stderr,
		     "Driver \"%s\" is not installed or does not support configuration.\n",
		     funcArg);
	    return 1;
	}
	printf ("%s", options);
	if (isatty (STDOUT_FILENO))
	    printf ("\n");
	return 0;
    } 
  /* driver command needs a valid screen number */
    else if (func == DRIVER && screenNum == -1) {
	fprintf (stderr, "Invalid screen number \"%s\".\n", funcArg);
	return 1;
    }

  /* open display and count the number of screens */
    if (!(dpy = XOpenDisplay (dpyName))) {
	fprintf (stderr, "Error: Couldn't open display\n");
	return 1;
    }
    nScreens = ScreenCount (dpy);

  /* final check on the screen number argument (if any)*/
    if ((func == DRIVER || func == OPTIONS) && screenNum >= nScreens) {
	fprintf (stderr, "Screen number \"%d\" out of range.\n", screenNum);
	return 1;
    }

    switch (func) {
      case NSCREENS:
	printf ("%d", nScreens);
	if (isatty (STDOUT_FILENO))
	    printf ("\n");
	break;
      case DRIVER: {
	  const char *name = (*GetScreenDriver) (dpy, screenNum);
	  if (!name) {
	      fprintf (stderr, "Screen \"%d\" is not direct rendering capable.\n",
		       screenNum);
	      return 1;
	  }
	  printf ("%s", name);
	  if (isatty (STDOUT_FILENO))
	      printf ("\n");
	  break;
      }
      case OPTIONS: {
	  const char *name = (*GetScreenDriver) (dpy, screenNum), *options;
	  if (!name) {
	      fprintf (stderr, "Screen \"%d\" is not direct rendering capable.\n",
		       screenNum);
	      return 1;
	  }
	  options = (*GetDriverConfig) (name);
	  if (!options) {
	      fprintf (stderr,
		       "Driver \"%s\" is not installed or does not support configuration.\n",
		       name);
	      return 1;
	  }
	  printf ("%s", options);
	  if (isatty (STDOUT_FILENO))
	      printf ("\n");
	  break;
      }
      case LIST:
	for (i = 0; i < nScreens; ++i) {
	    const char *name = (*GetScreenDriver) (dpy, i);
	    if (name)
		printf ("Screen %d: %s\n", i, name);
	    else
		printf ("Screen %d: not direct rendering capable.\n", i);
	}
    }

    return 0;
}
Пример #19
0
int
main(int argc, char **argv)
#endif
{
    int i;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    setuid(getuid());
#endif

#if defined(MSDOS) && !defined(_Windows) && !defined(__GNUC__)
    PC_setup();
#endif /* MSDOS !Windows */

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    int rc;
#ifdef OS2_IPC
    char semInputReadyName[40];
    sprintf( semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid() );
    rc = DosCreateEventSem(semInputReadyName,&semInputReady,0,0);
    if (rc != 0)
      fputs("DosCreateEventSem error\n",stderr);
#endif
    rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif

/* get helpfile from home directory */
#ifdef __DJGPP__
    {
	char *s;
	strcpy(HelpFile, argv[0]);
	for (s = HelpFile; *s; s++)
	    if (*s == DIRSEP1)
		*s = DIRSEP2;	/* '\\' to '/' */
	strcpy(strrchr(HelpFile, DIRSEP2), "/gnuplot.gih");
    }			/* Add also some "paranoid" tests for '\\':  AP */
#endif /* DJGPP */

#ifdef VMS
    unsigned int status[2] = { 1, 0 };
#endif

#if defined(HAVE_LIBEDITLINE)
    rl_getc_function = getc_wrapper;
#endif

#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc'
     * or gnuplot specific commands in '.editrc' (when using editline
     * instead of readline) */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
#if defined(HAVE_LIBREADLINE)
    using_history();
#else
    history_init();
#endif
#endif
#if defined(HAVE_LIBREADLINE) && !defined(MISSING_RL_TILDE_EXPANSION)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION] ... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -d  --default-settings\n"
		    "  -c  scriptfile ARG1 ARG2 ... \n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
#ifdef DEVELOPMENT_VERSION
	    printf(
#ifdef DIST_CONTACT
		    "Report bugs to "DIST_CONTACT"\n"
		    "            or %s\n",
#else
		    "Report bugs to %s\n",
#endif
		    bug_email);
#endif
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")
#ifdef _Windows
		|| !stricmp(argv[i], "-noend") || !stricmp(argv[i], "/noend")
#endif
		) {
	    persist_cl = TRUE;
	} else if (!strncmp(argv[i], "-d", 2) || !strcmp(argv[i], "--default-settings")) {
	    /* Skip local customization read from ~/.gnuplot */
	    skip_gnuplotrc = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* This was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

    /* Switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * Do any non-X platforms suffer from this problem?
     * EAM - Jan 2013 YES.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);

#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    /* "pi" is hard-wired as the first variable */
    (void) add_udv_by_name("GNUTERM");
    (void) add_udv_by_name("NaN");
    init_constants();
    udv_user_head = &(udv_NaN->next_udv);

    init_memory();

    interactive = FALSE;
    init_terminal();		/* can set term type if it likes */
    push_terminal(0);		/* remember the default terminal */

    /* reset the terminal when exiting */
    /* this is done through gp_atexit so that other terminal functions
     * can be registered to be executed before the terminal is reset. */
    gp_atexit(term_reset);

# if defined(WIN32) && !defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif

    /* Note: we want to know whether this is an interactive session so that we can
     * decide whether or not to write status information to stderr.  The old test
     * for this was to see if (argc > 1) but the addition of optional command line
     * switches broke this.  What we really wanted to know was whether any of the
     * command line arguments are file names or an explicit in-line "-e command".
     */
    for (i = 1; i < argc; i++) {
# ifdef _Windows
	if (!stricmp(argv[i], "/noend"))
	    continue;
# endif
	if ((argv[i][0] != '-') || (argv[i][1] == 'e') || (argv[i][1] == 'c') ) {
	    interactive = FALSE;
	    break;
	}
    }

    /* Need this before show_version is called for the first time */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

#ifdef WGP_CONSOLE
#ifdef CONSOLE_SWITCH_CP
    if (cp_changed && interactive) {
	fprintf(stderr,
	    "\ngnuplot changed the codepage of this console from %i to %i to\n" \
	    "match the graph window. Some characters might only display correctly\n" \
	    "if you change the font to a non-raster type.\n",
	    cp_input, GetConsoleCP());
    }
#else
    if ((GetConsoleCP() != GetACP()) && interactive) {
	fprintf(stderr,
	    "\nWarning: The codepage of the graph window (%i) and that of the\n" \
	    "console (%i) differ. Use `set encoding` or `!chcp` if extended\n" \
	    "characters don't display correctly.\n",
	    GetACP(), GetConsoleCP());
    }
#endif
#endif

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    if (status[1] = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(status[1]);
    if (status[1] = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(status[1]);
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	/* should move this stuff to another initialisation routine,
	 * something like init_set() maybe */
	get_user_env();
	init_loadpath();
	init_locale();

	memset(&sm_palette, 0, sizeof(sm_palette));
	init_fit();		/* Initialization of fitting module */
	init_session();

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    read_history(expanded_history_filename);

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     */
	    gp_atexit(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

	    fprintf(stderr, "\nTerminal type set to '%s'\n", term->name);
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (!successful_initialization) {
	    /* Only print the warning once */
	    successful_initialization = TRUE;
	    fprintf(stderr,"WARNING: Error during initialization\n\n");
	}
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_READLINE_RESET
	else
	{
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

	load_file_error();	/* if we were in load_file(), cleanup */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */

	/* Why a goto?  Because we exited the loop below via int_error */
	/* using LONGJMP.  The compiler was not expecting this, and    */
	/* "optimized" the handling of argc and argv such that simply  */
	/* entering the loop again from the top finds them messed up.  */
	/* If we reenter the loop via a goto then there is some hope   */
	/* that code reordering does not hurt us.                      */
	/* NB: the test for interactive means that execution from a    */
	/* pipe will not continue after an error. Do we want this?     */
	if (reading_from_dash && interactive)
	    goto RECOVER_FROM_ERROR_IN_DASH;
	reading_from_dash = FALSE;

	if (!interactive && !noinputfiles) {
	    term_reset();
	    gp_exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    /* load filenames given as arguments */
    while (--argc > 0) {
	    ++argv;
	    c_token = 0;
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")
#ifdef _Windows
		|| !stricmp(*argv, "-noend") || !stricmp(*argv, "/noend")
#endif
	    ) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));
	    } else if (strcmp(*argv, "-") == 0) {
#if defined(_Windows) && !defined(WGP_CONSOLE)
		TextShow(&textwin);
		interactive = TRUE;
#else
		interactive = isatty(fileno(stdin));
#endif

RECOVER_FROM_ERROR_IN_DASH:
		reading_from_dash = TRUE;
		while (!com_line());
		reading_from_dash = FALSE;
		interactive = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		interactive = FALSE;
		noinputfiles = FALSE;
		do_string(*argv);

	    } else if (!strncmp(*argv, "-d", 2) || !strcmp(*argv, "--default-settings")) {
		/* Ignore this; it already had its effect */
		FPRINTF((stderr, "ignoring -d\n"));

	    } else if (strcmp(*argv, "-c") == 0) {
		/* Pass command line arguments to the gnuplot script in the next
		 * argument. This consumes the remainder of the command line
		 */
		interactive = FALSE;
		noinputfiles = FALSE;
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -c scriptname args\n");
		    gp_exit(EXIT_FAILURE);
		}
		for (i=0; i<argc; i++)
		    /* Need to stash argv[i] somewhere visible to load_file() */
		    call_args[i] = gp_strdup(argv[i+1]);
		call_argc = argc - 1;

		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), 5);
		gp_exit(EXIT_SUCCESS);

	    } else if (*argv[0] == '-') {
		fprintf(stderr, "unrecognized option %s\n", *argv);
	    } else {
		interactive = FALSE;
		noinputfiles = FALSE;
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), 4);
	    }
    }

    /* take commands from stdin */
    if (noinputfiles)
	while (!com_line())
	    ctrlc_flag = FALSE; /* reset asynchronous Ctrl-C flag */

#ifdef _Windows
    /* On Windows, handle 'persist' by keeping the main input loop running (windows/wxt), */
    /* but only if there are any windows open. Note that qt handles this properly. */
    if (persist_cl) {
	if (WinAnyWindowOpen()) {
#ifdef WGP_CONSOLE
	    if (!interactive) {
		/* no further input from pipe */
		while (WinAnyWindowOpen())
		win_sleep(100);
	    } else
#endif
	    {
		interactive = TRUE;
		while (!com_line())
		    ctrlc_flag = FALSE; /* reset asynchronous Ctrl-C flag */
		interactive = FALSE;
	    }
	}
    }
#endif

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
#if ! defined(_Windows)
    /* Windows does the cleanup later */
    gp_exit_cleanup();
#endif
    return exit_status;
}
Пример #20
0
static char *read_input_line (SLang_RLine_Info_Type *rline, char *prompt, int noecho)
{
   char *line;
#ifdef REAL_UNIX_SYSTEM
   int stdin_is_noecho = 0;
#endif

   if (Use_Readline == 0)
     {
	char buf[1024];
	char *b;

	fprintf (stdout, "%s", prompt); fflush (stdout);
	if (noecho)
	  {
#ifdef REAL_UNIX_SYSTEM
	     if (isatty (fileno(stdin)))
	       {
		  (void) SLsystem ("stty -echo");   /* yuk */
		  stdin_is_noecho = 1;
	       }
#endif
	  }

	line = buf;
	while (NULL == fgets (buf, sizeof (buf), stdin))
	  {
#ifdef EINTR
	     if (errno == EINTR)
	       {
		  if (-1 == SLang_handle_interrupt ())
		    {
		       line = NULL;
		       break;
		    }
		  continue;
	       }
#endif
	     line = NULL;
	     break;
	  }
#ifdef REAL_UNIX_SYSTEM
	if (stdin_is_noecho)
	  (void) SLsystem ("stty echo");
#endif
	if (line == NULL)
	  return NULL;

	/* Remove the final newline */
	b = line;
	while (*b && (*b != '\n'))
	  b++;
	*b = 0;

	return SLmake_string (line);
     }
#if SYSTEM_SUPPORTS_SIGNALS
   init_tty ();
#endif
#if USE_GNU_READLINE
   (void) rline;
   if (noecho == 0)
     rl_redisplay_function = rl_redisplay;
   else
     {
	/* FIXME: What is the proper way to implement this in GNU readline? */
	(void) fputs (prompt, stdout); (void) fflush (stdout);
	rl_redisplay_function = redisplay_dummy;
     }
   line = readline (prompt);
   rl_redisplay_function = rl_redisplay;
#else
   SLtt_get_screen_size ();
   SLrline_set_display_width (rline, SLtt_Screen_Cols);
   (void) add_sigwinch_handlers ();
   Active_Rline_Info = rline;
   (void) SLrline_set_echo (rline, (noecho == 0));
   line = SLrline_read_line (rline, prompt, NULL);
   Active_Rline_Info = NULL;
#endif
#if SYSTEM_SUPPORTS_SIGNALS
   reset_tty ();
#else
   fputs ("\r\n", stdout);
   fflush (stdout);
#endif
   return line;
}
Пример #21
0
void ssh_decode_tty_flags(int fd, unsigned char *buf, size_t buf_len)
{
  SshBuffer buffer;
  
#ifdef USING_TERMIOS
  struct termios tio;
#endif /* USING_TERMIOS */
#ifdef USING_SGTTY
  struct sgttyb tio;
  struct tchars tiotc;
  struct ltchars tioltc;
  int tiolm;
#ifdef TIOCGSTAT
  struct tstatus tiots;
#endif /* TIOCGSTAT */
#endif
  int opcode, baud;

  if (!isatty(fd))
    {
      SSH_TRACE(2, ("Not a tty. (fd = %d)", fd));
      return;
    }

  if (buf_len == 0)
    return;
  
  SSH_DEBUG_HEXDUMP(5, ("received tty-flags buffer"), buf, buf_len);

  ssh_buffer_init(&buffer);

  ssh_buffer_append(&buffer, buf, buf_len);
  
  /* Get old attributes for the terminal.  We will modify these flags. 
     I am hoping that if there are any machine-specific modes, they will
     initially have reasonable values. */
#ifdef USING_TERMIOS
  if (tcgetattr(fd, &tio) < 0)
    return;
#endif /* USING_TERMIOS */
#ifdef USING_SGTTY
  if (ioctl(fd, TIOCGETP, &tio) < 0)
    return;
  if (ioctl(fd, TIOCGETC, &tiotc) < 0)
    return;
  if (ioctl(fd, TIOCLGET, &tiolm) < 0)
    return;
  if (ioctl(fd, TIOCGLTC, &tioltc) < 0)
    return;
#ifdef TIOCGSTAT
  if (ioctl(fd, TIOCGSTAT, &tiots) < 0)
    return;
#endif /* TIOCGSTAT */
#endif /* USING_SGTTY */

  for (;;)
    {
      ssh_decode_buffer(&buffer,
                    SSH_FORMAT_CHAR, &opcode,
                    SSH_FORMAT_END);
      
      switch(opcode)
        {
        case TTY_OP_END:
          goto set;

        case TTY_OP_ISPEED:
          baud = GET_UINT32();
          if (cfsetispeed(&tio, baud_to_speed(baud)) < 0)
            ssh_warning("cfsetispeed failed for %d", baud);
          break;

        case TTY_OP_OSPEED:
          baud = GET_UINT32();
          if (cfsetospeed(&tio, baud_to_speed(baud)) < 0)
            ssh_warning("cfsetospeed failed for %d", baud);
          break;

#ifdef USING_TERMIOS
#define TTYCHAR(NAME, OP)                               \
        case OP:                                        \
          tio.c_cc[NAME] = GET_UINT32();                \
          break;
#define TTYMODE(NAME, FIELD, OP)                        \
        case OP:                                        \
          if (GET_UINT32())                     \
            tio.FIELD |= NAME;                          \
          else                                          \
            tio.FIELD &= ~NAME;                         \
          break;
#define SGTTYCHAR(NAME, OP)
#define SGTTYMODE(NAME, FIELD, OP)
#define SGTTYMODEN(NAME, FIELD, OP)
#endif /* USING_TERMIOS */

#ifdef USING_SGTTY
#define TTYCHAR(NAME, OP)
#define TTYMODE(NAME, FIELD, OP)
#define SGTTYCHAR(NAME, OP)                             \
        case OP:                                        \
          NAME = GET_UINT32();                  \
          break;
#define SGTTYMODE(NAME, FIELD, OP)                      \
        case OP:                                        \
          if (GET_UINT32())                     \
            FIELD |= NAME;                              \
          else                                          \
            FIELD &= ~NAME;                             \
          break;
#define SGTTYMODEN(NAME, FIELD, OP)                     \
        case OP:                                        \
          if (GET_UINT32())                     \
            FIELD &= ~NAME;                             \
          else                                          \
            FIELD |= NAME;                              \
          break;
#endif /* USING_SGTTY */

#include "sshttyflagsi.h"

#undef TTYCHAR
#undef TTYMODE
#undef SGTTYCHAR
#undef SGTTYMODE
#undef SGTTYMODEN

        default:
          SSH_TRACE(1, ("Ignoring unsupported tty mode opcode %d (0x%x)",
                        opcode, opcode));
          /* Opcodes 0 to 160 are defined to have a uint32 argument. */
          if (opcode >= 0 && opcode < 160)
            {
              (void)GET_UINT32();
              break;
            }
          /* It is a truly undefined opcode (160 to 255).  We have no idea
             about its arguments.  So we must stop parsing.  Note that some
             data may be left in the packet; hopefully there is nothing more
             coming after the mode data. */
          ssh_warning("ssh_decode_tty_flags: unknown opcode %d", opcode);
          goto set;
        }
    }

 set:
  /* Set the new modes for the terminal. */
#ifdef USING_TERMIOS
  if (tcsetattr(fd, TCSANOW, &tio) < 0)
    ssh_warning("Setting tty modes failed: %.100s", strerror(errno));
#endif /* USING_TERMIOS */
#ifdef USING_SGTTY
  /* termio's ECHOE is really both LCRTBS and LCRTERA -
     so wire them together */
  if (tiolm & LCRTERA)
    tiolm |= LCRTBS;
  if (ioctl(fd, TIOCSETP, &tio) < 0
      || ioctl(fd, TIOCSETC, &tiotc) < 0
      || ioctl(fd, TIOCLSET, &tiolm) < 0
      || ioctl(fd, TIOCSLTC, &tioltc) < 0
#ifdef TIOCSSTAT
      || ioctl(fd, TIOCSSTAT, &tiots) < 0
#endif /* TIOCSSTAT */
     ) 
    ssh_warning("Setting tty modes failed: %.100s", strerror(errno));
#endif /* USING_SGTTY */
}
Пример #22
0
int main(int argc, char *argv[])
{
    ps_program_name=argv[0];
    ps_control_open_logfile();

    if (argc == 2)
        if ( (strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "--help") == 0))
        {
            printf("%s", ps_control_options);
            return EXIT_SUCCESS;
        }

    if (argc < 3)
        ps_log(EXIT_FAILURE, LOG_ERROR("too few parameters"));

    ps_init();
    ps_set_name(argv[1]);
    ps_control_check_input(argv[2], argc-3);
    ps_log(0, LOG_INFO("creating controller"));

    if (strcmp(argv[2],"--create") == 0)
    {
        ps_control_prepare_daemon_logfile((argc == 4) ? argv[3] : "none");
        ps_control_create_daemon();
    }
    else
    {
        ps_control_connect_daemon();

        if (strcmp(argv[2],"--pid") == 0)
        {
            ps_pid=ps_control_get_daemon_pid();
            printf("%d\n",(ps_pid == -1) ? 0 : ps_pid);

            if (ps_pid == -1)
                ps_log(EXIT_FAILURE, LOG_ERROR("--pid: failed to receive daemon PID"));
        }

        if (strcmp(argv[2],"--kill") == 0)
        {
            ps_pid=ps_control_get_daemon_pid();

            if (ps_pid <= 1)
                ps_log(EXIT_FAILURE, LOG_ERROR("--kill : could not determine daemon PID"));

            if (kill(ps_pid, SIGTERM) == -1)
                ps_log(EXIT_FAILURE, LOG_ERROR("--kill : failed to kill daemon - error [%s]"), strerror(errno));
        }

        if (ps_fd_control == -1)
            return EXIT_FAILURE;

        if (strcmp(argv[2],"--net") == 0)
            ps_control_unshare_network();

        if (strcmp(argv[2],"--ipc") == 0)
            ps_control_unshare_ipc();

        if (strcmp(argv[2],"--chrootfs") == 0)
            ps_control_change_rootfs(argv[3]);

        if (strcmp(argv[2],"--cwd") == 0)
            ps_control_change_workingdir(argv[3]);

        if (strcmp(argv[2],"--run") == 0)
        {
            if (isatty(STDIN_FILENO))
            {
                ps_control_save_terminal_attributes();
                atexit(ps_control_restore_terminal_attributes);
                ps_control_set_terminal_raw_mode();
            }

            ps_control_run_program(argc-3, argv+3);
        }
    }

    ps_log(0, LOG_INFO("closing controller"));
    return EXIT_SUCCESS;
}
Пример #23
0
Файл: commit.c Проект: moy/git
static int prepare_to_commit(const char *index_file, const char *prefix,
			     struct wt_status *s,
			     struct strbuf *author_ident)
{
	struct stat statbuf;
	struct strbuf committer_ident = STRBUF_INIT;
	int commitable, saved_color_setting;
	struct strbuf sb = STRBUF_INIT;
	char *buffer;
	const char *hook_arg1 = NULL;
	const char *hook_arg2 = NULL;
	int ident_shown = 0;
	int clean_message_contents = (cleanup_mode != CLEANUP_NONE);

	if (!no_verify && run_hook(index_file, "pre-commit", NULL))
		return 0;

	if (squash_message) {
		/*
		 * Insert the proper subject line before other commit
		 * message options add their content.
		 */
		if (use_message && !strcmp(use_message, squash_message))
			strbuf_addstr(&sb, "squash! ");
		else {
			struct pretty_print_context ctx = {0};
			struct commit *c;
			c = lookup_commit_reference_by_name(squash_message);
			if (!c)
				die(_("could not lookup commit %s"), squash_message);
			ctx.output_encoding = get_commit_output_encoding();
			format_commit_message(c, "squash! %s\n\n", &sb,
					      &ctx);
		}
	}

	if (message.len) {
		strbuf_addbuf(&sb, &message);
		hook_arg1 = "message";
	} else if (logfile && !strcmp(logfile, "-")) {
		if (isatty(0))
			fprintf(stderr, _("(reading log message from standard input)\n"));
		if (strbuf_read(&sb, 0, 0) < 0)
			die_errno(_("could not read log from standard input"));
		hook_arg1 = "message";
	} else if (logfile) {
		if (strbuf_read_file(&sb, logfile, 0) < 0)
			die_errno(_("could not read log file '%s'"),
				  logfile);
		hook_arg1 = "message";
	} else if (use_message) {
		buffer = strstr(use_message_buffer, "\n\n");
		if (!buffer || buffer[2] == '\0')
			die(_("commit has empty message"));
		strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
		hook_arg1 = "commit";
		hook_arg2 = use_message;
	} else if (fixup_message) {
		struct pretty_print_context ctx = {0};
		struct commit *commit;
		commit = lookup_commit_reference_by_name(fixup_message);
		if (!commit)
			die(_("could not lookup commit %s"), fixup_message);
		ctx.output_encoding = get_commit_output_encoding();
		format_commit_message(commit, "fixup! %s\n\n",
				      &sb, &ctx);
		hook_arg1 = "message";
	} else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
		if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
			die_errno(_("could not read MERGE_MSG"));
		hook_arg1 = "merge";
	} else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
		if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
			die_errno(_("could not read SQUASH_MSG"));
		hook_arg1 = "squash";
	} else if (template_file) {
		if (strbuf_read_file(&sb, template_file, 0) < 0)
			die_errno(_("could not read '%s'"), template_file);
		hook_arg1 = "template";
		clean_message_contents = 0;
	}

	/*
	 * The remaining cases don't modify the template message, but
	 * just set the argument(s) to the prepare-commit-msg hook.
	 */
	else if (whence == FROM_MERGE)
		hook_arg1 = "merge";
	else if (whence == FROM_CHERRY_PICK) {
		hook_arg1 = "commit";
		hook_arg2 = "CHERRY_PICK_HEAD";
	}

	if (squash_message) {
		/*
		 * If squash_commit was used for the commit subject,
		 * then we're possibly hijacking other commit log options.
		 * Reset the hook args to tell the real story.
		 */
		hook_arg1 = "message";
		hook_arg2 = "";
	}

	s->fp = fopen(git_path(commit_editmsg), "w");
	if (s->fp == NULL)
		die_errno(_("could not open '%s'"), git_path(commit_editmsg));

	if (clean_message_contents)
		stripspace(&sb, 0);

	if (signoff) {
		struct strbuf sob = STRBUF_INIT;
		int i;

		strbuf_addstr(&sob, sign_off_header);
		strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
					     getenv("GIT_COMMITTER_EMAIL")));
		strbuf_addch(&sob, '\n');
		for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
			; /* do nothing */
		if (prefixcmp(sb.buf + i, sob.buf)) {
			if (!i || !ends_rfc2822_footer(&sb))
				strbuf_addch(&sb, '\n');
			strbuf_addbuf(&sb, &sob);
		}
		strbuf_release(&sob);
	}

	if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
		die_errno(_("could not write commit template"));

	strbuf_release(&sb);

	/* This checks and barfs if author is badly specified */
	determine_author_info(author_ident);

	/* This checks if committer ident is explicitly given */
	strbuf_addstr(&committer_ident, git_committer_info(0));
	if (use_editor && include_status) {
		char *ai_tmp, *ci_tmp;
		if (whence != FROM_COMMIT)
			status_printf_ln(s, GIT_COLOR_NORMAL,
				_("\n"
				"It looks like you may be committing a %s.\n"
				"If this is not correct, please remove the file\n"
				"	%s\n"
				"and try again.\n"
				""),
				whence_s(),
				git_path(whence == FROM_MERGE
					 ? "MERGE_HEAD"
					 : "CHERRY_PICK_HEAD"));

		fprintf(s->fp, "\n");
		status_printf(s, GIT_COLOR_NORMAL,
			_("Please enter the commit message for your changes."));
		if (cleanup_mode == CLEANUP_ALL)
			status_printf_more(s, GIT_COLOR_NORMAL,
				_(" Lines starting\n"
				"with '#' will be ignored, and an empty"
				" message aborts the commit.\n"));
		else /* CLEANUP_SPACE, that is. */
			status_printf_more(s, GIT_COLOR_NORMAL,
				_(" Lines starting\n"
				"with '#' will be kept; you may remove them"
				" yourself if you want to.\n"
				"An empty message aborts the commit.\n"));
		if (only_include_assumed)
			status_printf_ln(s, GIT_COLOR_NORMAL,
					"%s", only_include_assumed);

		ai_tmp = cut_ident_timestamp_part(author_ident->buf);
		ci_tmp = cut_ident_timestamp_part(committer_ident.buf);
		if (strcmp(author_ident->buf, committer_ident.buf))
			status_printf_ln(s, GIT_COLOR_NORMAL,
				_("%s"
				"Author:    %s"),
				ident_shown++ ? "" : "\n",
				author_ident->buf);

		if (!user_ident_sufficiently_given())
			status_printf_ln(s, GIT_COLOR_NORMAL,
				_("%s"
				"Committer: %s"),
				ident_shown++ ? "" : "\n",
				committer_ident.buf);

		if (ident_shown)
			status_printf_ln(s, GIT_COLOR_NORMAL, "");

		saved_color_setting = s->use_color;
		s->use_color = 0;
		commitable = run_status(s->fp, index_file, prefix, 1, s);
		s->use_color = saved_color_setting;

		*ai_tmp = ' ';
		*ci_tmp = ' ';
	} else {
		unsigned char sha1[20];
		const char *parent = "HEAD";

		if (!active_nr && read_cache() < 0)
			die(_("Cannot read index"));

		if (amend)
			parent = "HEAD^1";

		if (get_sha1(parent, sha1))
			commitable = !!active_nr;
		else
			commitable = index_differs_from(parent, 0);
	}
	strbuf_release(&committer_ident);

	fclose(s->fp);

	/*
	 * Reject an attempt to record a non-merge empty commit without
	 * explicit --allow-empty. In the cherry-pick case, it may be
	 * empty due to conflict resolution, which the user should okay.
	 */
	if (!commitable && whence != FROM_MERGE && !allow_empty &&
	    !(amend && is_a_merge(head_sha1))) {
		run_status(stdout, index_file, prefix, 0, s);
		if (amend)
			fputs(_(empty_amend_advice), stderr);
		else if (whence == FROM_CHERRY_PICK)
			fputs(_(empty_cherry_pick_advice), stderr);
		return 0;
	}

	/*
	 * Re-read the index as pre-commit hook could have updated it,
	 * and write it out as a tree.  We must do this before we invoke
	 * the editor and after we invoke run_status above.
	 */
	discard_cache();
	read_cache_from(index_file);
	if (!active_cache_tree)
		active_cache_tree = cache_tree();
	if (cache_tree_update(active_cache_tree,
			      active_cache, active_nr, 0, 0) < 0) {
		error(_("Error building trees"));
		return 0;
	}

	if (run_hook(index_file, "prepare-commit-msg",
		     git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
		return 0;

	if (use_editor) {
		char index[PATH_MAX];
		const char *env[2] = { NULL };
		env[0] =  index;
		snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
		if (launch_editor(git_path(commit_editmsg), NULL, env)) {
			fprintf(stderr,
			_("Please supply the message using either -m or -F option.\n"));
			exit(1);
		}
	}

	if (!no_verify &&
	    run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
		return 0;
	}

	return 1;
}
Пример #24
0
void
getc_immediate_common (FILE *stream,
                       int *ch,
                       int *end_of_file,
                       int *avail,
                       int waiting)
{
#if defined (linux) || defined (sun) || defined (sgi) \
    || (defined (__osf__) && ! defined (__alpha_vxworks)) \
    || defined (__CYGWIN32__) || defined (__MACHTEN__) || defined (__hpux__) \
    || defined (_AIX) || (defined (__svr4__) && defined (i386)) \
    || defined (__Lynx__) || defined (__FreeBSD__) || defined (__OpenBSD__) \
    || defined (__GLIBC__) || defined (__APPLE__)
  char c;
  int nread;
  int good_one = 0;
  int eof_ch = 4; /* Ctrl-D */
  int fd = fileno (stream);
  struct termios otermios_rec, termios_rec;

  if (isatty (fd))
    {
      tcgetattr (fd, &termios_rec);
      memcpy (&otermios_rec, &termios_rec, sizeof (struct termios));

      /* Set RAW mode, with no echo */
      termios_rec.c_lflag = termios_rec.c_lflag & ~ICANON & ~ECHO;

#if defined(linux) || defined (sun) || defined (sgi) \
    || defined (__osf__) || defined (__MACHTEN__) || defined (__hpux__) \
    || defined (_AIX) || (defined (__svr4__) && defined (i386)) \
    || defined (__Lynx__) || defined (__FreeBSD__) || defined (__OpenBSD__) \
    || defined (__GLIBC__) || defined (__APPLE__)
      eof_ch = termios_rec.c_cc[VEOF];

      /* If waiting (i.e. Get_Immediate (Char)), set MIN = 1 and wait for
         a character forever. This doesn't seem to effect Ctrl-Z or
         Ctrl-C processing.
         If not waiting (i.e. Get_Immediate (Char, Available)),
         don't wait for anything but timeout immediately. */
      termios_rec.c_cc[VMIN] = waiting;
      termios_rec.c_cc[VTIME] = 0;
#endif
      tcsetattr (fd, TCSANOW, &termios_rec);

      while (! good_one)
        {
          /* Read is used here instead of fread, because fread doesn't
             work on Solaris5 and Sunos4 in this situation.  Maybe because we
             are mixing calls that use file descriptors and streams. */
          nread = read (fd, &c, 1);
          if (nread > 0)
            {
              /* On Unix terminals, Ctrl-D (EOT) is an End of File. */
              if (c == eof_ch)
                {
                  *avail = 0;
                  *end_of_file = 1;
                  good_one = 1;
                }

              /* Everything else is ok */
              else if (c != eof_ch)
                {
                  *avail = 1;
                  *end_of_file = 0;
                  good_one = 1;
                }
            }

          else if (! waiting)
            {
              *avail = 0;
              *end_of_file = 0;
              good_one = 1;
            }
          else
	    good_one = 0;
        }

      tcsetattr (fd, TCSANOW, &otermios_rec);
      *ch = c;
    }

  else
#elif defined (VMS)
  int fd = fileno (stream);

  if (isatty (fd))
    {
      if (initted == 0)
	{
	  decc$bsd_initscr ();
	  initted = 1;
	}

      decc$bsd_cbreak ();
      *ch = decc$bsd_wgetch (decc$ga_stdscr);

      if (*ch == 4)
	*end_of_file = 1;
      else
	*end_of_file = 0;

      *avail = 1;
      decc$bsd_nocbreak ();
    }
  else
#elif defined (__MINGW32__)
  int fd = fileno (stream);
  int char_waiting;
  int eot_ch = 4; /* Ctrl-D */

  if (isatty (fd))
    {
      if (waiting)
	{
	  *ch = getch ();
	  (*winflush_function) ();

	  if (*ch == eot_ch)
	    *end_of_file = 1;
	  else
	    *end_of_file = 0;

	  *avail = 1;
	}
      else /* ! waiting */
	{
	  char_waiting = kbhit();

	  if (char_waiting == 1)
	    {
	      *avail = 1;
	      *ch = getch ();
	      (*winflush_function) ();

	      if (*ch == eot_ch)
		*end_of_file = 1;
	      else
		*end_of_file = 0;
	    }
	  else
	    {
	      *avail = 0;
	      *end_of_file = 0;
	    }
	}
    }
  else
#elif defined (__vxworks)
  /* Bit masks of file descriptors to read from.  */
  struct fd_set readFds;
  /* Timeout before select returns if nothing can be read.  */
  struct timeval timeOut;
  char c;
  int fd = fileno (stream);
  int nread;
  int option;
  int readable;
  int status;
  int width;

  if (isatty (fd))
    {
      /* If we do not want to wait, we have to set up fd in RAW mode. This
	 should be done outside this function as setting fd in RAW mode under
	 vxWorks flushes the buffer of fd. If the RAW mode was set here, the
	 buffer would be empty and we would always return that no character
	 is available */
      if (! waiting)
	{
	  /* Initialization of timeOut for its use with select.  */
	  timeOut.tv_sec  = 0;
	  timeOut.tv_usec = 0;

	  /* Initialization of readFds for its use with select;
	     FD is the only file descriptor to be monitored */
	  FD_ZERO (&readFds);
	  FD_SET (fd, &readFds);
	  width = 2;

	  /* We do all this processing to emulate a non blocking read.  */
	  readable = select (width, &readFds, NULL, NULL, &timeOut);
	  if (readable == ERROR)
	    *avail = -1, *end_of_file = -1;
	  /* No character available in input.  */
	  else if (readable == 0)
	    *avail = 0, *end_of_file = 0;
	  else
	    {
	      nread = read (fd, &c, 1);
	      if (nread > 0)
		*avail = 1, *end_of_file = 0;
	      /* End Of File. */
	      else if (nread == 0)
		*avail = 0, *end_of_file = 1;
	      /* Error.  */
	      else
		*avail = -1, *end_of_file = -1;
	    }
	}

      /* We have to wait until we get a character */
      else
	{
	  *avail = -1;
	  *end_of_file = -1;

	  /* Save the current mode of FD.  */
	  option = ioctl (fd, FIOGETOPTIONS, 0);

	  /* Set FD in RAW mode.  */
	  status = ioctl (fd, FIOSETOPTIONS, OPT_RAW);
	  if (status != -1)
	    {
	      nread = read (fd, &c, 1);
	      if (nread > 0)
		*avail = 1, *end_of_file = 0;
	      /* End of file.  */
	      else if (nread == 0)
		*avail = 0, *end_of_file = 1;
	      /* Else there is an ERROR.  */
	    }

	  /* Revert FD to its previous mode. */
	  status = ioctl (fd, FIOSETOPTIONS, option);
	}

      *ch = c;
    }
  else
#endif
    {
      /* If we're not on a terminal, then we don't need any fancy processing.
	 Also this is the only thing that's left if we're not on one of the
	 supported systems; which means that for non supported systems,
         get_immediate may wait for a carriage return on terminals. */
      *ch = fgetc (stream);
      if (feof (stream))
        {
          *end_of_file = 1;
          *avail = 0;
        }
      else
        {
          *end_of_file = 0;
          *avail = 1;
        }
    }
}
Пример #25
0
extern int main(int argc, char *argv[], char *envp[]) {
	char *dashsee[2], *dollarzero, *null[1];
	int c;
	initprint();
	dashsee[0] = dashsee[1] = NULL;
	dollarzero = argv[0];
	rc_pid = getpid();
	dashell = (*argv[0] == '-'); /* Unix tradition */
	while ((c = rc_getopt(argc, argv, "c:deiIlnopsvx")) != -1)
		switch (c) {
		case 'c':
			dashsee[0] = rc_optarg;
			goto quitopts;
		case 'd':
			dashdee = TRUE;
			break;
		case 'e':
			dashee = TRUE;
			break;
		case 'I':
			dashEYE = TRUE;
			interactive = FALSE;
			break;
		case 'i':
			dasheye = interactive = TRUE;
			break;
		case 'l':
			dashell = TRUE;
			break;
		case 'n':
			dashen = TRUE;
			break;
		case 'o':
			dashoh = TRUE;
			break;
		case 'p':
			dashpee = TRUE;
			break;
		case 's':
			dashess = TRUE;
			break;
		case 'v':
			dashvee = TRUE;
			break;
		case 'x':
			dashex = TRUE;
			break;
		case '?':
			exit(1);
		}
quitopts:
	argv += rc_optind;
	/* use isatty() iff neither -i nor -I is set, and iff the input is not from a script or -c flags */
	if (!dasheye && !dashEYE && dashsee[0] == NULL && (dashess || *argv == NULL))
		interactive = isatty(0);
	if (!dashoh) {
		checkfd(0, rFrom);
		checkfd(1, rCreate);
		checkfd(2, rCreate);
	}
	initsignal();
	inithash();
	initparse();
	assigndefault("ifs", " ", "\t", "\n", (void *)0);
#ifdef DEFAULTPATH
	assigndefault("path", DEFAULTPATH, (void *)0);
#endif
	assigndefault("pid", nprint("%d", rc_pid), (void *)0);
	assigndefault("prompt", "; ", "", (void *)0);
	assigndefault("version",
                VERSION,
                "$Release: @(#)" PACKAGE " " VERSION " " DESCRIPTION " $",
                (void *)0 );
	initenv(envp);
	initinput();
	null[0] = NULL;
	starassign(dollarzero, null, FALSE); /* assign $0 to $* */
	inithandler();

	if (dashell) {
		char *rcrc;
		int fd;

		rcrc = concat(varlookup("home"), word("/.rcrc", NULL))->w;
		fd = rc_open(rcrc, rFrom);
		if (fd == -1) {
			if (errno != ENOENT)
				uerror(rcrc);
		} else {
			bool push_interactive;

			pushfd(fd);
			push_interactive = interactive;
			interactive = FALSE;
			doit(TRUE);
			interactive = push_interactive;
			close(fd);
		}
	}
	applylocale();

	if (dashsee[0] != NULL || dashess) {	/* input from  -c or -s? */
		if (*argv != NULL)
			starassign(dollarzero, argv, FALSE);
		if (dashess)
			pushfd(0);
		else
			pushstring(dashsee, TRUE);
	} else if (*argv != NULL) {	/* else from a file? */
		b_dot(--argv);
		rc_exit(getstatus());
	} else {			/* else stdin */
		pushfd(0);
	}
	dasheye = FALSE;
	doit(TRUE);
	rc_exit(getstatus());
	return 0; /* Never really reached. */
}
Пример #26
0
/*
 * Entry point
 */
int
main(int argc, char *argv[])
{
	struct stat sb;
	struct sigaction sa;
	const char *p, *s;
	char *end, *q;
	int c, e, r;

	while ((c = getopt(argc, argv,
	    "146AaB:dFilMmN:no:qRrS:sT:Uvw:")) != -1)
		switch (c) {
		case '1':
			once_flag = 1;
			break;
		case '4':
			family = PF_INET;
			break;
		case '6':
			family = PF_INET6;
			break;
		case 'A':
			A_flag = 1;
			break;
		case 'a':
			a_flag = 1;
			break;
		case 'B':
			B_size = (off_t)strtol(optarg, &end, 10);
			if (*optarg == '\0' || *end != '\0')
				errx(1, "invalid buffer size (%s)", optarg);
			break;
		case 'd':
			d_flag = 1;
			break;
		case 'F':
			F_flag = 1;
			break;
		case 'i':
			i_flag = 1;
			break;
		case 'l':
			l_flag = 1;
			break;
		case 'o':
			o_flag = 1;
			o_filename = optarg;
			break;
		case 'M':
		case 'm':
			if (r_flag)
				errx(1, "the -m and -r flags "
				    "are mutually exclusive");
			m_flag = 1;
			break;
		case 'N':
			N_filename = optarg;
			break;
		case 'n':
			n_flag = 1;
			break;
		case 'q':
			v_level = 0;
			break;
		case 'R':
			R_flag = 1;
			break;
		case 'r':
			if (m_flag)
				errx(1, "the -m and -r flags "
				    "are mutually exclusive");
			r_flag = 1;
			break;
		case 'S':
			S_size = (off_t)strtol(optarg, &end, 10);
			if (*optarg == '\0' || *end != '\0')
				errx(1, "invalid size (%s)", optarg);
			break;
		case 's':
			s_flag = 1;
			break;
		case 'T':
			T_secs = strtol(optarg, &end, 10);
			if (*optarg == '\0' || *end != '\0')
				errx(1, "invalid timeout (%s)", optarg);
			break;
		case 'U':
			U_flag = 1;
			break;
		case 'v':
			v_level++;
			break;
		case 'w':
			a_flag = 1;
			w_secs = strtol(optarg, &end, 10);
			if (*optarg == '\0' || *end != '\0')
				errx(1, "invalid delay (%s)", optarg);
			break;
		default:
			usage();
			exit(EX_USAGE);
		}

	argc -= optind;
	argv += optind;

	if (!argc) {
		usage();
		exit(EX_USAGE);
	}

	/* allocate buffer */
	if (B_size < MINBUFSIZE)
		B_size = MINBUFSIZE;
	if ((buf = malloc(B_size)) == NULL)
		errx(1, "%s", strerror(ENOMEM));

	/* timeouts */
	if ((s = getenv("FTP_TIMEOUT")) != NULL) {
		ftp_timeout = strtol(s, &end, 10);
		if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
			warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
			ftp_timeout = 0;
		}
	}
	if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
		http_timeout = strtol(s, &end, 10);
		if (*s == '\0' || *end != '\0' || http_timeout < 0) {
			warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
			http_timeout = 0;
		}
	}

	/* signal handling */
	sa.sa_flags = 0;
	sa.sa_handler = sig_handler;
	sigemptyset(&sa.sa_mask);
	sigaction(SIGALRM, &sa, NULL);
	sa.sa_flags = SA_RESETHAND;
	sigaction(SIGINT, &sa, NULL);

	/* output file */
	if (o_flag) {
		if (strcmp(o_filename, "-") == 0) {
			o_stdout = 1;
			if (i_flag) {
				warnx("-i and -o - are incompatible, dropping -i");
				i_flag = 0;
			}
		} else if (stat(o_filename, &sb) == -1) {
			if (errno == ENOENT) {
				if (argc > 1)
					errx(EX_USAGE, "%s is not a directory",
					    o_filename);
			} else {
				err(EX_IOERR, "%s", o_filename);
			}
		} else {
			if (sb.st_mode & S_IFDIR)
				o_directory = 1;
		}
	}

	/* check if output is to a tty (for progress report) */
	v_tty = isatty(STDERR_FILENO);
	if (v_tty)
		pgrp = getpgrp();

	r = 0;

	/* authentication */
	if (v_tty)
		fetchAuthMethod = query_auth;
	if (N_filename != NULL)
		setenv("NETRC", N_filename, 1);

	while (argc) {
		if ((p = strrchr(*argv, '/')) == NULL)
			p = *argv;
		else
			p++;

		if (!*p)
			p = "fetch.out";

		fetchLastErrCode = 0;

		if (o_flag) {
			if (o_stdout) {
				e = fetch(*argv, "-");
			} else if (o_directory) {
				asprintf(&q, "%s/%s", o_filename, p);
				e = fetch(*argv, q);
				free(q);
			} else {
				e = fetch(*argv, o_filename);
			}
		} else {
			e = fetch(*argv, p);
		}

		if (sigint)
			kill(getpid(), SIGINT);

		if (e == 0 && once_flag)
			exit(0);

		if (e) {
			r = 1;
			if ((fetchLastErrCode
			    && fetchLastErrCode != FETCH_UNAVAIL
			    && fetchLastErrCode != FETCH_MOVED
			    && fetchLastErrCode != FETCH_URL
			    && fetchLastErrCode != FETCH_RESOLV
			    && fetchLastErrCode != FETCH_UNKNOWN)) {
				if (w_secs && v_level)
					fprintf(stderr, "Waiting %ld seconds "
					    "before retrying\n", w_secs);
				if (w_secs)
					sleep(w_secs);
				if (a_flag)
					continue;
			}
		}

		argc--, argv++;
	}

	exit(r);
}
Пример #27
0
static void add_instrumentation(void) {

  static u8 line[MAX_AS_LINE];

  FILE* inf;
  FILE* outf;
  s32 outfd;
  u32 ins_lines = 0;
  u8  instr_ok = 0, skip_csect = 0, skip_next_label = 0;

#ifdef __APPLE__

  u8* colon_pos;

#endif /* __APPLE__ */

  if (input_file) {

    inf = fopen(input_file, "r");
    if (!inf) PFATAL("Unable to read '%s'", input_file);

  } else inf = stdin;

  outfd = open(modified_file, O_WRONLY | O_EXCL | O_CREAT, 0600);

  if (outfd < 0) PFATAL("Unable to write to '%s'", modified_file);

  outf = fdopen(outfd, "w");

  if (!outf) PFATAL("fdopen() failed");  

  while (fgets(line, MAX_AS_LINE, inf)) {

    fputs(line, outf);

    if (pass_thru) continue;

    /* We only want to instrument the .text section. So, let's keep track
       of that in processed files. */

    if (line[0] == '\t' && line[1] == '.') {

      /* OpenBSD puts jump tables directly inline with the code, which is
         a bit annoying. They use a specific format of p2align directives
         around them, so we use that as a signal. */

      if (!clang_mode && instr_ok && !strncmp(line + 2, "p2align ", 8) &&
          isdigit(line[10]) && line[11] == '\n') skip_next_label = 1;

      if (!strncmp(line + 2, "text\n", 5) ||
          !strncmp(line + 2, "section\t.text", 13) ||
          !strncmp(line + 2, "section\t__TEXT,__text", 21) ||
          !strncmp(line + 2, "section __TEXT,__text", 21)) {
        instr_ok = 1;
        continue; 
      }

      if (!strncmp(line + 2, "section\t", 8) ||
          !strncmp(line + 2, "section ", 8) ||
          !strncmp(line + 2, "bss\n", 4) ||
          !strncmp(line + 2, "data\n", 5)) {
        instr_ok = 0;
        continue;
      }

    }

    if (strstr(line, ".code")) {

      if (strstr(line, ".code32")) skip_csect = use_64bit;
      if (strstr(line, ".code64")) skip_csect = !use_64bit;

    }

    /* If we're in the right mood for instrumenting, check for function
       names or conditional labels. This is a bit messy, but in essence,
       we want to catch:

         ^main:      - function entry point (always instrumented)
         ^.L0:       - GCC branch label
         ^.LBB0_0:   - clang branch label (but only in clang mode)
         ^\tjnz foo  - conditional branches

       ...but not:

         ^# BB#0:    - clang comments
         ^ # BB#0:   - ditto
         ^.Ltmp0:    - clang non-branch labels
         ^.LC0       - GCC non-branch labels
         ^\tjmp foo  - non-conditional jumps

       Additionally, for clang on MacOS X follows a different convention
       with no leading dots on labels, hence the weird maze of #ifdefs
       later on.

     */

    if (skip_csect || !instr_ok || line[0] == '#' || line[0] == ' ')
      continue;

    /* Conditional branch instruction (jnz, etc). */

    if (line[0] == '\t') {

      if (line[1] == 'j' && line[2] != 'm' && R(100) < inst_ratio) {

        fprintf(outf, use_64bit ? trampoline_fmt_64 : trampoline_fmt_32,
                R(MAP_SIZE));

        ins_lines++;

      }

      continue;

    }

    /* Label of some sort. */

#ifdef __APPLE__

    /* Apple: L<whatever><digit>: */

    if ((colon_pos = strstr(line, ":"))) {

      if (line[0] == 'L' && isdigit(*(colon_pos - 1))) {

#else

    /* Everybody else: .L<whatever>: */

    if (strstr(line, ":")) {

      if (line[0] == '.') {

#endif /* __APPPLE__ */

        /* .L0: or LBB0_0: style jump destination */

#ifdef __APPLE__

        /* Apple: L<num> / LBB<num> */

        if ((isdigit(line[1]) || (clang_mode && !strncmp(line, "LBB", 3)))
            && R(100) < inst_ratio) {

#else

        /* Apple: .L<num> / .LBB<num> */

        if ((isdigit(line[2]) || (clang_mode && !strncmp(line + 1, "LBB", 3)))
            && R(100) < inst_ratio) {

#endif /* __APPLE__ */

          if (!skip_next_label) {

            fprintf(outf, use_64bit ? trampoline_fmt_64 : trampoline_fmt_32,
                    R(MAP_SIZE));

            ins_lines++;

          } else skip_next_label = 0;

        }

      } else {

        /* Function label (always instrumented) */

        fprintf(outf, use_64bit ? trampoline_fmt_64 : trampoline_fmt_32,
                R(MAP_SIZE));

        ins_lines++;
    
      }

    }

  }

  if (ins_lines)
    fputs(use_64bit ? main_payload_64 : main_payload_32, outf);

  if (input_file) fclose(inf);
  fclose(outf);

  if (!be_quiet) {

    if (!ins_lines) WARNF("No instrumentation targets found.");
    else OKF("Instrumented %u locations (%s-bit, %s mode, ratio %u%%).",
             ins_lines, use_64bit ? "64" : "32",
             getenv("AFL_HARDEN") ? "hardened" : "non-hardened",
             inst_ratio);
 
  }

}


/* Main entry point */

int main(int argc, char** argv) {

  s32 pid;
  u32 rand_seed;
  int status;
  u8* inst_ratio_str = getenv("AFL_INST_RATIO");

  struct timeval tv;
  struct timezone tz;

  clang_mode = !!getenv("__AFL_CLANG_MODE");

  if (isatty(2) && !getenv("AFL_QUIET")) {

    SAYF(cCYA "afl-as " cBRI VERSION cRST " (" __DATE__ " " __TIME__ 
         ") by <*****@*****.**>\n");
 
  } else be_quiet = 1;

  if (argc < 2) {

    SAYF("\n"
         "This is a helper application for afl-fuzz. It is a wrapper around GNU 'as',\n"
         "executed by the toolchain whenever using afl-gcc or afl-clang. You probably\n"
         "don't want to run this program directly.\n\n"

         "Rarely, when dealing with extremely complex projects, it may be advisable to\n"
         "set AFL_INST_RATIO to a value less than 100 in order to reduce the odds of\n"
         "instrumenting every discovered branch.\n\n");

    exit(1);

  }

  gettimeofday(&tv, &tz);

  rand_seed = tv.tv_sec ^ tv.tv_usec ^ getpid();

  srandom(rand_seed);

  edit_params(argc, argv);

  if (inst_ratio_str) {

    if (sscanf(inst_ratio_str, "%u", &inst_ratio) != 1 || inst_ratio > 100) 
      FATAL("Bad value of AFL_INST_RATIO (must be between 0 and 100)");

  }

  if (getenv("__AFL_AS_BEENHERE"))
    FATAL("Endless loop when calling 'as' (remove '.' from your PATH)");

  setenv("__AFL_AS_BEENHERE", "1", 1);

  /* When compiling with ASAN, we don't have a particularly elegant way to skip
     ASAN-specific branches. But we can probabilistically compensate for
     that... */

  if (getenv("AFL_USE_ASAN")) inst_ratio /= 3;

  add_instrumentation();

  if (!(pid = fork())) {

    execvp(as_params[0], (char**)as_params);
    FATAL("Oops, failed to execute '%s' - check your PATH", as_params[0]);

  }

  if (pid < 0) PFATAL("fork() failed");

  if (waitpid(pid, &status, 0) <= 0) PFATAL("waitpid() failed");

  if (!getenv("AFL_KEEP_ASSEMBLY")) unlink(modified_file);

  exit(WEXITSTATUS(status));

}
Пример #28
0
struct transport *transport_get(struct remote *remote, const char *url)
{
	const char *helper;
	struct transport *ret = xcalloc(1, sizeof(*ret));

	ret->progress = isatty(2);

	if (!remote)
		die("No remote provided to transport_get()");

	ret->got_remote_refs = 0;
	ret->remote = remote;
	helper = remote->foreign_vcs;

	if (!url && remote->url)
		url = remote->url[0];
	ret->url = url;

	/* maybe it is a foreign URL? */
	if (url) {
		const char *p = url;

		while (is_urlschemechar(p == url, *p))
			p++;
		if (starts_with(p, "::"))
			helper = xstrndup(url, p - url);
	}

	if (helper) {
		transport_helper_init(ret, helper);
	} else if (starts_with(url, "rsync:")) {
		transport_check_allowed("rsync");
		ret->get_refs_list = get_refs_via_rsync;
		ret->fetch = fetch_objs_via_rsync;
		ret->push = rsync_transport_push;
		ret->smart_options = NULL;
	} else if (url_is_local_not_ssh(url) && is_file(url) && is_bundle(url, 1)) {
		struct bundle_transport_data *data = xcalloc(1, sizeof(*data));
		transport_check_allowed("file");
		ret->data = data;
		ret->get_refs_list = get_refs_from_bundle;
		ret->fetch = fetch_refs_from_bundle;
		ret->disconnect = close_bundle;
		ret->smart_options = NULL;
	} else if (!is_url(url)
		|| starts_with(url, "file://")
		|| starts_with(url, "git://")
		|| starts_with(url, "ssh://")
		|| starts_with(url, "git+ssh://")
		|| starts_with(url, "ssh+git://")) {
		/*
		 * These are builtin smart transports; "allowed" transports
		 * will be checked individually in git_connect.
		 */
		struct git_transport_data *data = xcalloc(1, sizeof(*data));
		ret->data = data;
		ret->set_option = NULL;
		ret->get_refs_list = get_refs_via_connect;
		ret->fetch = fetch_refs_via_pack;
		ret->push_refs = git_transport_push;
		ret->connect = connect_git;
		ret->disconnect = disconnect_git;
		ret->smart_options = &(data->options);

		data->conn = NULL;
		data->got_remote_heads = 0;
	} else {
		/* Unknown protocol in URL. Pass to external handler. */
		int len = external_specification_len(url);
		char *handler = xmemdupz(url, len);
		transport_helper_init(ret, handler);
	}

	if (ret->smart_options) {
		ret->smart_options->thin = 1;
		ret->smart_options->uploadpack = "git-upload-pack";
		if (remote->uploadpack)
			ret->smart_options->uploadpack = remote->uploadpack;
		ret->smart_options->receivepack = "git-receive-pack";
		if (remote->receivepack)
			ret->smart_options->receivepack = remote->receivepack;
	}

	return ret;
}
Пример #29
0
static int _parse_options(const char *key, char *value,
		const char *file, int linenum)
{
	if(value == NULL) {
		/* options without settings */
		if(strcmp(key, "UseSyslog") == 0) {
			config->usesyslog = 1;
			pm_printf(ALPM_LOG_DEBUG, "config: usesyslog\n");
		} else if(strcmp(key, "ILoveCandy") == 0) {
			config->chomp = 1;
			pm_printf(ALPM_LOG_DEBUG, "config: chomp\n");
		} else if(strcmp(key, "VerbosePkgLists") == 0) {
			config->verbosepkglists = 1;
			pm_printf(ALPM_LOG_DEBUG, "config: verbosepkglists\n");
		} else if(strcmp(key, "UseDelta") == 0) {
			config->deltaratio = 0.7;
			pm_printf(ALPM_LOG_DEBUG, "config: usedelta (default 0.7)\n");
		} else if(strcmp(key, "TotalDownload") == 0) {
			config->totaldownload = 1;
			pm_printf(ALPM_LOG_DEBUG, "config: totaldownload\n");
		} else if(strcmp(key, "CheckSpace") == 0) {
			config->checkspace = 1;
		} else if(strcmp(key, "Color") == 0) {
			if(config->color == PM_COLOR_UNSET) {
				config->color = isatty(fileno(stdout)) ? PM_COLOR_ON : PM_COLOR_OFF;
				enable_colors(config->color);
			}
		} else {
			pm_printf(ALPM_LOG_WARNING,
					_("config file %s, line %d: directive '%s' in section '%s' not recognized.\n"),
					file, linenum, key, "options");
		}
	} else {
		/* options with settings */
		if(strcmp(key, "NoUpgrade") == 0) {
			setrepeatingoption(value, "NoUpgrade", &(config->noupgrade));
		} else if(strcmp(key, "NoExtract") == 0) {
			setrepeatingoption(value, "NoExtract", &(config->noextract));
		} else if(strcmp(key, "IgnorePkg") == 0) {
			setrepeatingoption(value, "IgnorePkg", &(config->ignorepkg));
		} else if(strcmp(key, "IgnoreGroup") == 0) {
			setrepeatingoption(value, "IgnoreGroup", &(config->ignoregrp));
		} else if(strcmp(key, "HoldPkg") == 0) {
			setrepeatingoption(value, "HoldPkg", &(config->holdpkg));
		} else if(strcmp(key, "CacheDir") == 0) {
			setrepeatingoption(value, "CacheDir", &(config->cachedirs));
		} else if(strcmp(key, "Architecture") == 0) {
			if(!config->arch) {
				config_set_arch(value);
			}
		} else if(strcmp(key, "UseDelta") == 0) {
			double ratio;
			char *endptr;
			const char *oldlocale;

			/* set the locale to 'C' for consistent decimal parsing (0.7 and never
			 * 0,7) from config files, then restore old setting when we are done */
			oldlocale = setlocale(LC_NUMERIC, NULL);
			setlocale(LC_NUMERIC, "C");
			ratio = strtod(value, &endptr);
			setlocale(LC_NUMERIC, oldlocale);

			if(*endptr != '\0' || ratio < 0.0 || ratio > 2.0) {
				pm_printf(ALPM_LOG_ERROR,
						_("config file %s, line %d: invalid value for '%s' : '%s'\n"),
						file, linenum, "UseDelta", value);
				return 1;
			}
			config->deltaratio = ratio;
			pm_printf(ALPM_LOG_DEBUG, "config: usedelta = %f\n", ratio);
		} else if(strcmp(key, "DBPath") == 0) {
			/* don't overwrite a path specified on the command line */
			if(!config->dbpath) {
				config->dbpath = strdup(value);
				pm_printf(ALPM_LOG_DEBUG, "config: dbpath: %s\n", value);
			}
		} else if(strcmp(key, "RootDir") == 0) {
			/* don't overwrite a path specified on the command line */
			if(!config->rootdir) {
				config->rootdir = strdup(value);
				pm_printf(ALPM_LOG_DEBUG, "config: rootdir: %s\n", value);
			}
		} else if(strcmp(key, "GPGDir") == 0) {
			if(!config->gpgdir) {
				config->gpgdir = strdup(value);
				pm_printf(ALPM_LOG_DEBUG, "config: gpgdir: %s\n", value);
			}
		} else if(strcmp(key, "LogFile") == 0) {
			if(!config->logfile) {
				config->logfile = strdup(value);
				pm_printf(ALPM_LOG_DEBUG, "config: logfile: %s\n", value);
			}
		} else if(strcmp(key, "XferCommand") == 0) {
			config->xfercommand = strdup(value);
			pm_printf(ALPM_LOG_DEBUG, "config: xfercommand: %s\n", value);
		} else if(strcmp(key, "CleanMethod") == 0) {
			alpm_list_t *methods = NULL;
			setrepeatingoption(value, "CleanMethod", &methods);
			if(process_cleanmethods(methods, file, linenum)) {
				FREELIST(methods);
				return 1;
			}
			FREELIST(methods);
		} else if(strcmp(key, "SigLevel") == 0) {
			alpm_list_t *values = NULL;
			setrepeatingoption(value, "SigLevel", &values);
			if(process_siglevel(values, &config->siglevel,
						&config->siglevel_mask, file, linenum)) {
				FREELIST(values);
				return 1;
			}
			FREELIST(values);
		} else if(strcmp(key, "LocalFileSigLevel") == 0) {
			alpm_list_t *values = NULL;
			setrepeatingoption(value, "LocalFileSigLevel", &values);
			if(process_siglevel(values, &config->localfilesiglevel,
						&config->localfilesiglevel_mask, file, linenum)) {
				FREELIST(values);
				return 1;
			}
			FREELIST(values);
		} else if(strcmp(key, "RemoteFileSigLevel") == 0) {
			alpm_list_t *values = NULL;
			setrepeatingoption(value, "RemoteFileSigLevel", &values);
			if(process_siglevel(values, &config->remotefilesiglevel,
						&config->remotefilesiglevel_mask, file, linenum)) {
				FREELIST(values);
				return 1;
			}
			FREELIST(values);
		} else {
			pm_printf(ALPM_LOG_WARNING,
					_("config file %s, line %d: directive '%s' in section '%s' not recognized.\n"),
					file, linenum, key, "options");
		}

	}
	return 0;
}
Пример #30
0
void InputCmd ()
/*************************************************************************
 *
 *  This is the main user command interface driver.
 *
 *************************************************************************/
{
   const char *color[2] = { "White", "Black" };
   int suffix;
   int i;
   leaf *ptr; 
   int ncmds;
   char *x,*trim;

   CLEAR (flags, THINK);
   memset(userinput,0,sizeof(userinput));
   memset(cmd,0,sizeof(cmd));
#ifndef HAVE_LIBREADLINE /* Why is this necessary anyway? */
   memset(inputstr,0,sizeof(inputstr));
#endif

#ifdef HAVE_LIBREADLINE
	 if (isatty(STDIN_FILENO)) {
	    sprintf(s,"%s (%d) %c ", color[board.side], (GameCnt+1)/2 + 1, prompt);
	    inputstr = readline(s);
	    if (inputstr == NULL) return;
	    if (*inputstr) {
	       add_history(inputstr);
	    }
	    if (strlen(inputstr) > INPUT_SIZE-1) {
	       printf("Warning: Input line truncated to %d characters.\n", INPUT_SIZE -1 );
	       inputstr[INPUT_SIZE-1] = '\000';
	    }
	 } else {
	    inputstr = malloc(INPUT_SIZE);
	    if (inputstr == NULL) {
	       perror("InputCmd");
	       exit(EXIT_FAILURE);
	    }
	    fgets(inputstr, INPUT_SIZE, stdin);
	    if (inputstr[0]) {
	       inputstr[strlen(inputstr)-1] = 0;
	    }
	 }
#else /* !HAVE_LIBREADLINE */
	if (!(flags & XBOARD)) {
	  printf ("%s (%d) %c ", color[board.side], (GameCnt+1)/2 + 1, prompt);
	  fflush(stdout);
        }
	fgets (inputstr, INPUT_SIZE, stdin) ;
#endif /* HAVE_LIBREADLINE */

	cmd[0] = '\n';
	strcpy(userinput,inputstr);
	sscanf (inputstr, "%s %[^\n]", cmd, inputstr);
	if (cmd[0] == '\n')
	  goto done;
	cmd[0] = subcmd[0] = setting[0] = subsetting[0] = '\0';
        ncmds = sscanf (userinput,"%s %s %s %[^\n]",
			cmd,subcmd,setting,subsetting);

   /* Put options after command back in inputstr - messy */
   sprintf(inputstr,"%s %s %s",subcmd,setting,subsetting);

   trim = inputstr + strlen(inputstr) - 1;
   while ( trim>=inputstr && *trim==' ')
                *trim--='\0';

   if (strcmp (cmd, "quit") == 0 || strcmp (cmd, "exit") == 0)
      SET (flags, QUIT);
   else if (strcmp (cmd, "help") == 0)
      ShowHelp (inputstr);
   else if (strcmp (cmd, "show") == 0)
      ShowCmd (inputstr);
   else if (strncmp (cmd, "book", 4) == 0) {
      if (strncmp(inputstr, "add",3) == 0) {
        sscanf (inputstr, "add %s", file);
        if (access(file,F_OK) < 0) {
	  printf("The syntax to add a new book is:\n\n\tbook add file.pgn\n");
        } else {
          BookPGNReadFromFile (file);
	}
      } else if (strncmp (inputstr, "on", 2) == 0 || strncmp (inputstr, "prefer", 6) == 0) {
	bookmode = BOOKPREFER;
	printf("book now on.\n");
      } else if (strncmp (inputstr, "off", 3) == 0) {
	bookmode = BOOKOFF;
	printf("book now off.\n");
      } else if (strncmp (inputstr, "best", 4) == 0) {
	bookmode = BOOKBEST;
	printf("book now best.\n");
      } else if (strncmp (inputstr, "worst", 5) == 0) {
	bookmode = BOOKWORST;
	printf("book now worst.\n");
      } else if (strncmp (inputstr, "random", 6) == 0) {
	bookmode = BOOKRAND;
	printf("book now random.\n");
      }
   } else if (strcmp (cmd, "test") == 0)
      TestCmd (inputstr);
   else if (strcmp (cmd, "version") == 0)
      ShowVersion ();
   else if (strcmp (cmd, "pgnsave") == 0)
           {     
		if ( strlen(inputstr) > 0 && strlen(inputstr) < INPUT_SIZE )
      		  PGNSaveToFile (inputstr,"");
		else
		  printf("Invalid filename.\n");
	   }
   else if (strcmp (cmd, "pgnload") == 0)
      PGNReadFromFile (inputstr);
   else if (strcmp (cmd, "manual") == 0)
      SET (flags, MANUAL);
   else if (strcmp (cmd, "debug") == 0)
   {
      SET (flags, DEBUGG);
      Debugmvl = 0;
      if (strcmp (inputstr, "debug") == 0)
      {
         while (strcmp (inputstr, s))
         {
            sscanf (inputstr, "%s %[^\n]", s, inputstr);
            ptr = ValidateMove (s);
            Debugmv[Debugmvl++] = ptr->move;
            MakeMove (board.side, &ptr->move);
         } 
         i = Debugmvl;
         while (i)
         {
            UnmakeMove (board.side, &Debugmv[--i]);
         } 
      }
   }
   else if (strcmp (cmd, "force") == 0)
	SET (flags, MANUAL);
   else if (strcmp (cmd, "white") == 0)
	;
   else if (strcmp (cmd, "black") == 0)
	;
   else if (strcmp (cmd, "hard") == 0)
	;
   else if (strcmp (cmd, "easy") == 0)
	;
   else if (strcmp (cmd, "list") == 0) {
	if (inputstr[0] == '?')
	{
	  printf("name    - list known players alphabetically\n");
	  printf("score   - list by GNU best result first \n");
	  printf("reverse - list by GNU worst result first\n");
	} else {
          sscanf (inputstr, "%s %[^\n]", cmd, inputstr);
          if (inputstr == '\000') DBListPlayer("rscore");
	  else DBListPlayer(inputstr);
	}
   }
   else if (strcmp (cmd, "post") == 0)
	SET (flags, POST);
   else if (strcmp (cmd, "nopost") == 0)
	CLEAR (flags, POST);
   else if (strcmp (cmd, "name") == 0) {
      strcpy(name, inputstr);
      x = name;
      while (*x != '\000') {
        if (*x == ' ') {
	  *x = '\000';
	  break;
	}
        x++;
      }
      suffix = 0;
      for (;;) {
	sprintf(logfile,"log.%03d",suffix);
 	sprintf(gamefile,"game.%03d",suffix);
	if (access(logfile,F_OK) < 0) {
	  ofp = fopen(logfile,"w");
	  break;
	} else 
	  suffix++;
      }
   }
   else if (strcmp (cmd, "result") == 0) {
     if (ofp != stdout) {  
	fprintf(ofp, "result: %s\n",inputstr);
	fclose(ofp); 
	ofp = stdout;
        printf("Save to %s\n",gamefile);
        PGNSaveToFile (gamefile, inputstr);
	DBUpdatePlayer (name, inputstr);
     }
   }	
   else if (strcmp (cmd, "rating") == 0) {
      sscanf(inputstr,"%d %d",&myrating,&opprating); 
      fprintf(ofp,"my rating = %d, opponent rating = %d\n",myrating,opprating); 
      /* Change randomness of book based on opponent rating. */
      /* Basically we play narrower book the higher the opponent */
      if (opprating >= 1700) bookfirstlast = 2;
      else if (opprating >= 1700) bookfirstlast = 2;
      else bookfirstlast = 2;
   }
   else if (strcmp (cmd, "activate") == 0) {
	CLEAR (flags, TIMEOUT);
	CLEAR (flags, ENDED);
   }
   else if (strcmp (cmd, "new") == 0) {
     InitVars ();
     NewPosition ();
     CLEAR (flags, MANUAL);
     CLEAR (flags, THINK);
     myrating = opprating = 0;
   }
   else if (strcmp (cmd, "time") == 0) {
     sscanf (inputstr, "%s %[^\n]", s, inputstr);
     TimeLimit[1^board.side] = atoi(s) / 100.0f ;
   }
   else if (strcmp (cmd, "otim") == 0)
	;
   else if (strcmp (cmd, "random") == 0)
	;
   else if (strcmp (cmd, "hash") == 0)
   {
      sscanf (inputstr, "%s %[^\n]", cmd, inputstr);
      if (strcmp (cmd, "off") == 0)
         CLEAR (flags, USEHASH);
      else if (strcmp (cmd, "on") == 0)
         SET (flags, USEHASH);
      printf ("Hashing %s\n", flags & USEHASH ? "on" : "off");
   }
   else if (strcmp (cmd, "hashsize") == 0)
   {
      if (inputstr[0] == 0) {
	 printf("Current HashSize is %u slots\n", HashSize);
      } else {
	 i = atoi (inputstr);
	 TTHashMask = 0;
	 while ((i >>= 1) > 0)
	 {
	    TTHashMask <<= 1;
	    TTHashMask |= 1;
	 }
	 HashSize = TTHashMask + 1;
	 printf ("Adjusting HashSize to %u slots\n", HashSize);
	 InitHashTable (); 
      }
   }
   else if (strcmp (cmd, "null") == 0)