Exemplo n.º 1
0
/*
** Show the difference between two files, one in memory and one on disk.
**
** The difference is the set of edits needed to transform pFile1 into
** zFile2.  The content of pFile1 is in memory.  zFile2 exists on disk.
**
** Use the internal diff logic if zDiffCmd is NULL.  Otherwise call the
** command zDiffCmd to do the diffing.
*/
static void diff_file(
  Blob *pFile1,             /* In memory content to compare from */
  const char *zFile2,       /* On disk content to compare to */
  const char *zName,        /* Display name of the file */
  const char *zDiffCmd,     /* Command for comparison */
  int ignoreEolWs           /* Ignore whitespace at end of lines */
){
  if( zDiffCmd==0 ){
    Blob out;      /* Diff output text */
    Blob file2;    /* Content of zFile2 */

    /* Read content of zFile2 into memory */
    blob_zero(&file2);
    blob_read_from_file(&file2, zFile2);

    /* Compute and output the differences */
    blob_zero(&out);
    //text_diff(pFile1, &file2, &out, 5, ignoreEolWs);
    csvs_diff(pFile1, &file2, &out);
    printf("--- %s\n+++ %s\n", zName, zName);
    printf("%s\n", blob_str(&out));

    /* Release memory resources */
    blob_reset(&file2);
    blob_reset(&out);
  }else{
    int cnt = 0;
    Blob nameFile1;    /* Name of temporary file to old pFile1 content */
    Blob cmd;          /* Text of command to run */

    /* Construct a temporary file to hold pFile1 based on the name of
    ** zFile2 */
    blob_zero(&nameFile1);
    do{
      blob_reset(&nameFile1);
      blob_appendf(&nameFile1, "%s~%d", zFile2, cnt++);
    }while( access(blob_str(&nameFile1),0)==0 );
    blob_write_to_file(pFile1, blob_str(&nameFile1));

    /* Construct the external diff command */
    blob_zero(&cmd);
    blob_appendf(&cmd, "%s ", zDiffCmd);
    shell_escape(&cmd, blob_str(&nameFile1));
    blob_append(&cmd, " ", 1);
    shell_escape(&cmd, zFile2);

    /* Run the external diff command */
    portable_system(blob_str(&cmd));

    /* Delete the temporary file and clean up memory used */
    unlink(blob_str(&nameFile1));
    blob_reset(&nameFile1);
    blob_reset(&cmd);
  }
}
Exemplo n.º 2
0
void run_command2(const char* cmd, const char* p1, const char* p2)
{
    char* e_p1 = shell_escape(p1);
    char* e_p2 = shell_escape(p2);
    char* e_cmd = g_strdup_printf("%s %s %s\n", cmd, e_p1, e_p2);
    g_free(e_p1);
    g_free(e_p2);

    g_spawn_command_line_async(e_cmd, NULL);
    g_free(e_cmd);
}
Exemplo n.º 3
0
/*
** SSH initialization of the transport layer
*/
int transport_ssh_open(UrlData *pUrlData){
  /* For SSH we need to create and run SSH fossil http 
  ** to talk to the remote machine.
  */
  const char *zSsh;  /* The base SSH command */
  Blob zCmd;         /* The SSH command */
  char *zHost;       /* The host name to contact */
  int n;             /* Size of prefix string */

  socket_ssh_resolve_addr(pUrlData);
  zSsh = db_get("ssh-command", zDefaultSshCmd);
  blob_init(&zCmd, zSsh, -1);
  if( pUrlData->port!=pUrlData->dfltPort && pUrlData->port ){
#ifdef __MINGW32__
    blob_appendf(&zCmd, " -P %d", pUrlData->port);
#else
    blob_appendf(&zCmd, " -p %d", pUrlData->port);
#endif
  }
  if( g.fSshTrace ){
    fossil_force_newline();
    fossil_print("%s", blob_str(&zCmd));  /* Show the base of the SSH command */
  }
  if( pUrlData->user && pUrlData->user[0] ){
    zHost = mprintf("%s@%s", pUrlData->user, pUrlData->name);
  }else{
    zHost = mprintf("%s", pUrlData->name);
  }
  n = blob_size(&zCmd);
  blob_append(&zCmd, " ", 1);
  shell_escape(&zCmd, zHost);
  blob_append(&zCmd, " ", 1);
  shell_escape(&zCmd, mprintf("%s", pUrlData->fossil));
  blob_append(&zCmd, " test-http", 10);
  if( pUrlData->path && pUrlData->path[0] ){
    blob_append(&zCmd, " ", 1);
    shell_escape(&zCmd, mprintf("%s", pUrlData->path));
  }
  if( g.fSshTrace ){
    fossil_print("%s\n", blob_str(&zCmd)+n);  /* Show tail of SSH command */
  }
  free(zHost);
  popen2(blob_str(&zCmd), &sshIn, &sshOut, &sshPid);
  if( sshPid==0 ){
    socket_set_errmsg("cannot start ssh tunnel using [%b]", &zCmd);
  }
  blob_reset(&zCmd);
  return sshPid==0;
}
Exemplo n.º 4
0
char *move_bin(const char *ipath, const char *file, bool run)
{
  char *path = strdup(ipath);

  expand_tilde(&path);

  /* move the binary to the correct place */
  static char newbin[DIRMAX] = "";
  char real[DIRMAX] = "";

  simple_snprintf(newbin, sizeof newbin, "%s%s%s", path, path[strlen(path) - 1] == '/' ? "" : "/", file);

  ContextNote(STR("realpath()"));
  realpath(binname, real);            /* get the realpath of binname */
  ContextNote(STR("realpath(): Success"));
  /* running from wrong dir, or wrong bin name.. lets try to fix that :) */
  sdprintf(STR("binname: %s"), binname);
  sdprintf(STR("newbin: %s"), newbin);
  sdprintf(STR("real: %s"), real);
  if (strcmp(binname, newbin) && strcmp(newbin, real)) {              /* if wrong path and new path != current */
    bool ok = 1;

    sdprintf(STR("wrong dir, is: %s :: %s"), binname, newbin);

    unlink(newbin);
    if (copyfile(binname, newbin))
      ok = 0;

    if (ok && !can_stat(newbin)) {
       unlink(newbin);
       ok = 0;
    }

    if (ok && fixmod(newbin)) {
        unlink(newbin);
        ok = 0;
    }

    if (ok) {
      sdprintf(STR("Binary successfully moved to: %s"), newbin);
      unlink(binname);
      if (run) {
        simple_snprintf(newbin, sizeof newbin, "%s%s%s", 
                        path, path[strlen(path) - 1] == '/' ? "" : "/", shell_escape(file));
        system(newbin);
        sdprintf(STR("exiting to let new binary run..."));
        exit(0);
      }
    } else {
      if (run)
        werr(ERR_WRONGBINDIR);
      sdprintf(STR("Binary move failed to: %s"), newbin);
      return binname;
    }
  }
  return newbin;
}
Exemplo n.º 5
0
static void append_executable(sl* list, const char* fn, const char* me) {
    char* exec = find_executable(fn, me);
    if (!exec) {
        ERROR("Error, couldn't find executable \"%s\"", fn);
        exit(-1);
    }
    sl_append_nocopy(list, shell_escape(exec));
    free(exec);
}
Exemplo n.º 6
0
/*
** Show the difference between two files, both in memory.
**
** The difference is the set of edits needed to transform pFile1 into
** pFile2.
**
** Use the internal diff logic if zDiffCmd is NULL.  Otherwise call the
** command zDiffCmd to do the diffing.
*/
static void diff_file_mem(
  Blob *pFile1,             /* In memory content to compare from */
  Blob *pFile2,             /* In memory content to compare to */
  const char *zName,        /* Display name of the file */
  const char *zDiffCmd,     /* Command for comparison */
  int ignoreEolWs           /* Ignore whitespace at end of lines */
){
  if( zDiffCmd==0 ){
    Blob out;      /* Diff output text */

    blob_zero(&out);
    text_diff(pFile1, pFile2, &out, 5, ignoreEolWs);
    printf("--- %s\n+++ %s\n", zName, zName);
    printf("%s\n", blob_str(&out));

    /* Release memory resources */
    blob_reset(&out);
  }else{
    Blob cmd;
    char zTemp1[300];
    char zTemp2[300];

    /* Construct a temporary file names */
    file_tempname(sizeof(zTemp1), zTemp1);
    file_tempname(sizeof(zTemp2), zTemp2);
    blob_write_to_file(pFile1, zTemp1);
    blob_write_to_file(pFile2, zTemp2);

    /* Construct the external diff command */
    blob_zero(&cmd);
    blob_appendf(&cmd, "%s ", zDiffCmd);
    shell_escape(&cmd, zTemp1);
    blob_append(&cmd, " ", 1);
    shell_escape(&cmd, zTemp2);

    /* Run the external diff command */
    portable_system(blob_str(&cmd));

    /* Delete the temporary file and clean up memory used */
    unlink(zTemp1);
    unlink(zTemp2);
    blob_reset(&cmd);
  }
}
Exemplo n.º 7
0
/*
 * Breaks the files list into reasonable sized lines to avoid line wrap...
 * all in the name of pretty output.  It only works on nodes whose types
 * match the one we're looking for
 */
static int fmt_proc (Node *p, void *closure)
{
    struct logfile_info *li;

    li = (struct logfile_info *) p->data;
    if (li->type == type)
    {
        if (li->tag == NULL
	    ? tag != NULL
	    : tag == NULL || strcmp (tag, li->tag) != 0)
	{
	    if (col > 0)
	        fprintf (fp, "\n");
	    fprintf (fp, "%s", prefix);
	    col = strlen (prefix);
	    while (col < 6)
	    {
	        fprintf (fp, " ");
		++col;
	    }

	    if (li->tag == NULL)
	        fprintf (fp, "No tag");
	    else
	        fprintf (fp, "Tag: %s", li->tag);

	    if (tag != NULL)
	        xfree (tag);
	    tag = xstrdup (li->tag);

	    /* Force a new line.  */
	    col = 70;
	}

	if (col == 0)
	{
	    fprintf (fp, "%s\t", prefix);
	    col = 8;
	}
	else if (col > 8 && (col + (int) strlen (p->key)) > 70)
	{
	    fprintf (fp, "\n%s\t", prefix);
	    col = 8;
	}
	{
		char *tmp;
		fprintf (fp, "%s ", shell_escape(&tmp,p->key));
		col += strlen (tmp) + 1;
		xfree(tmp);
	}
    }
    return (0);
}
Exemplo n.º 8
0
/*
** Open a connection to the server.  The server is defined by the following
** global variables:
**
**   g.urlName        Name of the server.  Ex: www.fossil-scm.org
**   g.urlPort        TCP/IP port.  Ex: 80
**   g.urlIsHttps     Use TLS for the connection
**
** Return the number of errors.
*/
int transport_open(void){
  int rc = 0;
  if( transport.isOpen==0 ){
    if( g.urlIsSsh ){
      Blob cmd;
      blob_zero(&cmd);
      shell_escape(&cmd, g.urlFossil);
      blob_append(&cmd, " test-http ", -1);
      shell_escape(&cmd, g.urlPath);
      /* fprintf(stdout, "%s\n", blob_str(&cmd)); */
      fprintf(sshOut, "%s\n", blob_str(&cmd));
      fflush(sshOut);
      blob_reset(&cmd);
    }else if( g.urlIsHttps ){
      #ifdef FOSSIL_ENABLE_SSL
      rc = ssl_open();
      if( rc==0 ) transport.isOpen = 1;
      #else
      socket_set_errmsg("HTTPS: Fossil has been compiled without SSL support");
      rc = 1;
      #endif
    }else if( g.urlIsFile ){
      sqlite3_uint64 iRandId;
      sqlite3_randomness(sizeof(iRandId), &iRandId);
      transport.zOutFile = mprintf("%s-%llu-out.http", 
                                       g.zRepositoryName, iRandId);
      transport.zInFile = mprintf("%s-%llu-in.http", 
                                       g.zRepositoryName, iRandId);
      transport.pFile = fopen(transport.zOutFile, "wb");
      if( transport.pFile==0 ){
        fossil_fatal("cannot output temporary file: %s", transport.zOutFile);
      }
      transport.isOpen = 1;
    }else{
      rc = socket_open();
      if( rc==0 ) transport.isOpen = 1;
    }
  }
  return rc;
}
Exemplo n.º 9
0
void crontab_del() {
  char *tmpFile = NULL, *p = NULL, buf[2048] = "";

  size_t tmplen = strlen(binname) + 100;
  tmpFile = (char *) my_calloc(1, tmplen);

  strlcpy(tmpFile, shell_escape(binname), tmplen);
  if (!(p = strrchr(tmpFile, '/')))
    return;
  p++;
  strcpy(p, STR(".ctb"));
  simple_snprintf(buf, sizeof(buf), STR("crontab -l | grep -v '%s' | grep -v \"^#\" | grep -v \"^\\$\" > %s"), binname, tmpFile);
  if (shell_exec(buf, NULL, NULL, NULL)) {
    simple_snprintf(buf, sizeof(buf), STR("crontab %s"), tmpFile);
    shell_exec(buf, NULL, NULL, NULL);
  }
  unlink(tmpFile);
}
Exemplo n.º 10
0
static int make_overlay(const char *path) {
        _cleanup_free_ char *escaped_path = NULL;
        bool tmpfs_mounted = false;
        const char *options = NULL;
        int r;

        assert(path);

        r = mkdir_p("/run/systemd/overlay-sysroot", 0700);
        if (r < 0)
                return log_error_errno(r, "Couldn't create overlay sysroot directory: %m");

        r = mount_verbose(LOG_ERR, "tmpfs", "/run/systemd/overlay-sysroot", "tmpfs", MS_STRICTATIME, "mode=755");
        if (r < 0)
                goto finish;

        tmpfs_mounted = true;

        if (mkdir("/run/systemd/overlay-sysroot/upper", 0755) < 0) {
                r = log_error_errno(errno, "Failed to create /run/systemd/overlay-sysroot/upper: %m");
                goto finish;
        }

        if (mkdir("/run/systemd/overlay-sysroot/work", 0755) < 0) {
                r = log_error_errno(errno, "Failed to create /run/systemd/overlay-sysroot/work: %m");
                goto finish;
        }

        escaped_path = shell_escape(path, ",:");
        if (!escaped_path) {
                r = log_oom();
                goto finish;
        }

        options = strjoina("lowerdir=", escaped_path, ",upperdir=/run/systemd/overlay-sysroot/upper,workdir=/run/systemd/overlay-sysroot/work");
        r = mount_verbose(LOG_ERR, "overlay", path, "overlay", 0, options);

finish:
        if (tmpfs_mounted)
                (void) umount_verbose("/run/systemd/overlay-sysroot");

        (void) rmdir("/run/systemd/overlay-sysroot");
        return r;
}
Exemplo n.º 11
0
static int test_shell_escape(void)
{
	int i;
	char out[PATH_MAX];
	const char *inputs[] = {
		"foo",
		"",
		"it's like this",
		"it's like that",
		"Hi\\There",
		NULL
	};
	const char *outputs[] = {
		"'foo'",
		"''",
		"'it'\\''s like this'",
		"'it'\\''s like that'",
		"'Hi\\\\There'",
		NULL
	};
	for (i = 0; inputs[i]; ++i) {
		memset(out, 0, sizeof(out));
		if (shell_escape(inputs[i], out, sizeof(out))) {
			fprintf(stderr, "test_shell_escape: error on test "
				"pattern %d: shell_escape error\n", i);
			return -EDOM;
		}
		if (strcmp(out, outputs[i])) {
			fprintf(stderr, "test_shell_escape: error on test "
				"pattern %d: got %s, expected %s\n",
				i, out, outputs[i]);
			return -EDOM;
		}
	}
	return 0;
}
Exemplo n.º 12
0
char *feh_printf(char *str, feh_file * file, winwidget winwid)
{
	char *c;
	char buf[20];
	static char ret[4096];
	char *filelist_tmppath;

	ret[0] = '\0';
	filelist_tmppath = NULL;

	for (c = str; *c != '\0'; c++) {
		if ((*c == '%') && (*(c+1) != '\0')) {
			c++;
			switch (*c) {
			case 'f':
				if (file)
					strncat(ret, file->filename, sizeof(ret) - strlen(ret) - 1);
				break;
			case 'F':
				if (file)
					strncat(ret, shell_escape(file->filename), sizeof(ret) - strlen(ret) - 1);
				break;
			case 'h':
				if (file && (file->info || !feh_file_info_load(file, NULL))) {
					snprintf(buf, sizeof(buf), "%d", file->info->height);
					strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 'l':
				snprintf(buf, sizeof(buf), "%d", gib_list_length(filelist));
				strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				break;
			case 'L':
				if (filelist_tmppath != NULL) {
					strncat(ret, filelist_tmppath, sizeof(ret) - strlen(ret) - 1);
				} else {
					filelist_tmppath = feh_unique_filename("/tmp/","filelist");
					feh_write_filelist(filelist, filelist_tmppath);
					strncat(ret, filelist_tmppath, sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 'm':
				strncat(ret, mode, sizeof(ret) - strlen(ret) - 1);
				break;
			case 'n':
				if (file)
					strncat(ret, file->name, sizeof(ret) - strlen(ret) - 1);
				break;
			case 'N':
				if (file)
					strncat(ret, shell_escape(file->name), sizeof(ret) - strlen(ret) - 1);
				break;
			case 'o':
				if (winwid) {
					snprintf(buf, sizeof(buf), "%d,%d", winwid->im_x,
						winwid->im_y);
					strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 'p':
				if (file && (file->info || !feh_file_info_load(file, NULL))) {
					snprintf(buf, sizeof(buf), "%d", file->info->pixels);
					strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 'P':
				if (file && (file->info || !feh_file_info_load(file, NULL))) {
					strncat(ret, format_size(file->info->pixels), sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 'r':
				if (winwid) {
					snprintf(buf, sizeof(buf), "%.1f", winwid->im_angle);
					strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 's':
				if (file && (file->info || !feh_file_info_load(file, NULL))) {
					snprintf(buf, sizeof(buf), "%d", file->info->size);
					strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 'S':
				if (file && (file->info || !feh_file_info_load(file, NULL))) {
					strncat(ret, format_size(file->info->size), sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 't':
				if (file && (file->info || !feh_file_info_load(file, NULL))) {
					strncat(ret, file->info->format, sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 'u':
				snprintf(buf, sizeof(buf), "%d",
					 current_file != NULL ? gib_list_num(filelist, current_file)
					 + 1 : 0);
				strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				break;
			case 'v':
				strncat(ret, VERSION, sizeof(ret) - strlen(ret) - 1);
				break;
			case 'V':
				snprintf(buf, sizeof(buf), "%d", getpid());
				strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				break;
			case 'w':
				if (file && (file->info || !feh_file_info_load(file, NULL))) {
					snprintf(buf, sizeof(buf), "%d", file->info->width);
					strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case 'z':
				if (winwid) {
					snprintf(buf, sizeof(buf), "%.2f", winwid->zoom);
					strncat(ret, buf, sizeof(ret) - strlen(ret) - 1);
				}
				break;
			case '%':
				strncat(ret, "%", sizeof(ret) - strlen(ret) - 1);
				break;
			default:
				weprintf("Unrecognized format specifier %%%c", *c);
				if ((strlen(ret) + 3) < sizeof(ret))
					strncat(ret, c - 1, 2);
				break;
			}
		} else if ((*c == '\\') && (*(c+1) != '\0') && ((strlen(ret) + 3) < sizeof(ret))) {
			c++;
			switch (*c) {
			case 'n':
				strcat(ret, "\n");
				break;
			default:
				strncat(ret, c - 1, 2);
				break;
			}
		} else if ((strlen(ret) + 2) < sizeof(ret))
			strncat(ret, c, 1);
	}
	if (filelist_tmppath != NULL)
		free(filelist_tmppath);
	return(ret);
}
Exemplo n.º 13
0
static void
_pic14_do_link (void)
{
  /*
   * link command format:
   * {linker} {incdirs} {lflags} -o {outfile} {spec_ofiles} {ofiles} {libs}
   *
   */
#define LFRM  "{linker} {incdirs} {sysincdirs} {lflags} -w -r -o {outfile} {user_ofile} {spec_ofiles} {ofiles} {libs}"
  hTab *linkValues = NULL;
  char *lcmd;
  set *tSet = NULL;
  int ret;
  char * procName;

  shash_add (&linkValues, "linker", "gplink");

  /* LIBRARY SEARCH DIRS */
  mergeSets (&tSet, libPathsSet);
  mergeSets (&tSet, libDirsSet);
  shash_add (&linkValues, "incdirs", joinStrSet (processStrSet (tSet, "-I", NULL, shell_escape)));

  joinStrSet (processStrSet (libDirsSet, "-I", NULL, shell_escape));
  shash_add (&linkValues, "sysincdirs", joinStrSet (processStrSet (libDirsSet, "-I", NULL, shell_escape)));

  shash_add (&linkValues, "lflags", joinStrSet (linkOptionsSet));

  {
    char *s = shell_escape (fullDstFileName ? fullDstFileName : dstFileName);

    shash_add (&linkValues, "outfile", s);
    Safe_free (s);
  }

  if (fullSrcFileName)
    {
      struct dbuf_s dbuf;
      char *s;

      dbuf_init (&dbuf, 128);

      dbuf_append_str (&dbuf, fullDstFileName ? fullDstFileName : dstFileName);
      dbuf_append (&dbuf, ".o", 2);
      s = shell_escape (dbuf_c_str (&dbuf));
      dbuf_destroy (&dbuf);
      shash_add (&linkValues, "user_ofile", s);
      Safe_free (s);
    }

  shash_add (&linkValues, "ofiles", joinStrSet (processStrSet (relFilesSet, NULL, NULL, shell_escape)));

  /* LIBRARIES */
  procName = processor_base_name ();
  if (!procName)
    procName = "16f877";

  addSet (&libFilesSet, Safe_strdup (pic14_getPIC()->isEnhancedCore ?
          "libsdcce.lib" : "libsdcc.lib"));

    {
      struct dbuf_s dbuf;

      dbuf_init (&dbuf, 128);
      dbuf_append (&dbuf, "pic", sizeof ("pic") - 1);
      dbuf_append_str (&dbuf, procName);
      dbuf_append (&dbuf, ".lib", sizeof (".lib") - 1);
      addSet (&libFilesSet, dbuf_detach_c_str (&dbuf));
    }

  shash_add (&linkValues, "libs", joinStrSet (processStrSet (libFilesSet, NULL, NULL, shell_escape)));

  lcmd = msprintf(linkValues, LFRM);
  ret = sdcc_system (lcmd);
  Safe_free (lcmd);

  if (ret)
    exit (1);
}
Exemplo n.º 14
0
/*
** Global initialization of the transport layer
*/
void transport_global_startup(void){
  if( g.urlIsSsh ){
    /* Only SSH requires a global initialization.  For SSH we need to create
    ** and run an SSH command to talk to the remote machine.
    */
    const char *zSsh;  /* The base SSH command */
    Blob zCmd;         /* The SSH command */
    char *zHost;       /* The host name to contact */
    char zIn[200];     /* An input line received back from remote */

    zSsh = db_get("ssh-command", zDefaultSshCmd);
    blob_init(&zCmd, zSsh, -1);
    if( g.urlPort!=g.urlDfltPort ){
#ifdef __MINGW32__
      blob_appendf(&zCmd, " -P %d", g.urlPort);
#else
      blob_appendf(&zCmd, " -p %d", g.urlPort);
#endif
    }
    if( g.urlUser && g.urlUser[0] ){
      zHost = mprintf("%s@%s", g.urlUser, g.urlName);
#ifdef __MINGW32__
      /* Only win32 (and specifically PLINK.EXE support the -pw option */
      if( g.urlPasswd && g.urlPasswd[0] ){
        Blob pw;
        blob_zero(&pw);
        if( g.urlPasswd[0]=='*' ){
          char *zPrompt;
          zPrompt = mprintf("Password for [%s]: ", zHost);
          prompt_for_password(zPrompt, &pw, 0);
          free(zPrompt);
        }else{
          blob_init(&pw, g.urlPasswd, -1);
        }
        blob_append(&zCmd, " -pw ", -1);
        shell_escape(&zCmd, blob_str(&pw));
        blob_reset(&pw);
      }
#endif
    }else{
      zHost = mprintf("%s", g.urlName);
    }
    blob_append(&zCmd, " ", 1);
    shell_escape(&zCmd, zHost);
    free(zHost);
    /* printf("%s\n", blob_str(&zCmd)); */
    popen2(blob_str(&zCmd), &sshIn, &sshOut, &sshPid);
    if( sshPid==0 ){
      fossil_fatal("cannot start ssh tunnel using [%b]", &zCmd);
    }
    blob_reset(&zCmd);

    /* Send an "echo" command to the other side to make sure that the
    ** connection is up and working.
    */
    fprintf(sshOut, "echo test\n");
    fflush(sshOut);
    sshin_read(zIn, sizeof(zIn));
    if( memcmp(zIn, "test", 4)!=0 ){
      pclose2(sshIn, sshOut, sshPid);
      fossil_fatal("ssh connection failed: [%s]", zIn);
    }
  }
}
Exemplo n.º 15
0
static void append_escape(sl* list, const char* fn) {
    sl_append_nocopy(list, shell_escape(fn));
}
Exemplo n.º 16
0
void check_processes()
{
  if (badprocess == DET_IGNORE)
    return;

  char *proclist = NULL, *out = NULL, *p = NULL, *np = NULL, *curp = NULL, buf[1024] = "", bin[128] = "";

  proclist = process_list[0] ? process_list : NULL;

  if (!proclist)
    return;

  if (!shell_exec("ps x", NULL, &out, NULL))
    return;

  /* Get this binary's filename */
  strlcpy(buf, shell_escape(binname), sizeof(buf));
  p = strrchr(buf, '/');
  if (p) {
    p++;
    strlcpy(bin, p, sizeof(bin));
  } else {
    bin[0] = 0;
  }
  /* Fix up the "permitted processes" list */
  p = (char *) my_calloc(1, strlen(proclist) + strlen(bin) + 6);
  strcpy(p, proclist);
  strcat(p, " ");
  strcat(p, bin);
  strcat(p, " ");
  proclist = p;
  curp = out;
  while (curp) {
    np = strchr(curp, '\n');
    if (np)
      *np++ = 0;
    if (atoi(curp) > 0) {
      char *pid = NULL, *tty = NULL, *mystat = NULL, *mytime = NULL, cmd[512] = "", line[2048] = "";

      strlcpy(line, curp, sizeof(line));
      /* it's a process line */
      /* Assuming format: pid tty stat time cmd */
      pid = newsplit(&curp);
      tty = newsplit(&curp);
      mystat = newsplit(&curp);
      mytime = newsplit(&curp);
      strlcpy(cmd, curp, sizeof(cmd));
      /* skip any <defunct> procs "/bin/sh -c" crontab stuff and binname crontab stuff */
      if (!strstr(cmd, "<defunct>") && !strncmp(cmd, "/bin/sh -c", 10) && 
          !strncmp(cmd, shell_escape(binname), strlen(shell_escape(binname)))) {
        /* get rid of any args */
        if ((p = strchr(cmd, ' ')))
          *p = 0;
        /* remove [] or () */
        if (strlen(cmd)) {
          p = cmd + strlen(cmd) - 1;
          if (((cmd[0] == '(') && (*p == ')')) || ((cmd[0] == '[') && (*p == ']'))) {
            *p = 0;
            strcpy(buf, cmd + 1);
            strcpy(cmd, buf);
          }
        }

        /* remove path */
        if ((p = strrchr(cmd, '/'))) {
          p++;
          strcpy(buf, p);
          strcpy(cmd, buf);
        }

        /* skip "ps" */
        if (strcmp(cmd, "ps")) {
          /* see if proc's in permitted list */
          strcat(cmd, " ");
          if ((p = strstr(proclist, cmd))) {
            /* Remove from permitted list */
            while (*p != ' ')
              *p++ = 1;
          } else {
            char *work = NULL;
            size_t size = 0;

            size = strlen(line) + 22;
            work = (char *) my_calloc(1, size);
            simple_snprintf(work, size, "Unexpected process: %s", line);
            detected(DETECT_PROCESS, work);
            free(work);
          }
        }
      }
    }
    curp = np;
  }
  free(proclist);
  if (out)
    free(out);
}
Exemplo n.º 17
0
static void appendf_escape(sl* list, const char* fmt, const char* fn) {
    char* esc = shell_escape(fn);
    sl_appendf(list, fmt, esc);
    free(esc);
}
Exemplo n.º 18
0
pid_t my_fork(void)
{
	pid_t pid = -1;
	int try;
	for (try = 0; try < 10; try++) {
		errno = 0;
		pid = fork();
		if (pid != -1 || errno != EAGAIN)
			return pid;
		err("fork: retry: Resource temporarily unavailable\n");
		usleep(100 * 1000);
	}
	return pid;
}

void m__system(char **argv, int flags, const char *res_name, pid_t *kid, int *fd, int *ex)
{
	pid_t pid;
	int status, rv = -1;
	int timeout = 0;
	char **cmdline = argv;
	int pipe_fds[2];

	struct sigaction so;
	struct sigaction sa;

	if (flags & (RETURN_STDERR_FD | RETURN_STDOUT_FD))
		assert(fd);

	sa.sa_handler = &alarm_handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;

	if (dry_run || verbose) {
		if (sh_varname && *cmdline)
			printf("%s=%s\n", sh_varname,
					res_name ? shell_escape(res_name) : "");
		while (*cmdline) {
			printf("%s ", shell_escape(*cmdline++));
		}
		printf("\n");
		if (dry_run) {
			if (kid)
				*kid = -1;
			if (fd)
				*fd = -1;
			if (ex)
				*ex = 0;
			return;
		}
	}

	/* flush stdout and stderr, so output of drbdadm
	 * and helper binaries is reported in order! */
	fflush(stdout);
	fflush(stderr);

	if (adjust_with_progress && !(flags & RETURN_STDERR_FD))
		flags |= SUPRESS_STDERR;

	/* create the pipe in any case:
	 * it helps the analyzer and later we have:
	 * '*fd = pipe_fds[0];' */
	if (pipe(pipe_fds) < 0) {
		perror("pipe");
		fprintf(stderr, "Error in pipe, giving up.\n");
		exit(E_EXEC_ERROR);
	}

	pid = my_fork();
	if (pid == -1) {
		fprintf(stderr, "Can not fork\n");
		exit(E_EXEC_ERROR);
	}
	if (pid == 0) {
#ifndef _WIN32
		prctl(PR_SET_PDEATHSIG, SIGKILL);
#endif
		/* Child: close reading end. */
		close(pipe_fds[0]);
		if (flags & RETURN_STDOUT_FD) {
			dup2(pipe_fds[1], STDOUT_FILENO);
		}
		if (flags & RETURN_STDERR_FD) {
			dup2(pipe_fds[1], STDERR_FILENO);
		}
		close(pipe_fds[1]);

		if (flags & SUPRESS_STDERR) {
			FILE *f = freopen("/dev/null", "w", stderr);
			if (!f)
				fprintf(stderr, "freopen(/dev/null) failed\n");
		}
		if (argv[0])
		{
#ifdef _WIN32
			// DW-1203 execvp() run with the full path.
			char path[256];
			char *temp = strdup(argv[0]);
			char *ptr, *name;
			/* DW-1425: it's supposed to run any application that belongs to the paths have been set in 'path' env var as long as this is able to parse env vars.
						since cygwin is NOT, preferentially search full path that is gotton from env var of drbd and drx. */
#define DRBDADM_MAX_ENV_LEN		64	
			char envs[][DRBDADM_MAX_ENV_LEN] = { "DRBD_PATH", "DRX_PATH", "" };
			int i = 0;
			// remove /usr/bin/
			name = ptr = strtok(temp, "/");
			while (ptr = strtok(NULL, "/"))
			{
				name = ptr;
			}
			
			for (i = 0; i < sizeof(envs) / DRBDADM_MAX_ENV_LEN; i++)
			{
				if (i == (sizeof(envs) / DRBDADM_MAX_ENV_LEN) - 1)
					strcpy(path, name);
				else
					sprintf(path, "%s\\%s", getenv(envs[i]), name);

				if (!execvp(path, argv))
					break;
			}
#else
			execvp(argv[0], argv);
#endif
		}
#ifdef _WIN32
		fprintf(stderr, "Can not exec %s\n", argv[0]);
		perror("Failed");
#else
		fprintf(stderr, "Can not exec\n");
#endif
		exit(E_EXEC_ERROR);
	}

	/* Parent process: close writing end. */
	close(pipe_fds[1]);

	if (flags & SLEEPS_FINITE) {
		sigaction(SIGALRM, &sa, &so);
		alarm_raised = 0;
		switch (flags & SLEEPS_MASK) {
		case SLEEPS_SHORT:
			timeout = global_options.cmd_timeout_short;
			timeout = timeout * 2; // DW-1280 adjust alarm timeout.
			break;
		case SLEEPS_LONG:
			timeout = global_options.cmd_timeout_medium;
			break;
		case SLEEPS_VERY_LONG:
			timeout = global_options.cmd_timeout_long;
			break;
		default:
			fprintf(stderr, "logic bug in %s:%d\n", __FILE__,
				__LINE__);
			exit(E_THINKO);
		}
		alarm(timeout);
	}

	if (kid)
		*kid = pid;

	if (flags & (RETURN_STDOUT_FD | RETURN_STDERR_FD)
			||  flags == RETURN_PID) {
		if (fd)
			*fd = pipe_fds[0];

		return;
	}

	while (1) {
		if (waitpid(pid, &status, 0) == -1) {
			if (errno != EINTR)
				break;
			if (alarm_raised) {
				alarm(0);
				sigaction(SIGALRM, &so, NULL);
				rv = 0x100;
				break;
			} else {
				fprintf(stderr, "logic bug in %s:%d\n",
					__FILE__, __LINE__);
				exit(E_EXEC_ERROR);
			}
		} else {
			if (WIFEXITED(status)) {
				rv = WEXITSTATUS(status);
				break;
			}
		}
	}

	/* Do not close earlier, else the child gets EPIPE. */
	close(pipe_fds[0]);

	if (flags & SLEEPS_FINITE) {
		if (rv >= 10
		    && !(flags & (DONT_REPORT_FAILED | SUPRESS_STDERR))) {
			fprintf(stderr, "Command '");
			for (cmdline = argv; *cmdline; cmdline++) {
				fprintf(stderr, "%s", *cmdline);
				if (cmdline[1])
					fputc(' ', stderr);
			}
			if (alarm_raised) {
				fprintf(stderr,
					"' did not terminate within %u seconds\n",
					timeout);
				exit(E_EXEC_ERROR);
			} else {
				fprintf(stderr,
					"' terminated with exit code %d\n", rv);
			}
		}
	}
	fflush(stdout);
	fflush(stderr);

	if (ex)
		*ex = rv;
}
Exemplo n.º 19
0
static void test_shell_escape_one(const char *s, const char *bad, const char *expected) {
        _cleanup_free_ char *r;

        assert_se(r = shell_escape(s, bad));
        assert_se(streq_ptr(r, expected));
}