Example #1
0
File: login.c Project: morrisxd/PMC
/* The return value will need to be freed. */
static char *
construct_cvspass_filename ()
{
    char *homedir;
    char *passfile;

    /* Environment should override file. */
    if ((passfile = getenv ("CVS_PASSFILE")) != NULL)
	return xstrdup (passfile);

    /* Construct absolute pathname to user's password file. */
    /* todo: does this work under OS/2 ? */
    homedir = get_homedir ();
    if (! homedir)
    {
	/* FIXME?  This message confuses a lot of users, at least
	   on Win95 (which doesn't set HOMEDRIVE and HOMEPATH like
	   NT does).  I suppose the answer for Win95 is to store the
	   passwords in the registry or something (??).  And .cvsrc
	   and such too?  Wonder what WinCVS does (about .cvsrc, the
	   right thing for a GUI is to just store the password in
	   memory only)...  */
	error (1, 0, "could not find out home directory");
	return (char *) NULL;
    }

    passfile = strcat_filename_onto_homedir (homedir, CVS_PASSWORD_FILE);

    /* Safety first and last, Scouts. */
    if (isfile (passfile))
	/* xchmod() is too polite. */
	chmod (passfile, 0600);

    return passfile;
}
Example #2
0
/* Check whether we have or could make a directory for history files. */
bool have_statedir(void)
{
	struct stat dirstat;
	const char *xdgdatadir;

	get_homedir();

	if (homedir != NULL) {
		statedir = concatenate(homedir, "/.nano/");

		if (stat(statedir, &dirstat) == 0 && S_ISDIR(dirstat.st_mode)) {
			poshistname = concatenate(statedir, POSITION_HISTORY);
			return TRUE;
		}
	}

	free(statedir);
	xdgdatadir = getenv("XDG_DATA_HOME");

	if (homedir == NULL && xdgdatadir == NULL)
		return FALSE;

	if (xdgdatadir != NULL)
		statedir = concatenate(xdgdatadir, "/nano/");
	else
		statedir = concatenate(homedir, "/.local/share/nano/");

	if (stat(statedir, &dirstat) == -1) {
		if (xdgdatadir == NULL) {
			char *statepath = concatenate(homedir, "/.local");
			mkdir(statepath, S_IRWXU | S_IRWXG | S_IRWXO);
			free(statepath);
			statepath = concatenate(homedir, "/.local/share");
			mkdir(statepath, S_IRWXU);
			free(statepath);
		}
		if (mkdir(statedir, S_IRWXU) == -1) {
			history_error(N_("Unable to create directory %s: %s\n"
								"It is required for saving/loading "
								"search history or cursor positions.\n"),
								statedir, strerror(errno));
			return FALSE;
		}
	} else if (!S_ISDIR(dirstat.st_mode)) {
		history_error(N_("Path %s is not a directory and needs to be.\n"
								"Nano will be unable to load or save "
								"search history or cursor positions.\n"),
								statedir);
		return FALSE;
	}

	poshistname = concatenate(statedir, POSITION_HISTORY);
	return TRUE;
}
Example #3
0
/*
 * To the "ignore list", add the hard-coded default ignored wildcards above,
 * the wildcards found in $CVSROOT/CVSROOT/cvsignore, the wildcards found in
 * ~/.cvsignore and the wildcards found in the CVSIGNORE environment
 * variable.
 */
void
ign_setup ()
{
    char *home_dir;
    char *tmp;

    ign_inhibit_server = 0;

    /* Start with default list and special case */
    tmp = xstrdup (ign_default);
    ign_add (tmp, 0);
    free (tmp);

#ifdef CLIENT_SUPPORT
    /* The client handles another way, by (after it does its own ignore file
       processing, and only if !ign_inhibit_server), letting the server
       know about the files and letting it decide whether to ignore
       them based on CVSROOOTADM_IGNORE.  */
    if (!current_parsed_root->isremote)
#endif
    {
	char *file = xmalloc (strlen (current_parsed_root->directory) + sizeof (CVSROOTADM)
			      + sizeof (CVSROOTADM_IGNORE) + 10);
	/* Then add entries found in repository, if it exists */
	(void) sprintf (file, "%s/%s/%s", current_parsed_root->directory,
			CVSROOTADM, CVSROOTADM_IGNORE);
	ign_add_file (file, 0);
	free (file);
    }

    /* Then add entries found in home dir, (if user has one) and file exists */
    home_dir = get_homedir ();
    /* If we can't find a home directory, ignore ~/.cvsignore.  This may
       make tracking down problems a bit of a pain, but on the other
       hand it might be obnoxious to complain when CVS will function
       just fine without .cvsignore (and many users won't even know what
       .cvsignore is).  */
    if (home_dir)
    {
	char *file = xmalloc (strlen (home_dir) + sizeof (CVSDOTIGNORE) + 10);
	(void) sprintf (file, "%s/%s", home_dir, CVSDOTIGNORE);
	ign_add_file (file, 0);
	free (file);
    }

    /* Then add entries found in CVSIGNORE environment variable. */
    ign_add (getenv (IGNORE_ENV), 0);

    /* Later, add ignore entries found in -I arguments */
}
Example #4
0
int singularity_action_do(int argc, char **argv) {

    singularity_priv_drop_perm();

    singularity_message(DEBUG, "Trying to change directory to where we started\n");
    char *target_pwd = envar_path("SINGULARITY_TARGET_PWD");
    if (!target_pwd || (chdir(target_pwd) < 0)) {
        if ( chdir(cwd_path) < 0 ) {
            char *homedir;

            singularity_message(DEBUG, "Failed changing directory to: %s\n", cwd_path);
            singularity_message(VERBOSE2, "Changing to home directory\n");

            singularity_message(DEBUG, "Obtaining user's homedir\n");
            homedir = get_homedir(NULL);

            if ( ( homedir != NULL ) && ( chdir(homedir) < 0 ) ) {
                singularity_message(WARNING, "Could not chdir to home directory: %s\n", homedir);
            }
        }
    }
    free(target_pwd);

    if ( action == ACTION_SHELL ) {
        singularity_message(DEBUG, "Running action: shell\n");
        action_shell_do(argc, argv);
    } else if ( action == ACTION_EXEC ) {
        singularity_message(DEBUG, "Running action: exec\n");
        action_exec_do(argc, argv);
    } else if ( action == ACTION_RUN ) {
        singularity_message(DEBUG, "Running action: run\n");
        action_run_do(argc, argv);
    } else if ( action == ACTION_TEST ) {
        singularity_message(DEBUG, "Running action: test\n");
        action_test_do(argc, argv);
    } else if ( action == ACTION_START ) {
        singularity_message(DEBUG, "Running action: start\n");
        action_start_do(argc, argv);
    } else if ( action == ACTION_STOP ) {
        singularity_message(DEBUG, "Running action: stop\n");
        action_stop_do(argc, argv);
    }
    singularity_message(ERROR, "Called singularity_action_do() without singularity_action_init()\n");
    return(-1);
}
Example #5
0
/*
 * To the "ignore list", add the hard-coded default ignored wildcards above,
 * the wildcards found in $CVSROOT/CVSROOT/cvsignore, the wildcards found in
 * ~/.cvsignore and the wildcards found in the CVSIGNORE environment
 * variable.
 */
void
ign_setup ()
{
    char *home_dir;
    char *tmp;

    ign_inhibit_server = 0;

    /* Start with default list and special case */
    tmp = xstrdup (ign_default);
    ign_add (tmp, 0);
    free (tmp);

#ifdef CLIENT_SUPPORT
    /* The client handles another way, by (after it does its own ignore file
       processing, and only if !ign_inhibit_server), letting the server
       know about the files and letting it decide whether to ignore
       them based on CVSROOOTADM_IGNORE.  */
    if (!client_active)
#endif
    {
	char *file = xmalloc (strlen (CVSroot_directory) + sizeof (CVSROOTADM)
			      + sizeof (CVSROOTADM_IGNORE) + 10);
	/* Then add entries found in repository, if it exists */
	(void) sprintf (file, "%s/%s/%s", CVSroot_directory,
			CVSROOTADM, CVSROOTADM_IGNORE);
	ign_add_file (file, 0);
	free (file);
    }

    /* Then add entries found in home dir, (if user has one) and file exists */
    home_dir = get_homedir ();
    if (home_dir)
    {
	char *file = xmalloc (strlen (home_dir) + sizeof (CVSDOTIGNORE) + 10);
	(void) sprintf (file, "%s/%s", home_dir, CVSDOTIGNORE);
	ign_add_file (file, 0);
	free (file);
    }

    /* Then add entries found in CVSIGNORE environment variable. */
    ign_add (getenv (IGNORE_ENV), 0);

    /* Later, add ignore entries found in -I arguments */
}
Example #6
0
File: fs.c Project: ikrabbe/nyx
static const char *
prepare_dir(const char *directory)
{
    /* replace ~ if necessary */
    if (*directory == '~')
    {
        static char buffer[512] = {0};

        /* clear buffer from previous runs */
        memset(buffer, 0, sizeof(buffer));

        snprintf(buffer, sizeof(buffer), "%s%s",
                get_homedir(),
                directory + 1);

        return buffer;
    }

    return directory;
}
Example #7
0
static void
ensure_session_directory (void)
{
  const char *home;
  char *dir;
  
  home = get_homedir ();

  /* be sure we have space for / and nul */
  dir = malloc (strlen (home) + strlen (DBUS_DIR) + strlen (DBUS_SESSION_BUS_DIR) + 3);
  if (dir == NULL)
    {
      fprintf (stderr, "no memory\n");
      exit (1);
    }
  
  strcpy (dir, home);
  strcat (dir, "/");
  strcat (dir, DBUS_DIR);

  if (mkdir (dir, 0700) < 0)
    {
      /* only print a warning here, writing the session file itself will fail later */
      if (errno != EEXIST)
        fprintf (stderr, "Unable to create %s\n", dir);
    }

  strcat (dir, "/");
  strcat (dir, DBUS_SESSION_BUS_DIR);

  if (mkdir (dir, 0700) < 0)
    {
      /* only print a warning here, writing the session file itself will fail later */
      if (errno != EEXIST)
        fprintf (stderr, "Unable to create %s\n", dir);
    }
  
  free (dir);
}
Example #8
0
/* check for ~./nccc/nccc.conf and create one if there is none */
int init_config()
{
	DIR             *dir;
        struct dirent   *dir_list;
        char		*confdir="";

	get_homedir();
	confdir = strdup(homedir);
	strcat(confdir, "/.nccc");
/* open config directory */
	if((dir = opendir(confdir)) == NULL)
	{
/* it does not exist, create it */
        	if(mkdir(confdir, 0700) < 0)
        	{
        		perror("Fehler beim erstellen des config-Verzeichnisses");
        		return 110;
        	}
        	if((dir = opendir(confdir)) == NULL)
        	{
        		perror("Fehler beim oeffnen des config-Verzeichnisses");
        		return 111;
        	}
        }
/* it exists, now look for the config-file */
        while((dir_list = readdir(dir)) != NULL) 
        {
        	if(strcmp(dir_list->d_name, "nccc.conf") == 0)
        	{
/* config-file found ! */
        		return 0;
        	}
        }
	if(create_config() != 0)
	{
		return 112;
	}
	return 0;
}
Example #9
0
/*
 * Creates dotdir (in homedir) if it doesn't exist
 *
 * returns 0 on success, -1 otherwise
 */
int touch_dotdir(void) {
  char *homedir;
  char *filename;

  if (!(homedir = get_homedir())) {
    fprintf(stderr, "Warning: Couldn't get home dir.\n");
    return -1;
  }

  if (asprintf(&filename, "%s/." PACKAGE, homedir) < 0) {
    fprintf(stderr,
           "Warning: Couldn't allocate memory for configuration directory.\n");
    return -1;
  }
  if (touch_dir(filename) < 0) {
    if (debug)
      fprintf(stderr, "Warning: Can't reach configuration directory.\n");
    return -1;
  }
  free(filename);

  return 0;
}
Example #10
0
/* This routine will expand the pathname to account for ~ and $
 * characters as described above.  Returns a pointer to a newly
 * malloc'd string.  If an error occurs, an error message is printed
 * via error() and NULL is returned.  FILE and LINE are the filename
 * and linenumber to include in the error message.  FILE must point
 * to something; LINE can be zero to indicate the line number is not
 * known.
 *
 * When FORMATSAFE is set, percent signs (`%') in variable contents are doubled
 * to prevent later expansion by format_cmdline.
 *
 * CVSROOT is used to expanding $CVSROOT.
 */
char *
expand_path (const char *name, const char *cvsroot, bool formatsafe,
	     const char *file, int line)
{
    size_t s, d, p;
    const char *e;

    char *mybuf = NULL;
    size_t mybuf_size = 0;
    char *buf = NULL;
    size_t buf_size = 0;

    char inquotes = '\0';

    char *result;

    /* Sorry this routine is so ugly; it is a head-on collision
       between the `traditional' unix *d++ style and the need to
       dynamically allocate.  It would be much cleaner (and probably
       faster, not that this is a bottleneck for CVS) with more use of
       strcpy & friends, but I haven't taken the effort to rewrite it
       thusly.  */

    /* First copy from NAME to MYBUF, expanding $<foo> as we go.  */
    s = d = 0;
    expand_string (&mybuf, &mybuf_size, d + 1);
    while ((mybuf[d++] = name[s]) != '\0')
    {
	if (name[s] == '\\')
	{
	    /* The next character is a literal.  Leave the \ in the string
	     * since it will be needed again when the string is split into
	     * arguments.
	     */
	    /* if we have a \ as the last character of the string, just leave
	     * it there - this is where we would set the escape flag to tell
	     * our parent we want another line if we cared.
	     */
	    if (name[++s])
	    {
		expand_string (&mybuf, &mybuf_size, d + 1);
		mybuf[d++] = name[s++];
	    }
	}
	/* skip $ variable processing for text inside single quotes */
	else if (inquotes == '\'')
	{
	    if (name[s++] == '\'')
	    {
		inquotes = '\0';
	    }
	}
	else if (name[s] == '\'')
	{
	    s++;
	    inquotes = '\'';
	}
	else if (name[s] == '"')
	{
	    s++;
	    if (inquotes) inquotes = '\0';
	    else inquotes = '"';
	}
	else if (name[s++] == '$')
	{
	    int flag = (name[s] == '{');
	    p = d;

	    expand_string (&mybuf, &mybuf_size, d + 1);
	    for (; (mybuf[d++] = name[s]); s++)
	    {
		if (flag
		    ? name[s] =='}'
		    : !isalnum (name[s]) && name[s] != '_')
		    break;
		expand_string (&mybuf, &mybuf_size, d + 1);
	    }
	    mybuf[--d] = '\0';
	    e = expand_variable (&mybuf[p+flag], cvsroot, file, line);

	    if (e)
	    {
		expand_string (&mybuf, &mybuf_size, d + 1);
		for (d = p - 1; (mybuf[d++] = *e++); )
		{
		    expand_string (&mybuf, &mybuf_size, d + 1);
		    if (mybuf[d-1] == '"')
		    {
			/* escape the double quotes if we're between a matched
			 * pair of double quotes so that this sub will be
			 * passed inside as or as part of a single argument
			 * during the argument split later.
			 */
			if (inquotes)
			{
			    mybuf[d-1] = '\\';
			    expand_string (&mybuf, &mybuf_size, d + 1);
			    mybuf[d++] = '"';
			}
		    }
		    else if (formatsafe && mybuf[d-1] == '%')
		    {
			/* escape '%' to get past printf style format strings
			 * later (in make_cmdline).
			 */
			expand_string (&mybuf, &mybuf_size, d + 1);
			mybuf[d] = '%';
			d++;
		    }
		}
		--d;
		if (flag && name[s])
		    s++;
	    }
	    else
		/* expand_variable has already printed an error message.  */
		goto error_exit;
	}
	expand_string (&mybuf, &mybuf_size, d + 1);
    }
    expand_string (&mybuf, &mybuf_size, d + 1);
    mybuf[d] = '\0';

    /* Then copy from MYBUF to BUF, expanding ~.  */
    s = d = 0;
    /* If you don't want ~username ~/ to be expanded simply remove
     * This entire if statement including the else portion
     */
    if (mybuf[s] == '~')
    {
	p = d;
	while (mybuf[++s] != '/' && mybuf[s] != '\0')
	{
	    expand_string (&buf, &buf_size, p + 1);
	    buf[p++] = name[s];
	}
	expand_string (&buf, &buf_size, p + 1);
	buf[p] = '\0';

	if (p == d)
	    e = get_homedir ();
	else
	{
#ifdef GETPWNAM_MISSING
	    if (line)
		error (0, 0,
		       "%s:%d:tilde expansion not supported on this system",
		       file, line);
	    else
		error (0, 0, "%s:tilde expansion not supported on this system",
		       file);
	    goto error_exit;
#else
	    struct passwd *ps;
	    ps = getpwnam (buf + d);
	    if (ps == NULL)
	    {
		if (line)
		    error (0, 0, "%s:%d: no such user %s",
			   file, line, buf + d);
		else
		    error (0, 0, "%s: no such user %s", file, buf + d);
		goto error_exit;
	    }
	    e = ps->pw_dir;
#endif
	}
	if (!e)
	    error (1, 0, "cannot find home directory");

	p = strlen (e);
	expand_string (&buf, &buf_size, d + p);
	memcpy (buf + d, e, p);
	d += p;
    }
    /* Kill up to here */
    p = strlen (mybuf + s) + 1;
    expand_string (&buf, &buf_size, d + p);
    memcpy (buf + d, mybuf + s, p);

    /* OK, buf contains the value we want to return.  Clean up and return
       it.  */
    free (mybuf);
    /* Save a little memory with xstrdup; buf will tend to allocate
       more than it needs to.  */
    result = xstrdup (buf);
    free (buf);
    return result;

 error_exit:
    if (mybuf) free (mybuf);
    if (buf) free (buf);
    return NULL;
}
Example #11
0
/* Convert the request uri to a filename.
 */
int uri_to_path(t_session *session) {
	size_t length;
	char *strstart, *strend;
	t_keyvalue *alias;
	int retval;

	/* Requested file in userdirectory?
	 */
	if (session->host->user_websites && (session->uri_len >= 3)) {
		if (*(session->uri + 1) == '~') {
			strstart = session->uri + 1;
			if ((strend = strchr(strstart, '/')) == NULL) {
				return 301;
			} else if ((length = strend - strstart) > 1) {
				if ((session->local_user = (char*)malloc(length + 1)) == NULL) {
					return 500;
				}

				memcpy(session->local_user, strstart, length);
				*(session->local_user + length) = '\0';

				if ((retval = get_homedir(session, session->local_user + 1)) != 200) {
					return retval;
				}
				session->host->error_handlers = NULL;
			} else {
				/* uri is '/~/...' */
				return 404;
			}
		}
	}

	/* Search for a script alias
	 */
	alias = session->host->script_alias;
	while (alias != NULL) {
		if (session->host->enable_path_info) {
			if ((retval = strncmp(session->uri, alias->key, alias->key_len)) == 0) {
				if (strlen(session->uri) > alias->key_len) {
					if (*(session->uri + alias->key_len) != '/') {
						retval = -1;
					}
				}
			}
		} else {
			retval = strcmp(session->uri, alias->key);
		}
		if (retval == 0) {
			if ((session->file_on_disk = strdup(alias->value)) == NULL) {
				return 500;
			}
			session->script_alias = alias;
			return 200;
		}
		alias = alias->next;
	}

	/* Search for an alias.
	 */
	alias = session->host->alias;
	while (alias != NULL) {
		if (strncmp(session->uri, alias->key, alias->key_len) == 0) {
			if ((*(session->uri + alias->key_len) == '/') || (*(session->uri + alias->key_len) == '\0')) {
				session->alias = alias;
				break;
			}
		}
		alias = alias->next;
	}

	/* Allocate memory
	 */
	if (alias == NULL) {
		length = session->host->website_root_len;
	} else {
		length = strlen(alias->value);
	}
	length += session->uri_len + MAX_START_FILE_LENGTH;
	if ((session->file_on_disk = (char*)malloc(length + 4)) == NULL) { /* + 3 for '.gz' (gzip encoding) */
		return 500;
	}

	/* Copy stuff
	 */
	if (alias == NULL) {
		length = session->host->website_root_len;
		memcpy(session->file_on_disk, session->host->website_root, length);
		strstart = session->uri;
		if (session->local_user != NULL) {
			strstart += strlen(session->local_user) + 1;
		}
	} else {
		length = strlen(alias->value);
		memcpy(session->file_on_disk, alias->value, length);
		strstart = session->uri + alias->key_len;

	}
	strcpy(session->file_on_disk + length, strstart);

	return 200;
}
Example #12
0
/* The main rcfile function.  It tries to open the system-wide rcfile,
 * followed by the current user's rcfile. */
void do_rcfile(void)
{
    struct stat rcinfo;
    FILE *rcstream;

    nanorc = mallocstrcpy(nanorc, SYSCONFDIR "/nanorc");

    /* Don't open directories, character files, or block files. */
    if (stat(nanorc, &rcinfo) != -1) {
	if (S_ISDIR(rcinfo.st_mode) || S_ISCHR(rcinfo.st_mode) ||
		S_ISBLK(rcinfo.st_mode))
	    rcfile_error(S_ISDIR(rcinfo.st_mode) ?
		_("\"%s\" is a directory") :
		_("\"%s\" is a device file"), nanorc);
    }

#ifdef DEBUG
    fprintf(stderr, "Parsing file \"%s\"\n", nanorc);
#endif

    /* Try to open the system-wide nanorc. */
    rcstream = fopen(nanorc, "rb");
    if (rcstream != NULL)
	parse_rcfile(rcstream
#ifdef ENABLE_COLOR
		, FALSE
#endif
		);

#ifdef DISABLE_ROOTWRAPPING
    /* We've already read SYSCONFDIR/nanorc, if it's there.  If we're
     * root, and --disable-wrapping-as-root is used, turn wrapping off
     * now. */
    if (geteuid() == NANO_ROOT_UID)
	SET(NO_WRAP);
#endif

    get_homedir();

    if (homedir == NULL)
	rcfile_error(N_("I can't find my home directory!  Wah!"));
    else {
#ifndef RCFILE_NAME
#define RCFILE_NAME ".nanorc"
#endif
	nanorc = charealloc(nanorc, strlen(homedir) + strlen(RCFILE_NAME) + 2);
	sprintf(nanorc, "%s/%s", homedir, RCFILE_NAME);

	/* Don't open directories, character files, or block files. */
	if (stat(nanorc, &rcinfo) != -1) {
	    if (S_ISDIR(rcinfo.st_mode) || S_ISCHR(rcinfo.st_mode) ||
		S_ISBLK(rcinfo.st_mode))
		rcfile_error(S_ISDIR(rcinfo.st_mode) ?
			_("\"%s\" is a directory") :
			_("\"%s\" is a device file"), nanorc);
	}

	/* Try to open the current user's nanorc. */
	rcstream = fopen(nanorc, "rb");
	if (rcstream == NULL) {
	    /* Don't complain about the file's not existing. */
	    if (errno != ENOENT)
		rcfile_error(N_("Error reading %s: %s"), nanorc,
			strerror(errno));
	} else
	    parse_rcfile(rcstream
#ifdef ENABLE_COLOR
		, FALSE
#endif
		);
    }

    free(nanorc);
    nanorc = NULL;

    if (errors && !ISSET(QUIET)) {
	errors = FALSE;
	fprintf(stderr,
		_("\nPress Enter to continue starting nano.\n"));
	while (getchar() != '\n')
	    ;
    }

#ifdef ENABLE_COLOR
    set_colorpairs();
#endif
}
Example #13
0
/* An empty LogHistory string in CVSROOT/config will turn logging off.
 */
void
history_write (int type, const char *update_dir, const char *revs,
               const char *name, const char *repository)
{
    const char *fname;
    char *workdir;
    char *username = getcaller ();
    int fd;
    char *line;
    char *slash = "", *cp;
    const char *cp2, *repos;
    int i;
    static char *tilde = "";
    static char *PrCurDir = NULL;
    time_t now;

    if (logoff)			/* History is turned off by noexec or
				 * readonlyfs.
				 */
	return;
    if (!strchr (config->logHistory, type))	
	return;

    if (nolock)
	goto out;

    repos = Short_Repository (repository);

    if (!PrCurDir)
    {
	char *pwdir;

	pwdir = get_homedir ();
	PrCurDir = CurDir;
	if (pwdir != NULL)
	{
	    /* Assumes neither CurDir nor pwdir ends in '/' */
	    i = strlen (pwdir);
	    if (!strncmp (CurDir, pwdir, i))
	    {
		PrCurDir += i;		/* Point to '/' separator */
		tilde = "~";
	    }
	    else
	    {
		/* Try harder to find a "homedir" */
		struct saved_cwd cwd;
		char *homedir;

		if (save_cwd (&cwd))
		    error (1, errno, "Failed to save current directory.");

		if (CVS_CHDIR (pwdir) < 0 || (homedir = xgetcwd ()) == NULL)
		    homedir = pwdir;

		if (restore_cwd (&cwd))
		    error (1, errno,
		           "Failed to restore current directory, `%s'.",
		           cwd.name);
		free_cwd (&cwd);

		i = strlen (homedir);
		if (!strncmp (CurDir, homedir, i))
		{
		    PrCurDir += i;	/* Point to '/' separator */
		    tilde = "~";
		}

		if (homedir != pwdir)
		    free (homedir);
	    }
	}
    }

    if (type == 'T')
    {
	repos = update_dir;
	update_dir = "";
    }
    else if (update_dir && *update_dir)
	slash = "/";
    else
	update_dir = "";

    workdir = Xasprintf ("%s%s%s%s", tilde, PrCurDir, slash, update_dir);

    /*
     * "workdir" is the directory where the file "name" is. ("^~" == $HOME)
     * "repos"	is the Repository, relative to $CVSROOT where the RCS file is.
     *
     * "$workdir/$name" is the working file name.
     * "$CVSROOT/$repos/$name,v" is the RCS file in the Repository.
     *
     * First, note that the history format was intended to save space, not
     * to be human readable.
     *
     * The working file directory ("workdir") and the Repository ("repos")
     * usually end with the same one or more directory elements.  To avoid
     * duplication (and save space), the "workdir" field ends with
     * an integer offset into the "repos" field.  This offset indicates the
     * beginning of the "tail" of "repos", after which all characters are
     * duplicates.
     *
     * In other words, if the "workdir" field has a '*' (a very stupid thing
     * to put in a filename) in it, then every thing following the last '*'
     * is a hex offset into "repos" of the first character from "repos" to
     * append to "workdir" to finish the pathname.
     *
     * It might be easier to look at an example:
     *
     *  M273b3463|dgg|~/work*9|usr/local/cvs/examples|1.2|loginfo
     *
     * Indicates that the workdir is really "~/work/cvs/examples", saving
     * 10 characters, where "~/work*d" would save 6 characters and mean that
     * the workdir is really "~/work/examples".  It will mean more on
     * directories like: usr/local/gnu/emacs/dist-19.17/lisp/term
     *
     * "workdir" is always an absolute pathname (~/xxx is an absolute path)
     * "repos" is always a relative pathname.  So we can assume that we will
     * never run into the top of "workdir" -- there will always be a '/' or
     * a '~' at the head of "workdir" that is not matched by anything in
     * "repos".  On the other hand, we *can* run off the top of "repos".
     *
     * Only "compress" if we save characters.
     */

    cp = workdir + strlen (workdir) - 1;
    cp2 = repos + strlen (repos) - 1;
    for (i = 0; cp2 >= repos && cp > workdir && *cp == *cp2--; cp--)
	i++;

    if (i > 2)
    {
	i = strlen (repos) - i;
	(void) sprintf ((cp + 1), "*%x", i);
    }

    if (!revs)
	revs = "";
    now = time (NULL);
    line = Xasprintf ("%c%08lx|%s|%s|%s|%s|%s\n", type, (long) now,
		      username, workdir, repos, revs, name);

    fname = get_history_log_name (now);

    if (!history_lock (current_parsed_root->directory))
	/* history_lock() will already have printed an error on failure.  */
	goto out;

    fd = CVS_OPEN (fname, O_WRONLY | O_APPEND | O_CREAT | OPEN_BINARY, 0666);
    if (fd < 0)
    {
	if (!really_quiet)
            error (0, errno,
		   "warning: cannot open history file `%s' for write", fname);
        goto out;
    }

    TRACE (TRACE_FUNCTION, "open (`%s', a)", fname);

    /* Lessen some race conditions on non-Posix-compliant hosts.
     *
     * FIXME:  I'm guessing the following was necessary for NFS when multiple
     * simultaneous writes to the same file are possible, since NFS does not
     * natively support append mode and it must be emulated via lseek().  Now
     * that the history file is locked for write, the following lseek() may be
     * unnecessary.
     */
    if (lseek (fd, (off_t) 0, SEEK_END) == -1)
	error (1, errno, "cannot seek to end of history file: %s", fname);

    if (write (fd, line, strlen (line)) < 0)
	error (1, errno, "cannot write to history file: %s", fname);
    free (line);
    if (close (fd) != 0)
	error (1, errno, "cannot close history file: %s", fname);
    free (workdir);
 out:
    clear_history_lock ();
}
Example #14
0
static char *
get_session_file (void)
{
  static const char prefix[] = "/" DBUS_DIR "/" DBUS_SESSION_BUS_DIR "/";
  const char *machine;
  const char *home;
  char *display;
  char *result;
  char *p;

  machine = get_machine_uuid ();
  if (machine == NULL)
    return NULL;

  display = xstrdup (getenv ("DISPLAY"));
  if (display == NULL)
    {
      verbose ("X11 integration disabled because X11 is not running\n");
      return NULL;
    }

  /* remove the screen part of the display name */
  p = strrchr (display, ':');
  if (p != NULL)
    {
      for ( ; *p; ++p)
        {
          if (*p == '.')
            {
              *p = '\0';
              break;
            }
        }
    }

  /* Note that we leave the hostname in the display most of the
   * time. The idea is that we want to be per-(machine,display,user)
   * triplet to be extra-sure we get a bus we can connect to. Ideally
   * we'd recognize when the hostname matches the machine we're on in
   * all cases; we do try to drop localhost and localhost.localdomain
   * as a special common case so that alternate spellings of DISPLAY
   * don't result in extra bus instances.
   *
   * We also kill the ":" if there's nothing in front of it. This
   * avoids an ugly double underscore in the filename.
   */
  remove_prefix (display, "localhost.localdomain:");
  remove_prefix (display, "localhost:");
  remove_prefix (display, ":");

  /* replace the : in the display with _ if the : is still there.
   * use _ instead of - since it can't be in hostnames.
   */
  for (p = display; *p; ++p)
    {
      if (*p == ':')
        *p = '_';
    }
  
  home = get_homedir ();
  
  result = malloc (strlen (home) + strlen (prefix) + strlen (machine) +
                   strlen (display) + 2);
  if (result == NULL)
    {
      /* out of memory */
      free (display);
      return NULL;
    }

  strcpy (result, home);
  strcat (result, prefix);
  strcat (result, machine);
  strcat (result, "-");
  strcat (result, display);
  free (display);

  verbose ("session file: %s\n", result);
  return result;
}
/** read the command-line options
 *
 * \return length of modified argv
 *
 * \todo possibly maintain a list of dirs to search??
 */
int
setup_options(int argc, char *argv[])
{
	char *str = NULL;
	int pos, i;

	/* first set up defaults */
	for (i = 0; i < (int) ARRAY_LENGTH(env_vars); ++i)
	{
		if ((str = getenv(env_vars[i].name)))
			*env_vars[i].dest = xstrdup(str);
		else if (strcmp(env_vars[i].name, ENVIRON_SAVEDIR) == 0
			&& (str = get_homedir()))
		{
			size_t len = strlen(str) + strlen(PACKAGE_TARNAME) + 3;

			*env_vars[i].dest = xmalloc(len);
			sprintf(*env_vars[i].dest, "%s/.%s", str, PACKAGE_TARNAME);
			free(str);
		}
		else
			*env_vars[i].dest = xstrdup(env_vars[i].def_val);
	}

	/* set up default values */
	options.want_audio = 1;
	options.want_intro = 1;
	options.want_cheats = 0;
	options.want_fullscreen = 0;
	options.want_debug = 0;
	options.feat_shorter_advanced_training = 0;
	options.feat_random_nauts =0;    //Naut Randomize, Nikakd, 10/8/10
	options.feat_compat_nauts =10;   //Naut Compatibility, Nikakd, 10/8/10
	options.feat_no_cTraining =1;    //No Capsule Training, Nikakd, 10/8/10
	options.feat_no_backup =1;       //No Backup crew required -Leon
	options.cheat_no_damage=0;       //Damaged Equipment Cheat, Nikakd, 10/8/10
	options.feat_random_eq=0;
	options.feat_eq_new_name =0;
	options.cheat_altasOnMoon=0;
	options.cheat_addMaxS=1;
	options.boosterSafety=0;

	fixpath_options();

	/* now try to read config file, if it exists */
	if (read_config_file() < 0)
		/* if not, then write default config template */
		write_default_config();

	/* first pass: command line options */
	for (pos = 1; pos < argc; ++pos)
	{
		str = argv[pos];

		if (str[0] != '-')
			continue;

		if (!str[1])
			continue;

		if (strcmp(str, "--") == 0)
		{
			shift_argv(argv + pos, argc - pos, 1);
			argc--;
			break;
		}

		/* check what option matches */
		if (strcmp(str, "-h") == 0)
			usage(0);
		else if (strcmp(str, "-i") == 0)
			options.want_intro = 0;
		else if (strcmp(str, "-n") == 0)
			options.want_cheats = 1;
		else if (strcmp(str, "-a") == 0)
			options.want_audio = 0;
		else if (strcmp(str, "-f") == 0)
			options.want_fullscreen = 1;
		else if (strcmp(str, "-v") == 0)
			options.want_debug++;
		else
		{
			ERROR2("unknown option %s", str);
			usage(1);
		}

		shift_argv(argv + pos, argc - pos, 1);
		argc--;
		pos--; /* for loop will advance it again */
	}

	/* second pass: variable assignments */
	for (pos = 1; pos < argc; ++pos)
	{
		/** \todo should use PATH_MAX or something similar here */
		char name[32 + 1], *value;
		int offset = 0;
		int fields = 0;

		fields = sscanf(argv[pos], "%32[A-Z_]=%n", name, &offset);

		/* it is unclear whether %n increments return value */
		if (fields < 1)
			continue;

		value = argv[pos] + offset;

		for (i = 0; i < (int) ARRAY_LENGTH(env_vars); ++i)
		{
			if (strcmp(name, env_vars[i].name) == 0)
			{
				free(*env_vars[i].dest);
				*env_vars[i].dest = xstrdup(value);
				break;
			}
		}

		if (i == (int) ARRAY_LENGTH(env_vars))
			WARNING2("unsupported command line variable `%s'", name);

		/* remove matched string from argv */
		shift_argv(argv + pos, argc - pos, 1);

		/*
		 * now we have one fewer arg, pos points to the next arg,
		 * keep it this way after incrementing it on top of the loop
		 */
		pos--;
		argc--;
	}

	fixpath_options();

	return argc;
}
Example #16
0
int main(int argc, char * const *argv){
  //VirusTotal-Structs
  struct VtResponse *response;
  struct VtDomain *domain_report;
  struct VtIpAddr *ip_report;
  struct VtUrl *url_report;
  struct VtFile *file_scan;
  struct VtComments *comments;

  char* apikey = (char*)calloc(APIKEY_SIZE, APIKEY_SIZE*sizeof(char)); // TODO must be free'd
  int c; 
  char* fname = NULL;
  fname = get_homedir(); 
  if(!getapikey(apikey, fname)) return 1;

  // Print Usage if no parameter is given
  if(argc < 2){
    print_usage(argv[0]);
    free_variables(apikey);
    return 0;
  } 

  //signals for c-vtapi dunno why
  signal(SIGHUP, sighand_callback);
  signal(SIGTERM, sighand_callback);

  while(1){
    int option_index = 0;
    static struct option long_options[] = {
      {"scandomain",  required_argument, 0, 'd'},
      {"scanip",      required_argument, 0, 'i'},
      {"scanfile",    required_argument, 0, 'f'},
      {"scanurl",     required_argument, 0, 'u'},
      {"commentsget", required_argument, 0, 'g'},
      {"commentsput", required_argument, 0, 'p'},
      {"search",      required_argument, 0, 's'},
      {0,             0,                 0,  0 }
    }; // static struct option

    c = getopt_long_only(argc, argv, "", long_options, &option_index);

    if(c == -1){
      break;
    } 

    switch(c){
      case 'd':
        // scandomain wrapper
        break; 
      case 'i':
        // scanip  wrapper
        break; 
      case 'f':
        // scanfile wrapper
        break; 
      case 'u':
        // scanurl wrapper
        break; 
      case 'g':
        // commentsget wrapper
        break; 
      case 'p':
        // commentsput wrapper
        break; 
      case 's':
        // search function
        break; 
      default:
        printf("?? getopt returned character code 0%o ??\n", c);
    } 
  } 

  if (optind < argc) {
    printf("non-option ARGV-elements: ");
    while (optind < argc){
      printf("%s ", argv[optind++]);
    } 
    printf("\n");
  } 
  free_variables(apikey);
  return 0;
} 
Example #17
0
/*
 * To the "ignore list", add the hard-coded default ignored wildcards above,
 * the wildcards found in $CVSROOT/CVSROOT/cvsignore, the wildcards found in
 * ~/.cvsignore and the wildcards found in the CVSIGNORE environment
 * variable.
 */
void
ign_setup ()
{
    char *home_dir;
    char *tmp, *ptr, *server_line;
	int len;

    ign_inhibit_server = 0;

    /* Start with default list and special case */
    tmp = xstrdup (ign_default);
    ign_add (tmp, 0);
    xfree (tmp);

    /* The client handles another way, by (after it does its own ignore file
       processing, and only if !ign_inhibit_server), letting the server
       know about the files and letting it decide whether to ignore
       them based on CVSROOOTADM_IGNORE.  */
    if (current_parsed_root && !current_parsed_root->isremote)
    {
	char *file = (char*)xmalloc (strlen (current_parsed_root->directory) + sizeof (CVSROOTADM)
			      + sizeof (CVSROOTADM_IGNORE) + 10);
	/* Then add entries found in repository, if it exists */
	sprintf (file, "%s/%s/%s", current_parsed_root->directory,
			CVSROOTADM, CVSROOTADM_IGNORE);
	ign_add_file (file, 0);
	xfree (file);
    }
	else if(supported_request("read-cvsignore"))
	{
		TRACE(1,"Requesting server cvsignore");
		send_to_server ("read-cvsignore\n", 0);
		read_line(&server_line);
		if(server_line[0]=='E' && server_line[1]==' ')
		{
			fprintf (stderr, "%s\n", server_line + 2);
			error_exit();
		}
		len = atoi(server_line);
		tmp = (char*)xmalloc(len+1);
		ptr = tmp;
		while (len > 0)
		{
			size_t n;

			n = try_read_from_server (ptr, len);
			len -= n;
			ptr += n;
		}
		*ptr = '\0';
		ptr=strtok(tmp,"\n");
		while(ptr && *ptr)
		{
			ign_add(ptr,0);
			ptr=strtok(NULL,"\n");
		}
		xfree(tmp);
		xfree(server_line);
		ign_inhibit_server = 1; /* We have all the server-side ignore stuff... ignore any more */
	}

    /* Then add entries found in home dir, (if user has one) and file exists */
    home_dir = get_homedir ();
    /* If we can't find a home directory, ignore ~/.cvsignore.  This may
       make tracking down problems a bit of a pain, but on the other
       hand it might be obnoxious to complain when CVS will function
       just fine without .cvsignore (and many users won't even know what
       .cvsignore is).  */
    if (home_dir)
    {
	char *file = (char*)xmalloc (strlen (home_dir) + sizeof (CVSDOTIGNORE) + 10);
	sprintf (file, "%s/%s", home_dir, CVSDOTIGNORE);
	ign_add_file (file, 0);
	xfree (file);
    }

    /* Then add entries found in CVSIGNORE environment variable. */
    ign_add (CProtocolLibrary::GetEnvironment (IGNORE_ENV), 0);

    /* Later, add ignore entries found in -I arguments */
}