Exemplo n.º 1
0
void
dnsdomainname (void)
{
    char *host_name;
    struct addrinfo hints, *res;
    const char *dn;
    int rc;

    host_name = xgethostname ();
    if (!host_name)
        error (EXIT_FAILURE, errno, "cannot determine host name");

    memset (&hints, 0, sizeof (struct addrinfo));
    hints.ai_flags = AI_CANONNAME;

    rc = getaddrinfo (host_name, NULL, &hints, &res);
    if (rc != 0)
        error (EXIT_FAILURE, 0, "%s", gai_strerror (rc));

    dn = strchr (res->ai_canonname, '.');
    if (dn)
        puts (dn + 1);

    free (host_name);
    freeaddrinfo (res);
}
Exemplo n.º 2
0
void			create_server(t_server *serv)
{
    int			s;
    int			i;
    struct sockaddr_in	sin;
    int			nb_port;

    memset(serv->fd_type, FD_FREE, MAX_FD * sizeof(int));
    xgethostname(serv->hostname, MAX_HOST_NAME_LEN);
    cfg_port(serv->port);
    cfg_timeout(&(serv->timeout));
    cfg_key(&(serv->key));
    nb_port = count_nb_port(serv->port);
    printf("*** IRC Server  ***\n");
    for (i = 0; i < nb_port; i++)
    {
        s = socket(PF_INET, SOCK_STREAM, 0);
        sin.sin_family = AF_INET;
        sin.sin_port = htons(serv->port[i]);
        sin.sin_addr.s_addr = INADDR_ANY;
        bind(s, (struct sockaddr *)&sin, sizeof(sin));
        listen(s, MAX_LISTEN);
        printf("Listen on port: %d\n", serv->port[i]);
        serv->fd_type[s] = FD_SERVER;
        serv->fct_read[s] = server_socket_read;
        serv->fct_write[s] = 0;
    }
    serv->channel = 0;
}
Exemplo n.º 3
0
Arquivo: hostname.c Projeto: 8l/csolve
  CHECK_TYPE GLOBAL(PROGRAM_NAME_LOC)
{
  char *hostname;

  initialize_main (&argc, &argv);
  set_program_name (argv[0]);
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  atexit (close_stdout);

  parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version,
                      usage, AUTHORS, (char const *) NULL);
  if (getopt_long (argc, argv, "", NULL, NULL) != -1)
    usage (EXIT_FAILURE);

  if (argc == optind + 1)
    {
#ifdef HAVE_SETHOSTNAME
      /* Set hostname to operand.  */
      char const *name = argv[optind];
      if (sethostname (name, strlen (name)) != 0)
        error (EXIT_FAILURE, errno, _("cannot set name to %s"), quote (name));
#else
      error (EXIT_FAILURE, 0,
             _("cannot set hostname; this system lacks the functionality"));
#endif
    }

  if (argc <= optind)
    {
      hostname = xgethostname ();
      if (hostname == NULL)
        error (EXIT_FAILURE, errno, _("cannot determine hostname"));
      printf ("%s\n", hostname);

    }

  if (optind + 1 < argc)
    {
      error (0, 0, _("extra operand %s"), quote (argv[optind + 1]));
      usage (EXIT_FAILURE);
    }

  exit (EXIT_SUCCESS);

  return 0;
}
Exemplo n.º 4
0
int
main (int argc, char *argv[])
{
  char *hostname;

  hostname = xgethostname ();
  if (! hostname)
    {
      perror ("xgethostname");
      return 1;
    }

  printf ("%s\n", hostname);
  free (hostname);

  return 0;
}
Exemplo n.º 5
0
static const char *get_thishost(struct login_context *cxt, const char **domain)
{
	if (!cxt->thishost) {
		cxt->thishost = xgethostname();
		if (!cxt->thishost) {
			if (domain)
				*domain = NULL;
			return NULL;
		}
		cxt->thisdomain = strchr(cxt->thishost, '.');
		if (cxt->thisdomain)
			*cxt->thisdomain++ = '\0';
	}

	if (domain)
		*domain = cxt->thisdomain;
	return cxt->thishost;
}
Exemplo n.º 6
0
/**
 * shishi_keys_for_localservicerealm_in_file:
 * @handle: Shishi library handle create by shishi_init().
 * @filename: file to read keys from.
 * @service: service to get key for.
 * @realm: realm of server to get key for, or NULL for default realm.
 *
 * Get key for specified @service and @realm from @filename.
 *
 * Return value: Returns the key for the server
 * "SERVICE/HOSTNAME@REALM" (where HOSTNAME is the current system's
 * hostname), read from the default host keys file (see
 * shishi_hostkeys_default_file()), or NULL if no key could be found
 * or an error encountered.
 **/
Shishi_key *
shishi_keys_for_localservicerealm_in_file (Shishi * handle,
					   const char *filename,
					   const char *service,
					   const char *realm)
{
  char *hostname;
  char *server;
  Shishi_key *key;

  hostname = xgethostname ();

  asprintf (&server, "%s/%s", service, hostname);

  key = shishi_keys_for_serverrealm_in_file (handle, filename, server, realm);

  free (server);
  free (hostname);

  return key;
}
Exemplo n.º 7
0
/*
main() -- make the program behave like sendmail, then call ssmtp
*/
int main(int argc, char **argv)
{
	char **new_argv;

	/* Try to be bulletproof :-) */
	(void)signal(SIGHUP, SIG_IGN);
	(void)signal(SIGINT, SIG_IGN);
	(void)signal(SIGTTIN, SIG_IGN);
	(void)signal(SIGTTOU, SIG_IGN);

	/* Set the globals */
	prog = basename(argv[0]);

	hostname = xgethostname();

	if(!hostname) {
		perror("xgethostname");
		die("Cannot get the name of this machine");
	}
	new_argv = parse_options(argc, argv);

	exit(ssmtp(new_argv));
}
Exemplo n.º 8
0
Arquivo: logger.c Projeto: alisw/uuid
static inline char *logger_xgethostname(void)
{
	char *str = getenv("LOGGER_TEST_HOSTNAME");
	return str ? xstrdup(str) : xgethostname();
}
Exemplo n.º 9
0
static char *makemsg(char *fname, char **mvec, int mvecsz,
		     size_t *mbufsize, int print_banner)
{
	register int ch, cnt;
	struct stat sbuf;
	FILE *fp;
	char *p, *lbuf, *tmpname, *mbuf;
	long line_max;

	line_max = sysconf(_SC_LINE_MAX);
	lbuf = xmalloc(line_max);

	if ((fp = xfmkstemp(&tmpname, NULL)) == NULL)
		err(EXIT_FAILURE, _("can't open temporary file"));
	unlink(tmpname);
	free(tmpname);

	if (print_banner == TRUE) {
		char *hostname = xgethostname();
		char *whom, *where, *date;
		struct passwd *pw;
		time_t now;

		if (!(whom = getlogin()) || !*whom)
			whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
		if (!whom) {
			whom = "someone";
			warn(_("cannot get passwd uid"));
		}
		where = ttyname(STDOUT_FILENO);
		if (!where) {
			where = "somewhere";
			warn(_("cannot get tty name"));
		} else if (strncmp(where, "/dev/", 5) == 0)
			where += 5;

		time(&now);
		date = xstrdup(ctime(&now));
		date[strlen(date) - 1] = '\0';

		/*
		 * all this stuff is to blank out a square for the message;
		 * we wrap message lines at column 79, not 80, because some
		 * terminals wrap after 79, some do not, and we can't tell.
		 * Which means that we may leave a non-blank character
		 * in column 80, but that can't be helped.
		 */
		/* snprintf is not always available, but the sprintf's here
		   will not overflow as long as %d takes at most 100 chars */
		fprintf(fp, "\r%79s\r\n", " ");
		sprintf(lbuf, _("Broadcast message from %s@%s (%s) (%s):"),
			      whom, hostname, where, date);
		fprintf(fp, "%-79.79s\007\007\r\n", lbuf);
		free(hostname);
		free(date);
	}
	fprintf(fp, "%79s\r\n", " ");

	 if (mvec) {
		/*
		 * Read message from argv[]
		 */
		int i;

		for (i = 0; i < mvecsz; i++) {
			fputs(mvec[i], fp);
			if (i < mvecsz - 1)
				fputc(' ', fp);
		}
		fputc('\r', fp);
		fputc('\n', fp);

	} else {
		/*
		 * read message from <file>
		 */
		if (fname) {
			/*
			 * When we are not root, but suid or sgid, refuse to read files
			 * (e.g. device files) that the user may not have access to.
			 * After all, our invoker can easily do "wall < file"
			 * instead of "wall file".
			 */
			uid_t uid = getuid();
			if (uid && (uid != geteuid() || getgid() != getegid()))
				errx(EXIT_FAILURE, _("will not read %s - use stdin."),
				     fname);

			if (!freopen(fname, "r", stdin))
				err(EXIT_FAILURE, _("cannot open %s"), fname);

		}

		/*
		 * Read message from stdin.
		 */
		while (fgets(lbuf, line_max, stdin)) {
			for (cnt = 0, p = lbuf; (ch = *p) != '\0'; ++p, ++cnt) {
				if (cnt == 79 || ch == '\n') {
					for (; cnt < 79; ++cnt)
						putc(' ', fp);
					putc('\r', fp);
					putc('\n', fp);
					cnt = 0;
				}
				if (ch != '\n')
					carefulputc(ch, fp);
			}
		}
	}
	fprintf(fp, "%79s\r\n", " ");

	free(lbuf);
	rewind(fp);

	if (fstat(fileno(fp), &sbuf))
		err(EXIT_FAILURE, _("stat failed"));

	*mbufsize = (size_t) sbuf.st_size;
	mbuf = xmalloc(*mbufsize);

	if (fread(mbuf, 1, *mbufsize, fp) != *mbufsize)
		err(EXIT_FAILURE, _("fread failed"));

	if (close_stream(fp) != 0)
		errx(EXIT_FAILURE, _("write error"));
	return mbuf;
}
Exemplo n.º 10
0
static int get_pack(struct fetch_pack_args *args,
		    int xd[2], char **pack_lockfile)
{
	struct async demux;
	int do_keep = args->keep_pack;
	const char *cmd_name;
	struct pack_header header;
	int pass_header = 0;
	struct child_process cmd = CHILD_PROCESS_INIT;
	int ret;

	memset(&demux, 0, sizeof(demux));
	if (use_sideband) {
		/* xd[] is talking with upload-pack; subprocess reads from
		 * xd[0], spits out band#2 to stderr, and feeds us band#1
		 * through demux->out.
		 */
		demux.proc = sideband_demux;
		demux.data = xd;
		demux.out = -1;
		demux.isolate_sigpipe = 1;
		if (start_async(&demux))
			die(_("fetch-pack: unable to fork off sideband demultiplexer"));
	}
	else
		demux.out = xd[0];

	if (!args->keep_pack && unpack_limit) {

		if (read_pack_header(demux.out, &header))
			die(_("protocol error: bad pack header"));
		pass_header = 1;
		if (ntohl(header.hdr_entries) < unpack_limit)
			do_keep = 0;
		else
			do_keep = 1;
	}

	if (alternate_shallow_file) {
		argv_array_push(&cmd.args, "--shallow-file");
		argv_array_push(&cmd.args, alternate_shallow_file);
	}

	if (do_keep || args->from_promisor) {
		if (pack_lockfile)
			cmd.out = -1;
		cmd_name = "index-pack";
		argv_array_push(&cmd.args, cmd_name);
		argv_array_push(&cmd.args, "--stdin");
		if (!args->quiet && !args->no_progress)
			argv_array_push(&cmd.args, "-v");
		if (args->use_thin_pack)
			argv_array_push(&cmd.args, "--fix-thin");
		if (do_keep && (args->lock_pack || unpack_limit)) {
			char hostname[HOST_NAME_MAX + 1];
			if (xgethostname(hostname, sizeof(hostname)))
				xsnprintf(hostname, sizeof(hostname), "localhost");
			argv_array_pushf(&cmd.args,
					"--keep=fetch-pack %"PRIuMAX " on %s",
					(uintmax_t)getpid(), hostname);
		}
		if (args->check_self_contained_and_connected)
			argv_array_push(&cmd.args, "--check-self-contained-and-connected");
		if (args->from_promisor)
			argv_array_push(&cmd.args, "--promisor");
	}
	else {
		cmd_name = "unpack-objects";
		argv_array_push(&cmd.args, cmd_name);
		if (args->quiet || args->no_progress)
			argv_array_push(&cmd.args, "-q");
		args->check_self_contained_and_connected = 0;
	}

	if (pass_header)
		argv_array_pushf(&cmd.args, "--pack_header=%"PRIu32",%"PRIu32,
				 ntohl(header.hdr_version),
				 ntohl(header.hdr_entries));
	if (fetch_fsck_objects >= 0
	    ? fetch_fsck_objects
	    : transfer_fsck_objects >= 0
	    ? transfer_fsck_objects
	    : 0) {
		if (args->from_promisor)
			/*
			 * We cannot use --strict in index-pack because it
			 * checks both broken objects and links, but we only
			 * want to check for broken objects.
			 */
			argv_array_push(&cmd.args, "--fsck-objects");
		else
			argv_array_pushf(&cmd.args, "--strict%s",
					 fsck_msg_types.buf);
	}

	cmd.in = demux.out;
	cmd.git_cmd = 1;
	if (start_command(&cmd))
		die(_("fetch-pack: unable to fork off %s"), cmd_name);
	if (do_keep && pack_lockfile) {
		*pack_lockfile = index_pack_lockfile(cmd.out);
		close(cmd.out);
	}

	if (!use_sideband)
		/* Closed by start_command() */
		xd[0] = -1;

	ret = finish_command(&cmd);
	if (!ret || (args->check_self_contained_and_connected && ret == 1))
		args->self_contained_and_connected =
			args->check_self_contained_and_connected &&
			ret == 0;
	else
		die(_("%s failed"), cmd_name);
	if (use_sideband && finish_async(&demux))
		die(_("error in sideband demultiplexer"));
	return 0;
}
Exemplo n.º 11
0
/* return NULL on success, else hostname running the gc */
static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
{
	struct lock_file lock = LOCK_INIT;
	char my_host[HOST_NAME_MAX + 1];
	struct strbuf sb = STRBUF_INIT;
	struct stat st;
	uintmax_t pid;
	FILE *fp;
	int fd;
	char *pidfile_path;

	if (is_tempfile_active(pidfile))
		/* already locked */
		return NULL;

	if (xgethostname(my_host, sizeof(my_host)))
		xsnprintf(my_host, sizeof(my_host), "unknown");

	pidfile_path = git_pathdup("gc.pid");
	fd = hold_lock_file_for_update(&lock, pidfile_path,
				       LOCK_DIE_ON_ERROR);
	if (!force) {
		static char locking_host[HOST_NAME_MAX + 1];
		static char *scan_fmt;
		int should_exit;

		if (!scan_fmt)
			scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
		fp = fopen(pidfile_path, "r");
		memset(locking_host, 0, sizeof(locking_host));
		should_exit =
			fp != NULL &&
			!fstat(fileno(fp), &st) &&
			/*
			 * 12 hour limit is very generous as gc should
			 * never take that long. On the other hand we
			 * don't really need a strict limit here,
			 * running gc --auto one day late is not a big
			 * problem. --force can be used in manual gc
			 * after the user verifies that no gc is
			 * running.
			 */
			time(NULL) - st.st_mtime <= 12 * 3600 &&
			fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
			/* be gentle to concurrent "gc" on remote hosts */
			(strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
		if (fp != NULL)
			fclose(fp);
		if (should_exit) {
			if (fd >= 0)
				rollback_lock_file(&lock);
			*ret_pid = pid;
			free(pidfile_path);
			return locking_host;
		}
	}

	strbuf_addf(&sb, "%"PRIuMAX" %s",
		    (uintmax_t) getpid(), my_host);
	write_in_full(fd, sb.buf, sb.len);
	strbuf_release(&sb);
	commit_lock_file(&lock);
	pidfile = register_tempfile(pidfile_path);
	free(pidfile_path);
	return NULL;
}
Exemplo n.º 12
0
static void syslog_rfc5424(const  struct logger_ctl *ctl, const char *msg)
{
	char *buf, *tag = NULL, *hostname = NULL;
	char pid[32], time[64], timeq[80];
	struct ntptimeval ntptv;
	struct timeval tv;
	struct tm *tm;
	int len;

	*pid = *time = *timeq = '\0';
	if (ctl->fd < 0)
		return;

	if (ctl->rfc5424_time) {
		gettimeofday(&tv, NULL);
		if ((tm = localtime(&tv.tv_sec)) != NULL) {
			char fmt[64];

			strftime(fmt, sizeof(fmt), " %Y-%m-%dT%H:%M:%S.%%06u%z",
				 tm);
			snprintf(time, sizeof(time), fmt, tv.tv_usec);
		} else
			err(EXIT_FAILURE, _("localtime() failed"));
	}

	if (ctl->rfc5424_host) {
		hostname = xgethostname();
		/* Arbitrary looking 'if (var < strlen()) checks originate from
		 * RFC 5424 - 6 Syslog Message Format definition.  */
		if (255 < strlen(hostname))
			errx(EXIT_FAILURE, _("hostname '%s' is too long"),
			     hostname);
	}

	tag = ctl->tag ? ctl->tag : xgetlogin();

	if (48 < strlen(tag))
		errx(EXIT_FAILURE, _("tag '%s' is too long"), tag);

	if (ctl->pid)
		snprintf(pid, sizeof(pid), " %d", ctl->pid);

	if (ctl->rfc5424_tq) {
		if (ntp_gettime(&ntptv) == TIME_OK)
			snprintf(timeq, sizeof(timeq),
				 " [timeQuality tzKnown=\"1\" isSynced=\"1\" syncAccuracy=\"%ld\"]",
				 ntptv.maxerror);
		else
			snprintf(timeq, sizeof(timeq),
				 " [timeQuality tzKnown=\"1\" isSynced=\"0\"]");
	}

	len = xasprintf(&buf, "<%d>1%s%s%s %s -%s%s %s", ctl->pri, time,
		  hostname ? " " : "",
		  hostname ? hostname : "",
		  tag, pid, timeq, msg);

	if (write_all(ctl->fd, buf, len) < 0)
		warn(_("write failed"));

	if (ctl->stderr_printout)
		fprintf(stderr, "%s\n", buf);

	free(hostname);
	free(buf);
}