示例#1
0
文件: main.c 项目: ashwinraghav/Cqual
/* Entry point of cc1/c++.  Decode command args, then call compile_file.
   Exit code is 35 if can't open files, 34 if fatal error,
   33 if had nonfatal errors, else success.  */
int main(int argc, char **argv)
{
  register int i;
  dd_list files, preludes;
  dd_list_pos cur;
  int version_flag = 0;
  char *p;
  char *config_file = NULL;

#ifdef TIMER_USERTIME
  reset_timer(&total_time);
#endif
  start_timer(&total_time);
  region_init();
  parse_region = newregion();
  in_prelude = FALSE;
  num_hotspots = 0;
  parsed_files = dd_new_list(parse_region);

  copy_argc = 0;
  copy_argv = xmalloc((argc + 1) * sizeof(*copy_argv));
  files = dd_new_list(parse_region);
  preludes = dd_new_list(parse_region);

  p = argv[0] + strlen (argv[0]);
  while (p != argv[0] && p[-1] != '/'
#ifdef DIR_SEPARATOR
	 && p[-1] != DIR_SEPARATOR
#endif
	 )
    --p;
  progname = p;

#ifdef SIGPIPE
  signal (SIGPIPE, pipe_closed);
#endif

  copy_argv[0] = argv[0];
  copy_argc = 1;
  for (i = 1; i < argc; i++)
    {
      int j;
      bool copy_arg = TRUE;

      /* If this is a language-specific option,
	 decode it in a language-specific way.  */
      for (j = 0; lang_options[j] != 0; j++)
	if (!strncmp (argv[i], lang_options[j],
		      strlen (lang_options[j])))
	  break;
      if (lang_options[j] != 0)
	/* If the option is valid for *some* language,
	   treat it as valid even if this language doesn't understand it.  */
	c_decode_option(argv[i]);
      else if (argv[i][0] == '-' && argv[i][1] != 0)
	{
	  register char *str = argv[i] + 1;
	  if (str[0] == 'Y')
	    str++;

	  if (!strcmp (str, "dumpbase"))
	    copy_argv[copy_argc++] = argv[i++];
	  else if (str[0] == 'f')
	    {
	      register char *p = &str[1];
	      int found = 0;

	      /* Some kind of -f option.
		 P's value is the option sans `-f'.
		 Search for it in the table of options.  */

	      for (j = 0;
		   !found && j < sizeof (f_options) / sizeof (f_options[0]);
		   j++)
		{
		  if (!strcmp (p, f_options[j].string))
		    {
		      *f_options[j].variable = f_options[j].on_value;
		      /* A goto here would be cleaner,
			 but breaks the vax pcc.  */
		      found = 1;
		    }
		  if (p[0] == 'n' && p[1] == 'o' && p[2] == '-'
		      && ! strcmp (p+3, f_options[j].string))
		    {
		      *f_options[j].variable = ! f_options[j].on_value;
		      found = 1;
		    }
		}
	    }
	  else if (!strcmp (str, "pedantic"))
	    pedantic = 1;
	  else if (!strcmp (str, "pedantic-errors"))
	    flag_pedantic_errors = pedantic = 1;
	  else if (!strcmp (str, "quiet"))
	    quiet_flag = 1;
	  else if (!strcmp (str, "version"))
	    version_flag = 1;
	  else if (!strcmp (str, "w"))
	    inhibit_warnings = 1;
	  else if (!strcmp (str, "W"))
	    {
	      extra_warnings = 1;
	      /* We save the value of warn_uninitialized, since if they put
		 -Wuninitialized on the command line, we need to generate a
		 warning about not using it without also specifying -O.  */
	      if (warn_uninitialized != 1)
		warn_uninitialized = 2;
	    }
	  else if (str[0] == 'W')
	    {
	      register char *p = &str[1];
	      int found = 0;

	      /* Some kind of -W option.
		 P's value is the option sans `-W'.
		 Search for it in the table of options.  */

	      for (j = 0;
		   !found && j < sizeof (W_options) / sizeof (W_options[0]);
		   j++)
		{
		  if (!strcmp (p, W_options[j].string))
		    {
		      *W_options[j].variable = W_options[j].on_value;
		      /* A goto here would be cleaner,
			 but breaks the vax pcc.  */
		      found = 1;
		    }
		  if (p[0] == 'n' && p[1] == 'o' && p[2] == '-'
		      && ! strcmp (p+3, W_options[j].string))
		    {
		      *W_options[j].variable = ! W_options[j].on_value;
		      found = 1;
		    }
		}

	      if (found)
		;
	      else if (!strncmp (p, "id-clash-", 9))
		{
		  char *endp = p + 9;

		  while (*endp)
		    {
		      if (*endp >= '0' && *endp <= '9')
			endp++;
		      else
			{
			  error ("Invalid option `%s'", argv[i]);
			  goto id_clash_lose;
			}
		    }
		  warn_id_clash = 1;
		  id_clash_len = atoi (str + 10);
		id_clash_lose: ;
		}
	      else if (!strncmp (p, "larger-than-", 12))
		{
		  char *endp = p + 12;

		  while (*endp)
		    {
		      if (*endp >= '0' && *endp <= '9')
			endp++;
		      else
			{
			  error ("Invalid option `%s'", argv[i]);
			  goto larger_than_lose;
			}
		    }
		  warn_larger_than = 1;
		  larger_than_size = atoi (str + 13);
		larger_than_lose: ;
		}
	    }
	  else if (!strcmp (str, "o"))
	    copy_argv[copy_argc++] = argv[i++];
	  else if (str[0] == 'G')
	    {
	      if (str[1] == '\0')
		copy_argv[copy_argc++] = argv[i++];
	    }
	  else if (!strncmp (str, "aux-info", 8))
	    {
	      if (str[8] == '\0')
		copy_argv[copy_argc++] = argv[i++];
	    }
	  else if (!strcmp(str, "config"))
	    {
	      if (i < argc - 1)
		{
		  i++;
		  config_file = strdup(argv[i]);
		}
	      else
		error ("Missing -config file");
	    }
	  else if (!strcmp(str, "prelude"))
	    {
	      if (i < argc - 1)
		{
		  i++;
		  dd_add_last(parse_region, preludes,
			      rstrdup(parse_region, argv[i]));
		}
	      else
		error("Missing -prelude file");
	    }
	  else if (!strcmp(str, "hotspots"))
	    {
	      if (i < argc - 1)
		{
		  i++;
		  num_hotspots = atoi(argv[i]);
		  if (num_hotspots < 0)
		    error("Negative value for -hotspots count");
		}
	      else
		error("Missing -hotspots count");
	    }
	  else if (!strcmp( str, "program-files"))
	    {
	      if (i < argc - 1)
		{
		  i++;
		  add_program_files(argv[i], files);
		}
	      else
		error("Missing -program-files file");
	    }
	}
      else if (argv[i][0] == '+')
	;
      else
	{
	  /* Allow wildcards, because PAM won't expand files */
	  glob_t globbuf;
	  char **cur;

	  if (glob(argv[i], 0, NULL, &globbuf))
	    {
	      /* glob returned non-zero error status; abort */
	      fprintf(stderr, "%s: file not found\n", argv[i]);
	      exit(FATAL_EXIT_CODE);
	    }
	  else
	    for (cur = globbuf.gl_pathv; *cur; cur++)
	      {
		/* Assume anything called prelude.i is a prelude file */
		if ( strlen(*cur) >= 9 &&
                    !strncmp("prelude.i", *cur + strlen(*cur) - 9, 9))
		  dd_add_last(parse_region, preludes,
			      rstrdup(parse_region, *cur));
		else
		  dd_add_last(parse_region, files,
			      rstrdup(parse_region, *cur));
	      }
	  copy_arg = FALSE;
	}

      if (copy_arg)
	copy_argv[copy_argc++] = argv[i];
    }
  copy_argv[copy_argc] = NULL;

  if (flag_casts_preserve && flag_flow_sensitive) {
    fprintf(stderr, "-fcasts-preserve currently not allowed with "
	    "-fflow_sensitive");
    exit(FATAL_EXIT_CODE);
  }

  /* Now analyze *all* of the files.  First, initialize all appropriate
     data structures. */
  init_types();
  cval_init();
  init_effects();
  init_qtype();
  init_quals();
  init_qerror();

  init_store();

  if (config_file)
    load_config_file_quals(config_file);

  /* Add const so that we can do -fconst-subtyping no matter what */
  if (!const_qual)
    {
      begin_po_qual();
      const_qual = add_qual("const");
      add_level_qual(const_qual, level_ref);
      set_po_nonprop();
      end_po_qual();
    }

  /* Add volatile so we can handle noreturn functions */
  if (!volatile_qual)
    {
      begin_po_qual();
      volatile_qual = add_qual("volatile");
      add_level_qual(volatile_qual, level_ref);
      add_sign_qual(volatile_qual, sign_eq);
      set_po_nonprop();
      end_po_qual();
    }

  /* Add noreturn, for non-returning functions */
  if (!noreturn_qual)
    {
      begin_po_qual();
      noreturn_qual = add_qual("noreturn");
      add_level_qual(noreturn_qual, level_value);
      add_sign_qual(noreturn_qual, sign_eq);
      set_po_nonprop();
      end_po_qual();
    }

  end_define_pos(); /* Allow cqual to run with no qualifiers */

  init_pam();
  init_analyze();
  found_fs_qual = FALSE; /* Force reset, since init_analyze may
			    look up some quals */

  /* Now analyze the prelude files */
  in_prelude = TRUE;
  dd_scan(cur, preludes)
    {
      char *file;
      
      file = DD_GET(char *, cur);
      fprintf(stderr, "Analyzing prelude %s\n", file);
      compile_file(file);
    }
示例#2
0
static int getparam_display(struct param_opts *popt, char *pattern)
{
        int rc;
        int fd;
        int i;
        char *buf;
        glob_t glob_info;
        char filename[PATH_MAX + 1];    /* extra 1 byte for file type */

        rc = glob(pattern, GLOB_BRACE, NULL, &glob_info);
        if (rc) {
                fprintf(stderr, "error: get_param: %s: %s\n",
                        pattern, globerrstr(rc));
                return -ESRCH;
        }

	buf = malloc(PAGE_CACHE_SIZE);
	for (i = 0; i  < glob_info.gl_pathc; i++) {
		char *valuename = NULL;

		memset(buf, 0, PAGE_CACHE_SIZE);
                /* As listparam_display is used to show param name (with type),
                 * here "if (only_path)" is ignored.*/
                if (popt->po_show_path) {
			if (strlen(glob_info.gl_pathv[i]) >
			    sizeof(filename)-1) {
				free(buf);
				return -E2BIG;
			}
			strncpy(filename, glob_info.gl_pathv[i],
				sizeof(filename));
                        valuename = display_name(filename, 0);
                }

                /* Write the contents of file to stdout */
                fd = open(glob_info.gl_pathv[i], O_RDONLY);
                if (fd < 0) {
                        fprintf(stderr,
                                "error: get_param: opening('%s') failed: %s\n",
                                glob_info.gl_pathv[i], strerror(errno));
                        continue;
                }

		do {
			rc = read(fd, buf, PAGE_CACHE_SIZE);
			if (rc == 0)
				break;
                        if (rc < 0) {
                                fprintf(stderr, "error: get_param: "
                                        "read('%s') failed: %s\n",
                                        glob_info.gl_pathv[i], strerror(errno));
                                break;
                        }
                        /* Print the output in the format path=value if the
                         * value contains no new line character or cab be
                         * occupied in a line, else print value on new line */
                        if (valuename && popt->po_show_path) {
                                int longbuf = strnchr(buf, rc - 1, '\n') != NULL
                                              || rc > 60;
                                printf("%s=%s", valuename, longbuf ? "\n" : buf);
                                valuename = NULL;
                                if (!longbuf)
                                        continue;
                                fflush(stdout);
                        }
                        rc = write(fileno(stdout), buf, rc);
                        if (rc < 0) {
                                fprintf(stderr, "error: get_param: "
                                        "write to stdout failed: %s\n",
                                        strerror(errno));
                                break;
                        }
                } while (1);
                close(fd);
        }

        globfree(&glob_info);
        free(buf);
        return rc;
}
示例#3
0
文件: portscan.cpp 项目: Eih3/v0.83
    int GetAvailablePorts( std::vector<std::string>& result,
					   bool checkInUse )
    {
#ifdef _WIN32

	   std::stringstream devname;
	   ctb::SerialPort com;

	   for( int i = 1; i < 64; i++ )
	   {
            devname.clear();
            devname.str( "" );

            // some systems like WinCE doesn't like the extended port numbering...
            i < 10 ? devname << "COM" << i : devname << "\\\\.\\COM" << i;
            if( com.Open( devname.str().c_str() ) >= 0 ) {
                devname.str("");
                devname << "COM" << i;
                result.push_back( devname.str().c_str() );
            }
            com.Close();
	   }

#else
	   glob_t globbuf;

	   // search for standard serial ports
	   int res = glob( "/dev/ttyS*", GLOB_ERR, NULL, &globbuf );

	   if( res == 0 ) {

		  // no error, glob was successful
		  for( int i = 0; i < globbuf.gl_pathc; i++ ) {

			 if( checkInUse ) {

				ctb::SerialPort com;

				if( com.Open( globbuf.gl_pathv[ i ] ) < 0 ) {

				    continue;

				}

				result.push_back( std::string( globbuf.gl_pathv[ i ] ) );

			 }
		  }

	   }
	   globfree( &globbuf );

	   // search for USB to RS232 converters
	   res = glob( "/dev/ttyUSB*", GLOB_ERR, NULL, &globbuf );

	   if( res == 0 ) {

		  // no error, glob was successful
		  for( int i = 0; i < globbuf.gl_pathc; i++ ) {

			 if( checkInUse ) {

				ctb::SerialPort com;

				if( com.Open( globbuf.gl_pathv[ i ] ) < 0 ) {

				    continue;

				}

				result.push_back( std::string( globbuf.gl_pathv[ i ] ) );

			 }
		  }

	   }

	   globfree( &globbuf );
#endif

    return result.size();

    }
示例#4
0
int main (int argc, char **argv)
{
Q330 q330;
Q330_ADDR addr;

    init(argc, argv, &q330);

    switch (q330.cmd.code) {

      case Q330_CMD_REBOOT:
        boot(&q330);
        break;

      case Q330_CMD_SAVE:
        save(&q330);
        break;

      case Q330_CMD_SAVEBOOT:
        save(&q330);
        sleep(5);
        boot(&q330);
        break;

      case Q330_CMD_RESYNC:
        resync(&q330);
        break;

      case Q330_CMD_GPS_ON:
        gpsON(&q330);
        break;

      case Q330_CMD_GPS_OFF:
        gpsOFF(&q330);
        break;

      case Q330_CMD_GPS_COLD:
        gpsColdStart(&q330);
        break;

      case Q330_CMD_GPS_CNF:
        gpsCnf(&q330);
        break;

      case Q330_CMD_GPS_ID:
        gpsId(&q330);
        break;

      case Q330_CMD_CAL_START:
        calStart(&q330);
        break;

      case Q330_CMD_CAL_STOP:
        calStop(&q330);
        break;

      case Q330_CMD_IFCONFIG:
        ifconfig(&q330);
        break;

      case Q330_CMD_STATUS:
        status(&q330);
        break;

      case Q330_CMD_FIX:
        fix(&q330);
        break;

      case Q330_CMD_GLOB:
        glob(&q330);
        break;

      case Q330_CMD_SC:
        sc(&q330);
        break;

      case Q330_CMD_PULSE:
        pulse(&q330);
        break;

      case Q330_CMD_AMASS:
        amass(&q330);
        break;

      case Q330_CMD_DCP:
        dcp(&q330);
        break;

      case Q330_CMD_SPP:
        spp(&q330);
        break;

      case Q330_CMD_MAN:
        man(&q330);
        break;

      case Q330_CMD_CO:
        checkout(&q330);
        break;

      default:
        fprintf(stderr, "ERROR: command '%s' is unsupported\n", q330.cmd.name);
        break;

    }

    if (q330.qdp != NULL) qdpDeregister(q330.qdp, TRUE);
}
示例#5
0
int
main (int argc, char *argv[])
{
  int i, j;
  int glob_flags = 0;
  glob_t g;
  int quotes = 1;

  while ((i = getopt (argc, argv, "bcdegmopqstT")) != -1)
    switch(i)
      {
      case 'b':
	glob_flags |= GLOB_BRACE;
	break;
      case 'c':
	glob_flags |= GLOB_NOCHECK;
	break;
      case 'd':
	glob_flags |= GLOB_ONLYDIR;
	break;
      case 'e':
	glob_flags |= GLOB_NOESCAPE;
	break;
      case 'g':
	glob_flags |= GLOB_NOMAGIC;
	break;
      case 'm':
	glob_flags |= GLOB_MARK;
	break;
      case 'o':
	glob_flags |= GLOB_DOOFFS;
	g.gl_offs = 1;
	break;
      case 'p':
	glob_flags |= GLOB_PERIOD;
	break;
      case 'q':
	quotes = 0;
	break;
      case 's':
	glob_flags |= GLOB_NOSORT;
	break;
      case 't':
	glob_flags |= GLOB_TILDE;
	break;
      case 'T':
	glob_flags |= GLOB_TILDE_CHECK;
	break;
      default:
	exit (-1);
      }

  if (optind >= argc || chdir (argv[optind]))
    exit(1);

  j = optind + 1;
  if (optind + 1 >= argc)
    exit (1);

  /* Do a glob on each remaining argument.  */
  for (j = optind + 1; j < argc; j++) {
    i = glob (argv[j], glob_flags, NULL, &g);
    if (i != 0)
      break;
    glob_flags |= GLOB_APPEND;
  }

  /* Was there an error? */
  if (i == GLOB_NOSPACE)
    puts ("GLOB_NOSPACE");
  else if (i == GLOB_ABORTED)
    puts ("GLOB_ABORTED");
  else if (i == GLOB_NOMATCH)
    puts ("GLOB_NOMATCH");

  /* If we set an offset, fill in the first field.  */
  if (glob_flags & GLOB_DOOFFS)
    g.gl_pathv[0] = (char *) "abc";

  /* Print out the names.  Unless otherwise specified, qoute them.  */
  if (g.gl_pathv)
    {
      for (i = 0; i < g.gl_pathc; ++i)
        printf ("%s%s%s\n", quotes ? "`" : "", g.gl_pathv[i],
		quotes ? "'" : "");
    }
  return 0;
}
示例#6
0
FILE *
ftpd_popen(char *program, char *type, int do_stderr, int no_glob)
{
	char *cp;
	FILE *iop;
	int argc, gargc, pdes[2], pid;
	char **pop, *argv[MAXARGS], *gargv[MAXGLOBS];
	char *foo;

	if (strcmp(type, "r") && strcmp(type, "w"))
		return (NULL);

	if (!pids) {

	    /* This function is ugly and should be rewritten, in
	     * modern unices there is no such thing as a maximum
	     * filedescriptor.
	     */

	    fds = getdtablesize();
	    pids = (int*)calloc(fds, sizeof(int));
	    if(!pids)
		return NULL;
	}
	if (pipe(pdes) < 0)
		return (NULL);

	/* break up string into pieces */
	foo = NULL;
	for (argc = 0, cp = program; argc < MAXARGS - 1; cp = NULL) {
		if (!(argv[argc++] = strtok_r(cp, " \t\n", &foo)))
			break;
	}
	argv[MAXARGS - 1] = NULL;

	gargv[0] = (char*)ftp_rooted(argv[0]);
	/* glob each piece */
	for (gargc = argc = 1; argv[argc] && gargc < MAXGLOBS - 1; argc++) {
		glob_t gl;
		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE
		    |
#ifdef GLOB_MAXPATH
	GLOB_MAXPATH
#else
	GLOB_LIMIT
#endif
		    ;

		memset(&gl, 0, sizeof(gl));
		if (no_glob ||
		    glob(argv[argc], flags, NULL, &gl) ||
		    gl.gl_pathc == 0)
			gargv[gargc++] = strdup(argv[argc]);
		else
			for (pop = gl.gl_pathv;
			     *pop && gargc < MAXGLOBS - 1;
			     pop++)
				gargv[gargc++] = strdup(*pop);
		globfree(&gl);
	}
	gargv[gargc] = NULL;

	iop = NULL;
	switch(pid = fork()) {
	case -1:			/* error */
		close(pdes[0]);
		close(pdes[1]);
		goto pfree;
		/* NOTREACHED */
	case 0:				/* child */
		if (*type == 'r') {
			if (pdes[1] != STDOUT_FILENO) {
				dup2(pdes[1], STDOUT_FILENO);
				close(pdes[1]);
			}
			if(do_stderr)
			    dup2(STDOUT_FILENO, STDERR_FILENO);
			close(pdes[0]);
		} else {
			if (pdes[0] != STDIN_FILENO) {
				dup2(pdes[0], STDIN_FILENO);
				close(pdes[0]);
			}
			close(pdes[1]);
		}
		execv(gargv[0], gargv);
		gargv[0] = argv[0];
		execv(gargv[0], gargv);
		_exit(1);
	}
	/* parent; assume fdopen can't fail...  */
	if (*type == 'r') {
		iop = fdopen(pdes[0], type);
		close(pdes[1]);
	} else {
		iop = fdopen(pdes[1], type);
		close(pdes[0]);
	}
	pids[fileno(iop)] = pid;

pfree:
	for (argc = 1; gargv[argc] != NULL; argc++)
	    free(gargv[argc]);


	return (iop);
}
示例#7
0
文件: vmdio.c 项目: yhalcyon/Gromacs
static int load_vmd_library(const char *fn, t_gmxvmdplugin *vmdplugin)
{
    char            pathname[GMX_PATH_MAX], filename[GMX_PATH_MAX];
    const char     *pathenv;
    const char     *err;
    int             i;
    int             ret = 0;
    char            pathenv_buffer[GMX_PATH_MAX];
#ifndef GMX_NATIVE_WINDOWS
    glob_t          globbuf;
    const char     *defpath_suffix = "/plugins/*/molfile";
    const char     *defpathenv     = GMX_VMD_PLUGIN_PATH;
#else
    WIN32_FIND_DATA ffd;
    HANDLE          hFind = INVALID_HANDLE_VALUE;
    char            progfolder[GMX_PATH_MAX];
    char            defpathenv[GMX_PATH_MAX];
    const char     *defpath_suffix = "\\plugins\\WIN32\\molfile";
    SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, progfolder);
    sprintf(defpathenv, "%s\\University of Illinois\\VMD\\plugins\\WIN32\\molfile", progfolder);
#endif

    vmdplugin->api      = NULL;
    vmdplugin->filetype = strrchr(fn, '.');
    if (!vmdplugin->filetype)
    {
        return 0;
    }
    vmdplugin->filetype++;

    /* First look for an explicit path given at run time for the
     * plugins, then an implicit run-time path, and finally for one
     * given at configure time. This last might be hard-coded to the
     * default for VMD installs. */
    pathenv = getenv("VMD_PLUGIN_PATH");
    if (pathenv == NULL)
    {
        pathenv = getenv("VMDDIR");
        if (NULL == pathenv)
        {
            printf("\nNeither VMD_PLUGIN_PATH or VMDDIR set. ");
            printf("Using default location:\n%s\n", defpathenv);
            pathenv = defpathenv;
        }
        else
        {
            printf("\nVMD_PLUGIN_PATH no set, but VMDDIR is set. ");
#ifdef _MSC_VER
            _snprintf_s(pathenv_buffer, sizeof(pathenv_buffer), _TRUNCATE, "%s%s", pathenv, defpath_suffix);
#else
            snprintf(pathenv_buffer, sizeof(pathenv_buffer), "%s%s", pathenv, defpath_suffix);
#endif
            printf("Using semi-default location:\n%s\n", pathenv_buffer);
            pathenv = pathenv_buffer;
        }
    }
    strncpy(pathname, pathenv, sizeof(pathname));
#ifndef GMX_NATIVE_WINDOWS
    strcat(pathname, "/*.so");
    glob(pathname, 0, NULL, &globbuf);
    if (globbuf.gl_pathc == 0)
    {
        printf("\nNo VMD Plugins found\n"
               "Set the environment variable VMD_PLUGIN_PATH to the molfile folder within the\n"
               "VMD installation.\n"
               "The architecture (e.g. 32bit versus 64bit) of Gromacs and VMD has to match.\n");
        return 0;
    }
    for (i = 0; i < globbuf.gl_pathc && vmdplugin->api == NULL; i++)
    {
        /* FIXME: Undefined which plugin is chosen if more than one plugin
           can read a certain file ending. Requires some additional command
           line option or enviroment variable to specify which plugin should
           be picked.
         */
        ret |= load_sharedlibrary_plugins(globbuf.gl_pathv[i], vmdplugin);
    }
    globfree(&globbuf);
#else
    strcat(pathname, "\\*.so");
    hFind = FindFirstFile(pathname, &ffd);
    if (INVALID_HANDLE_VALUE == hFind)
    {
        printf("\nNo VMD Plugins found\n");
        return 0;
    }
    do
    {
        sprintf(filename, "%s\\%s", pathenv, ffd.cFileName);
        ret |= load_sharedlibrary_plugins(filename, vmdplugin);
    }
    while (FindNextFile(hFind, &ffd )  != 0 && vmdplugin->api == NULL);
    FindClose(hFind);
#endif

    if (!ret)
    {
        printf("\nCould not open any VMD library.\n");
        err = vmddlerror();
        if (!err)
        {
            printf("Compiled with dlopen?\n");
        }
        else
        {
            printf("Last error:\n%s\n", err);
        }
        return 0;
    }

    if (vmdplugin->api == NULL)
    {
        printf("\nNo plugin for %s found\n", vmdplugin->filetype);
        return 0;
    }

    if (vmdplugin->api->abiversion < 10)
    {
        printf("\nPlugin and/or VMD is too old. At least VMD 1.8.6 is required.\n");
        return 0;
    }

    printf("\nUsing VMD plugin: %s (%s)\n", vmdplugin->api->name, vmdplugin->api->prettyname);

    return 1;

}
示例#8
0
文件: sesutil.c 项目: drpnd/freebsd
static int
sesled(int argc, char **argv, bool setfault)
{
	encioc_elm_devnames_t objdn;
	encioc_element_t *objp;
	glob_t g;
	char *disk, *endptr;
	size_t len, i, ndisks;
	int fd;
	unsigned int nobj, j, sesid;
	bool all, isses, onoff;

	isses = false;
	all = false;
	onoff = false;

	if (argc != 3) {
		usage(stderr, (setfault ? "fault" : "locate"));
	}

	disk = argv[1];

	sesid = strtoul(disk, &endptr, 10);
	if (*endptr == '\0') {
		endptr = strrchr(uflag, '*');
		if (endptr != NULL && *endptr == '*') {
			warnx("Must specifying a SES device (-u) to use a SES "
			    "id# to identify a disk");
			usage(stderr, (setfault ? "fault" : "locate"));
		}
		isses = true;
	}

	if (strcmp(argv[2], "on") == 0) {
		onoff = true;
	} else if (strcmp(argv[2], "off") == 0) {
		onoff = false;
	} else {
		usage(stderr, (setfault ? "fault" : "locate"));
	}

	if (strcmp(disk, "all") == 0) {
		all = true;
	}
	len = strlen(disk);

	/* Get the list of ses devices */
	if (glob((uflag != NULL ? uflag : "/dev/ses[0-9]*"), 0, NULL, &g) ==
	    GLOB_NOMATCH) {
		globfree(&g);
		errx(EXIT_FAILURE, "No SES devices found");
	}

	ndisks = 0;
	for (i = 0; i < g.gl_pathc; i++) {
		/* ensure we only got numbers after ses */
		if (strspn(g.gl_pathv[i] + 8, "0123456789") !=
		    strlen(g.gl_pathv[i] + 8)) {
			continue;
		}
		if ((fd = open(g.gl_pathv[i], O_RDWR)) < 0) {
			/*
			 * Don't treat non-access errors as critical if we are
			 * accessing all devices
			 */
			if (errno == EACCES && g.gl_pathc > 1) {
				err(EXIT_FAILURE, "unable to access SES device");
			}
			warn("unable to access SES device: %s", g.gl_pathv[i]);
			continue;
		}

		if (ioctl(fd, ENCIOC_GETNELM, (caddr_t) &nobj) < 0) {
			close(fd);
			err(EXIT_FAILURE, "ENCIOC_GETNELM");
		}

		objp = calloc(nobj, sizeof(encioc_element_t));
		if (objp == NULL) {
			close(fd);
			err(EXIT_FAILURE, "calloc()");
		}

		if (ioctl(fd, ENCIOC_GETELMMAP, (caddr_t) objp) < 0) {
			close(fd);
			err(EXIT_FAILURE, "ENCIOC_GETELMMAP");
		}

		if (isses) {
			if (sesid > nobj) {
				close(fd);
				errx(EXIT_FAILURE,
				     "Requested SES ID does not exist");
			}
			do_led(fd, sesid, onoff, setfault);
			ndisks++;
			close(fd);
			break;
		}
		for (j = 0; j < nobj; j++) {
			memset(&objdn, 0, sizeof(objdn));
			objdn.elm_idx = objp[j].elm_idx;
			objdn.elm_names_size = 128;
			objdn.elm_devnames = calloc(128, sizeof(char));
			if (objdn.elm_devnames == NULL) {
				close(fd);
				err(EXIT_FAILURE, "calloc()");
			}
			if (ioctl(fd, ENCIOC_GETELMDEVNAMES,
			    (caddr_t) &objdn) <0) {
				continue;
			}
			if (objdn.elm_names_len > 0) {
				if (all) {
					do_led(fd, objdn.elm_idx,
					    onoff, setfault);
					continue;
				}
				if (disk_match(objdn.elm_devnames, disk, len)) {
					do_led(fd, objdn.elm_idx,
					    onoff, setfault);
					ndisks++;
					break;
				}
			}
		}
		close(fd);
	}
	globfree(&g);
	if (ndisks == 0 && all == false) {
		errx(EXIT_FAILURE, "Count not find the SES id of device '%s'",
		    disk);
	}

	return (EXIT_SUCCESS);
}
示例#9
0
void getDirectoryListing( std::vector< std::string >& listing, const std::string& dir, const std::string& extension, bool appenddetails )
{
    std::list< std::pair< std::string, std::string > > files;

#ifdef WIN32
    WIN32_FIND_DATA findData;
    HANDLE          fileHandle;
    int             flag = 1;
    std::string     search ( ( extension == "" ) ? "*" : "*." );
    std::string     directory( dir );

    if ( directory == "" )
        directory = ".";

    directory += "/";
    search = directory + search + extension;
    fileHandle = FindFirstFile( search.c_str(), &findData );
    if ( fileHandle == INVALID_HANDLE_VALUE )
        return;

    while ( flag )
    {
        if ( strcmp( findData.cFileName, "." ) && strcmp( findData.cFileName, ".." ) )
        {
            std::string details;
            if ( appenddetails )
                details = convertFileTime( findData.ftLastWriteTime );

            // check for directories
            if( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
                files.push_back( make_pair( "[" + std::string( findData.cFileName ) + "]", details ) );
            else
                files.push_back( make_pair( findData.cFileName, details ) );
        }
        flag = FindNextFile( fileHandle, &findData );
    }
    FindClose( fileHandle );
#endif

#ifdef LINUX
    struct stat     fileInfo;
    glob_t          ff_glob;
    std::string     directory( dir );

    if ( directory == "" )
        directory = ".";

    directory += "/";
    std::string search = directory + "*" + extension;

    // check if the directory exists
    if ( opendir( directory.c_str() ) == NULL )
        return;

    glob( search.c_str(), 0, NULL, &ff_glob );
    for ( size_t cnt = 0; cnt < ff_glob.gl_pathc; ++cnt )
    {
        std::string filename( ff_glob.gl_pathv[ cnt ] );
        filename.erase( 0, directory.size() );
        std::string details;
        // check for directories
        stat( std::string( directory + filename ).c_str(), &fileInfo );

        if ( appenddetails )
        {
            time_t modtime = fileInfo.st_mtime;
            details = ctime( &modtime );
            details.erase( details.size() - 1 ); // remove line break at end of string
        }

        if( S_ISDIR( fileInfo.st_mode ) )
            files.push_back( make_pair( "[" + std::string( filename ) + "]", details ) );
        else
            files.push_back( make_pair( filename, details ) );
    }
#endif

    // sort and copy files into listing
    files.sort();
    std::list< std::pair< std::string, std::string > >::iterator p_beg = files.begin(), p_end = files.end();
    for ( ; p_beg != p_end; ++p_beg )
    {
        if ( appenddetails )
            listing.push_back( p_beg->second + "   " + p_beg->first );
        else
            listing.push_back( p_beg->first );
    }
}
示例#10
0
// get the next file in the directory
// automatically wrap if we've hit the end
BOOL LLDir_Solaris::getNextFileInDir(const std::string &dirname, const std::string &mask, std::string &fname, BOOL wrap)
{
	glob_t g;
	BOOL result = FALSE;
	fname = "";
	
	if(!(dirname == mCurrentDir))
	{
		// different dir specified, close old search
		mCurrentDirIndex = -1;
		mCurrentDirCount = -1;
		mCurrentDir = dirname;
	}
	
	std::string tmp_str;
	tmp_str = dirname;
	tmp_str += mask;

	if(glob(tmp_str.c_str(), GLOB_NOSORT, NULL, &g) == 0)
	{
		if(g.gl_pathc > 0)
		{
			if((int)g.gl_pathc != mCurrentDirCount)
			{
				// Number of matches has changed since the last search, meaning a file has been added or deleted.
				// Reset the index.
				mCurrentDirIndex = -1;
				mCurrentDirCount = g.gl_pathc;
			}
	
			mCurrentDirIndex++;
	
			if((mCurrentDirIndex >= (int)g.gl_pathc) && wrap)
			{
				mCurrentDirIndex = 0;
			}
			
			if(mCurrentDirIndex < (int)g.gl_pathc)
			{
//				llinfos << "getNextFileInDir: returning number " << mCurrentDirIndex << ", path is " << g.gl_pathv[mCurrentDirIndex] << llendl;

				// The API wants just the filename, not the full path.
				//fname = g.gl_pathv[mCurrentDirIndex];

				char *s = strrchr(g.gl_pathv[mCurrentDirIndex], '/');
				
				if(s == NULL)
					s = g.gl_pathv[mCurrentDirIndex];
				else if(s[0] == '/')
					s++;
					
				fname = s;
				
				result = TRUE;
			}
		}
		
		globfree(&g);
	}
	
	return(result);
}
示例#11
0
static gboolean
pk_alpm_config_parse (PkAlpmConfig *config, const gchar *filename,
			 PkAlpmConfigSection *section, GError **error)
{
	g_autoptr(GFile) file = NULL;
	g_autoptr(GFileInputStream) is = NULL;
	g_autoptr(GDataInputStream) input = NULL;
	gchar *key, *str, *line = NULL;
	guint num = 1;
	GError *e = NULL;

	g_return_val_if_fail (config != NULL, FALSE);
	g_return_val_if_fail (filename != NULL, FALSE);

	file = g_file_new_for_path (filename);
	is = g_file_read (file, NULL, &e);
	if (is == NULL) {
		g_propagate_error (error, e);
		return FALSE;
	}

	input = g_data_input_stream_new (G_INPUT_STREAM (is));

	for (;; g_free (line), ++num) {
		line = g_data_input_stream_read_line (input, NULL, NULL, &e);

		if (line == NULL)
			break;
		/* skip empty lines */
		g_strstrip (line);
		if (*line == '\0' || *line == '#')
			continue;

		/* remove trailing comments */
		for (str = line; *str != '\0' && *str != '#'; ++str);
		*str-- = '\0';

		/* change sections */
		if (*line == '[' && *str == ']') {
			*str = '\0';
			str = line + 1;

			if (*str == '\0') {
				g_set_error (&e, PK_ALPM_ERROR,
					     PK_ALPM_ERR_CONFIG_INVALID,
					     "empty section name");
				break;
			}

			section = pk_alpm_config_enter_section (config, str);
			continue;
		}

		/* parse a directive */
		if (section == NULL) {
			g_set_error (&e, PK_ALPM_ERROR, PK_ALPM_ERR_CONFIG_INVALID,
				     "directive must belong to a section");
			break;
		}

		str = line;
		key = strsep (&str, "=");
		g_strchomp (key);
		if (str != NULL)
			g_strchug (str);

		if (str == NULL) {
			/* set a boolean directive */
			if (pk_alpm_config_section_match (section,
							     "options") == 0 &&
			    pk_alpm_config_set_boolean (config, key)) {
				continue;
			}
			/* report error below */
		} else if (g_strcmp0 (key, "Include") == 0) {
			gsize i;
			glob_t match = { 0 };

			/* ignore globbing errors */
			if (glob (str, GLOB_NOCHECK, NULL, &match) != 0)
				continue;

			/* parse the files that matched */
			for (i = 0; i < match.gl_pathc; ++i) {
				if (!pk_alpm_config_parse (config,
							      match.gl_pathv[i],
							      section, &e)) {
					break;
				}
			}

			globfree (&match);
			if (e == NULL)
				continue;
			break;
		} else if (pk_alpm_config_section_match (section,
							    "options") == 0) {
			/* set a string or list directive */
			if (pk_alpm_config_set_string (config, key, str) ||
			    pk_alpm_config_set_list (config, key, str)) {
				continue;
			}
			/* report error below */
		} else if (g_strcmp0 (key, "Server") == 0) {
			if (!pk_alpm_config_add_server (config, section,
							   str, &e)) {
				break;
			}
			continue;
		}

		if (g_strcmp0 (key, "SigLevel") == 0 && str != NULL) {
			pk_alpm_config_add_siglevel (config, section, str);
			continue;
		}

		/* report errors from above */
		g_set_error (&e, PK_ALPM_ERROR, PK_ALPM_ERR_CONFIG_INVALID,
			     "unrecognised directive '%s'", key);
		break;
	}

	if (e != NULL) {
		g_propagate_prefixed_error (error, e, "%s:%u", filename, num);
		return FALSE;
	} else
		return TRUE;
}
示例#12
0
文件: man.c 项目: SylvestreG/bitrig
/*
 * manual --
 *	Search the manuals for the pages.
 */
static int
manual(const char *page, TAG *tag, glob_t *pg)
{
	ENTRY *ep, *e_sufp, *e_tag;
	TAG *missp, *sufp;
	int anyfound, cnt, found;
	char *p, buf[MAXPATHLEN];

	anyfound = 0;
	buf[0] = '*';

	/* Expand the search path. */
	if (f_all != f_where) {
		e_tag = tag == NULL ? NULL : TAILQ_FIRST(&tag->list);
		while (e_tag != NULL) {
			if (glob(e_tag->s, GLOB_BRACE | GLOB_NOSORT,
			    NULL, pg)) {
				/* No GLOB_NOMATCH here due to {arch,}. */
				warn("globbing directories");
				(void)cleanup(0);
				exit(1);
			}
			for (cnt = 0; cnt < pg->gl_pathc; cnt++) {
				if ((ep = malloc(sizeof(ENTRY))) == NULL ||
				    (ep->s = strdup(pg->gl_pathv[cnt])) ==
						NULL) {
					warn(NULL);
					(void)cleanup(0);
					exit(1);
				}
				TAILQ_INSERT_BEFORE(e_tag, ep, q);
			}
			ep = e_tag;
			e_tag = TAILQ_NEXT(e_tag, q);
			free(ep->s);
			TAILQ_REMOVE(&tag->list, ep, q);
			free(ep);
			globfree(pg);
			pg->gl_pathc = 0;
		}
	}

	/* For each element in the list... */
	e_tag = tag == NULL ? NULL : TAILQ_FIRST(&tag->list);
	for (; e_tag != NULL; e_tag = TAILQ_NEXT(e_tag, q)) {
		(void)snprintf(buf, sizeof(buf), "%s/%s.*", e_tag->s, page);
		switch (glob(buf, GLOB_APPEND | GLOB_BRACE | GLOB_NOSORT,
		    NULL, pg)) {
		case (0):
			break;
		case (GLOB_NOMATCH):
			continue;
		default:
			warn("globbing files");
			(void)cleanup(0);
			exit(1);
		}
		if (pg->gl_matchc == 0)
			continue;

		/* Find out if it's really a man page. */
		for (cnt = pg->gl_pathc - pg->gl_matchc;
		    cnt < pg->gl_pathc; ++cnt) {

			if (!f_all || !f_where) {
				check_companion(pg->gl_pathv + cnt, tag);
				if (*pg->gl_pathv[cnt] == '\0')
					continue;
			}

			/*
			 * Try the _suffix key words first.
			 *
			 * XXX
			 * Older versions of man.conf didn't have the suffix
			 * key words, it was assumed that everything was a .0.
			 * We just test for .0 first, it's fast and probably
			 * going to hit.
			 */
			(void)snprintf(buf, sizeof(buf), "*/%s.0", page);
			if (!fnmatch(buf, pg->gl_pathv[cnt], 0))
				goto next;

			e_sufp = (sufp = getlist("_suffix")) == NULL ?
			    NULL : TAILQ_FIRST(&sufp->list);
			for (found = 0;
			    e_sufp != NULL; e_sufp = TAILQ_NEXT(e_sufp, q)) {
				(void)snprintf(buf,
				     sizeof(buf), "*/%s%s", page, e_sufp->s);
				if (!fnmatch(buf, pg->gl_pathv[cnt], 0)) {
					found = 1;
					break;
				}
			}
			if (found)
				goto next;

			/* Try the _build key words next. */
			e_sufp = (sufp = getlist("_build")) == NULL ?
			    NULL : TAILQ_FIRST(&sufp->list);
			for (found = 0;
			    e_sufp != NULL; e_sufp = TAILQ_NEXT(e_sufp, q)) {
				for (p = e_sufp->s;
				    *p != '\0' && !isspace(*p); ++p);
				if (*p == '\0')
					continue;
				*p = '\0';
				(void)snprintf(buf,
				     sizeof(buf), "*/%s%s", page, e_sufp->s);
				if (!fnmatch(buf, pg->gl_pathv[cnt], 0)) {
					if (!f_where)
						build_page(p + 1,
						    &pg->gl_pathv[cnt]);
					*p = ' ';
					found = 1;
					break;
				}
				*p = ' ';
			}
			if (found) {
next:				anyfound = 1;
				if (!f_all && !f_where) {
					/* Delete any other matches. */
					while (++cnt< pg->gl_pathc)
						pg->gl_pathv[cnt] = "";
					break;
				}
				continue;
			}

			/* It's not a man page, forget about it. */
			pg->gl_pathv[cnt] = "";
		}

		if (anyfound && !f_all && !f_where)
			break;
	}

	/* If not found, enter onto the missing list. */
	if (!anyfound) {
		sigset_t osigs;

		sigprocmask(SIG_BLOCK, &blocksigs, &osigs);

		if ((missp = getlist("_missing")) == NULL)
			missp = addlist("_missing");
		if ((ep = malloc(sizeof(ENTRY))) == NULL ||
		    (ep->s = strdup(page)) == NULL) {
			warn(NULL);
			(void)cleanup(0);
			exit(1);
		}
		TAILQ_INSERT_TAIL(&missp->list, ep, q);
		sigprocmask(SIG_SETMASK, &osigs, NULL);
	}
	return (anyfound);
}
示例#13
0
文件: battery.c 项目: jb55/ds4ctl
int main(int argc, char* argv[]) {
  struct controller controller;
  glob_t pglob;

  char *device;
  glob("/sys/class/input/js*", 0, 0, &pglob);

  if (pglob.gl_pathc == 0) {
    sprintf(err, "Could not enumerate any input devices");
    return 0;
  }

  for (size_t i = 0; i < pglob.gl_pathc; ++i) {
    device = pglob.gl_pathv[i];
    if (!read_controller(device, &controller)) {
      fatal();
    }
    else {
      /* controller.capacity = 20; */
      float percent = controller.capacity / 100.f;
      printf("\ndevice: %s\n", device);
      printf("capacity: %d\n", controller.capacity);
      float scale = 255 * percent;
      printf("writing %f\n", scale);

      if (controller.capacity <= 10) {
        write_trigger(device, "heartbeat");
      }
      else {
        write_trigger(device, "none");
        write_color(device, "global", 1);
      }

      if (controller.capacity < 25) {
        if (!write_color(device, "red", 10)) fatal();
        if (!write_color(device, "green", 0)) fatal();
        if (!write_color(device, "blue", 0)) fatal();
      }
      else if (controller.capacity < 50) {
        if (!write_color(device, "red", 10)) fatal();
        if (!write_color(device, "green", 5)) fatal();
        if (!write_color(device, "blue", 0)) fatal();
      }
      else if (controller.capacity < 75 ) {
        if (!write_color(device, "red", 10)) fatal();
        if (!write_color(device, "green", 10)) fatal();
        if (!write_color(device, "blue", 0)) fatal();
      }
      else if (controller.capacity < 100 ) {
        if (!write_color(device, "red", 0)) fatal();
        if (!write_color(device, "green", 10)) fatal();
        if (!write_color(device, "blue", 0)) fatal();
      }
      else if (controller.capacity >= 100 ) {
        if (!write_color(device, "red", 0)) fatal();
        if (!write_color(device, "green", 0)) fatal();
        if (!write_color(device, "blue", 10)) fatal();
      }
    }
  }

  globfree(&pglob);

  return 0;

}
/**
 * Read all processes of the proc files system to initialize
 * the process tree (sysdep version... but should work for
 * all procfs based unices) 
 * @param reference  reference of ProcessTree
 * @return treesize>0 if succeeded otherwise =0.
 */
int initprocesstree_sysdep(ProcessTree_T ** reference) {
  int                 i = 0, j;
  int                 rv, bytes = 0;
  int                 treesize = 0;
  int                 stat_ppid = 0;
  char               *tmp = NULL;
  char                procname[STRLEN];
  char                buf[1024];
  char                stat_item_state;
  long                stat_item_cutime = 0;
  long                stat_item_cstime = 0;
  long                stat_item_rss = 0;
  glob_t              globbuf;
  unsigned long       stat_item_utime = 0;
  unsigned long       stat_item_stime = 0;
  unsigned long long  stat_item_starttime = 0ULL;
  ProcessTree_T      *pt = NULL;

  ASSERT(reference);

  /* Find all processes in the /proc directory */
  if ((rv = glob("/proc/[0-9]*", GLOB_ONLYDIR, NULL, &globbuf))) {
    LogError("system statistic error -- glob failed: %d (%s)\n", rv, STRERROR);
    return FALSE;
  } 

  treesize = globbuf.gl_pathc;

  pt = CALLOC(sizeof(ProcessTree_T), treesize);

  /* Insert data from /proc directory */
  for (i = 0; i < treesize; i++) {

    pt[i].pid = atoi(globbuf.gl_pathv[i] + strlen("/proc/"));
    
    if (!read_proc_file(buf, sizeof(buf), "stat", pt[i].pid, NULL)) {
      DEBUG("system statistic error -- cannot read /proc/%d/stat\n", pt[i].pid);
      continue;
    }

    pt[i].time = get_float_time();

    if (!(tmp = strrchr(buf, ')'))) {
      DEBUG("system statistic error -- file /proc/%d/stat parse error\n", pt[i].pid);
      continue;
    }
    *tmp = 0;
    if (sscanf(buf, "%*d (%256s", procname) != 1) {
      DEBUG("system statistic error -- file /proc/%d/stat process name parse error\n", pt[i].pid);
      continue;
    }

    tmp += 2;

    /* This implementation is done by using fs/procfs/array.c as a basis
     * it is also worth looking into the source of the procps utils */
    if (sscanf(tmp,
         "%c %d %*d %*d %*d %*d %*u %*u"
         "%*u %*u %*u %lu %lu %ld %ld %*d %*d %*d "
         "%*u %llu %*u %ld %*u %*u %*u %*u %*u "
         "%*u %*u %*u %*u %*u %*u %*u %*u %*d %*d\n",
         &stat_item_state,
         &stat_ppid,
         &stat_item_utime,
         &stat_item_stime,
         &stat_item_cutime,
         &stat_item_cstime,
         &stat_item_starttime,
         &stat_item_rss) != 8) {
      DEBUG("system statistic error -- file /proc/%d/stat parse error\n", pt[i].pid);
      continue;
    }
    
    pt[i].ppid      = stat_ppid;
    pt[i].starttime = get_starttime() + (time_t)(stat_item_starttime / HZ);
  
    /* jiffies -> seconds = 1 / HZ
     * HZ is defined in "asm/param.h"  and it is usually 1/100s but on
     * alpha system it is 1/1024s */
    pt[i].cputime     = ((float)(stat_item_utime + stat_item_stime) * 10.0) / HZ;
    pt[i].cpu_percent = 0;

    /* State is Zombie -> then we are a Zombie ... clear or? (-: */
    if (stat_item_state == 'Z')
      pt[i].status_flag |= PROCESS_ZOMBIE;

    if (page_shift_to_kb < 0)
      pt[i].mem_kbyte = (stat_item_rss >> abs(page_shift_to_kb));
    else
      pt[i].mem_kbyte = (stat_item_rss << abs(page_shift_to_kb));

    if (! read_proc_file(buf, sizeof(buf), "cmdline", pt[i].pid, &bytes)) {
      DEBUG("system statistic error -- cannot read /proc/%d/cmdline\n", pt[i].pid);
      continue;
    }
    /* The cmdline file contains argv elements/strings terminated separated by '\0' => join the string: */
    for (j = 0; j < (bytes - 1); j++)
      if (buf[j] == 0)
        buf[j] = ' ';
    pt[i].cmdline = *buf ? Str_dup(buf) : Str_dup(procname);
  }
示例#15
0
static void config_rescan(GVC_t *gvc, char *config_path)
{
    FILE *f = NULL;
    glob_t globbuf;
    char *config_glob, *config_re, *path, *libdir;
    int i, rc, re_status;
    gvplugin_library_t *library;
    regex_t re;
#ifndef WIN32
    char *plugin_glob = "libgvplugin_*";
#endif
#if defined(DARWIN_DYLIB)
    char *plugin_re_beg = "[^0-9]\\.";
    char *plugin_re_end = "\\.dylib$";
#elif defined(__MINGW32__)
	char *plugin_glob = "libgvplugin_*";
	char *plugin_re_beg = "[^0-9]-";
    char *plugin_re_end = "\\.dll$"; 
#elif defined(__CYGWIN__)
    plugin_glob = "cyggvplugin_*";
    char *plugin_re_beg = "[^0-9]-";
    char *plugin_re_end = "\\.dll$"; 
#elif defined(WIN32)
    char *plugin_glob = "gvplugin_*";
    char *plugin_re_beg = "[^0-9]";
    char *plugin_re_end = "\\.dll$"; 
#elif ((defined(__hpux__) || defined(__hpux)) && !(defined(__ia64)))
    char *plugin_re_beg = "\\.sl\\.";
    char *plugin_re_end = "$"; 
#else
    /* Everyone else */
    char *plugin_re_beg = "\\.so\\.";
    char *plugin_re_end= "$";
#endif

    if (config_path) {
	f = fopen(config_path,"w");
	if (!f) {
	    agerr(AGERR,"failed to open %s for write.\n", config_path);
	    exit(1);
	}

	fprintf(f, "# This file was generated by \"dot -c\" at time of install.\n\n");
	fprintf(f, "# You may temporarily disable a plugin by removing or commenting out\n");
	fprintf(f, "# a line in this file, or you can modify its \"quality\" value to affect\n");
	fprintf(f, "# default plugin selection.\n\n");
	fprintf(f, "# Manual edits to this file **will be lost** on upgrade.\n\n");
    }

    libdir = gvconfig_libdir(gvc);

    config_re = gmalloc(strlen(plugin_re_beg) + 20 + strlen(plugin_re_end) + 1);

#if defined(WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
    sprintf(config_re,"%s%s", plugin_re_beg, plugin_re_end);
#elif defined(GVPLUGIN_VERSION)
    sprintf(config_re,"%s%d%s", plugin_re_beg, GVPLUGIN_VERSION, plugin_re_end);
#else
    sprintf(config_re,"%s[0-9]+%s", plugin_re_beg, plugin_re_end);
#endif

    if (regcomp(&re, config_re, REG_EXTENDED|REG_NOSUB) != 0) {
	agerr(AGERR,"cannot compile regular expression %s", config_re);
    }

    config_glob = gmalloc(strlen(libdir) + 1 + strlen(plugin_glob) + 1);
    strcpy(config_glob, libdir);
	strcat(config_glob, DIRSEP);
    strcat(config_glob, plugin_glob);

    /* load all libraries even if can't save config */

#if defined(WIN32)
    rc = glob(gvc, config_glob, GLOB_NOSORT, NULL, &globbuf);
#else
    rc = glob(config_glob, GLOB_NOSORT, NULL, &globbuf);
#endif
    if (rc == 0) {
	for (i = 0; i < globbuf.gl_pathc; i++) {
	    re_status = regexec(&re, globbuf.gl_pathv[i], (size_t) 0, NULL, 0);
	    if (re_status == 0) {
		library = gvplugin_library_load(gvc, globbuf.gl_pathv[i]);
		if (library) {
		    gvconfig_plugin_install_from_library(gvc, globbuf.gl_pathv[i], library);
		}
	    }
	}
	/* rescan with all libs loaded to check cross dependencies */
	for (i = 0; i < globbuf.gl_pathc; i++) {
	    re_status = regexec(&re, globbuf.gl_pathv[i], (size_t) 0, NULL, 0);
	    if (re_status == 0) {
		library = gvplugin_library_load(gvc, globbuf.gl_pathv[i]);
		if (library) {
		    path = strrchr(globbuf.gl_pathv[i],DIRSEP[0]);
		    if (path)
			path++;
		    if (f && path)
			gvconfig_write_library_config(gvc, path, library, f);
		}
	    }
	}
    }
    regfree(&re);
    globfree(&globbuf);
    free(config_glob);
    free(config_re);
    if (f)
	fclose(f);
}
示例#16
0
文件: files.c 项目: hoijui/Remind
static int SetupGlobChain(char const *dirname, IncludeStruct *i)
{
    DynamicBuffer pattern;
    char *dir;
    size_t l;
    int r;
    glob_t glob_buf;
    DirectoryFilenameChain *dc = CachedDirectoryChains;

    i->chain = NULL;
    if (!*dirname) return E_CANT_OPEN;

    dir = StrDup(dirname);
    if (!dir) return E_NO_MEM;

    /* Strip trailing slashes off directory */
    l = strlen(dir);
    while(l) {
	if (*(dir+l-1) == '/') {
	    l--;
	    *(dir+l) = 0;
	} else {
	    break;
	}
    }

    /* Repair root directory :-) */
    if (!l) {
	*dir = '/';
    }

    /* Check the cache */
    while(dc) {
	if (!strcmp(dc->dirname, dir)) {
	    if (DebugFlag & DB_TRACE_FILES) {
		fprintf(ErrFp, "Found cached directory listing for `%s'\n",
			dir);
	    }
	    free(dir);
	    i->chain = dc->chain;
	    return OK;
	}
	dc = dc->next;
    }

    if (DebugFlag & DB_TRACE_FILES) {
	fprintf(ErrFp, "Scanning directory `%s' for *.rem files\n", dir);
    }

    if (ShouldCache) {
	dc = malloc(sizeof(DirectoryFilenameChain));
	if (dc) {
	    dc->dirname = StrDup(dir);
	    if (!dc->dirname) {
		free(dc);
		dc = NULL;
	    }
	}
	if (dc) {
	    if (DebugFlag & DB_TRACE_FILES) {
		fprintf(ErrFp, "Caching directory `%s' listing\n", dir);
	    }

	    dc->chain = NULL;
	    dc->next = CachedDirectoryChains;
	    CachedDirectoryChains = dc;
	}
    }

    DBufInit(&pattern);
    DBufPuts(&pattern, dir);
    DBufPuts(&pattern, "/*.rem");
    free(dir);

    r = glob(DBufValue(&pattern), 0, NULL, &glob_buf);
    DBufFree(&pattern);

    if (r == GLOB_NOMATCH) {
	globfree(&glob_buf);
	return OK;
    }

    if (r != 0) {
	globfree(&glob_buf);
	return -1;
    }

    /* Add the files to the chain backwards to preserve sort order */
    for (r=glob_buf.gl_pathc-1; r>=0; r--) {
	FilenameChain *ch = malloc(sizeof(FilenameChain));
	if (!ch) {
	    globfree(&glob_buf);
	    FreeChain(i->chain);
	    i->chain = NULL;
	    return E_NO_MEM;
	}

	/* TODO: stat the file and only add if it's a plain file and
	   readable by us */
	ch->filename = StrDup(glob_buf.gl_pathv[r]);
	if (!ch->filename) {
	    globfree(&glob_buf);
	    FreeChain(i->chain);
	    i->chain = NULL;
	    free(ch);
	    return E_NO_MEM;
	}
	ch->next = i->chain;
	i->chain = ch;
    }
    if (dc) {
	dc->chain = i->chain;
    }

    globfree(&glob_buf);
    return OK;
}
示例#17
0
文件: Dir.cpp 项目: Chris-Hood/mpc-hc
ZtringList Dir::GetAllFileNames(const Ztring &Dir_Name_, dirlist_t Options)
{
    ZtringList ToReturn;
    Ztring Dir_Name=Dir_Name_;

    #ifdef ZENLIB_USEWX
        int Flags=wxDIR_FILES | wxDIR_DIRS;

        //Search for files
        wxArrayString Liste;
        wxFileName FullPath; FullPath=Dir_Name.c_str();
        //-File
        if (FullPath.FileExists())
        {
            FullPath.Normalize();
            Liste.Add(FullPath.GetFullPath());
        }
        //-Directory
        else if (FullPath.DirExists())
        {
            FullPath.Normalize();
            wxDir::GetAllFiles(FullPath.GetFullPath(), &Liste, Ztring(), Flags);
        }
        //-WildCards
        else
        {
            wxString FileName=FullPath.GetFullName();
            FullPath.SetFullName(Ztring()); //Supress filename
            FullPath.Normalize();
            if (FullPath.DirExists())
                wxDir::GetAllFiles(FullPath.GetPath(), &Liste, FileName, Flags);
        }

        //Compatible array
        ToReturn.reserve(Liste.GetCount());
        for (size_t Pos=0; Pos<Liste.GetCount(); Pos++)
            ToReturn.push_back(Liste[Pos].c_str());
    #else //ZENLIB_USEWX
        #ifdef WINDOWS
            //Is a dir?
            if (Exists(Dir_Name))
                Dir_Name+=__T("\\*");

            //Path
            Ztring Path=FileName::Path_Get(Dir_Name);
            if (Path.empty())
            {
                #ifdef UNICODE
                    #ifndef ZENLIB_NO_WIN9X_SUPPORT
                    if (IsWin9X_Fast())
                    {
                        DWORD Path_Size=GetFullPathNameA(Dir_Name.To_Local().c_str(), 0, NULL, NULL);
                        char* PathTemp=new char[Path_Size+1];
                        if (GetFullPathNameA(Dir_Name.To_Local().c_str(), Path_Size+1, PathTemp, NULL))
                            Path=FileName::Path_Get(PathTemp);
                        delete [] PathTemp; //PathTemp=NULL;
                    }
                    else
                    #endif //ZENLIB_NO_WIN9X_SUPPORT
                    {
                        DWORD Path_Size=GetFullPathName(Dir_Name.c_str(), 0, NULL, NULL);
                        Char* PathTemp=new Char[Path_Size+1];
                        if (GetFullPathNameW(Dir_Name.c_str(), Path_Size+1, PathTemp, NULL))
                            Path=FileName::Path_Get(PathTemp);
                        delete [] PathTemp; //PathTemp=NULL;
                    }
                #else
                    DWORD Path_Size=GetFullPathName(Dir_Name.c_str(), 0, NULL, NULL);
                    Char* PathTemp=new Char[Path_Size+1];
                    if (GetFullPathName(Dir_Name.c_str(), Path_Size+1, PathTemp, NULL))
                        Path=FileName::Path_Get(PathTemp);
                    delete [] PathTemp; //PathTemp=NULL;
                #endif //UNICODE
            }

            #ifdef UNICODE
                WIN32_FIND_DATAW FindFileDataW;
                HANDLE hFind;
                #ifndef ZENLIB_NO_WIN9X_SUPPORT
                WIN32_FIND_DATAA FindFileDataA;
                if (IsWin9X_Fast())
                    hFind=FindFirstFileA(Dir_Name.To_Local().c_str(), &FindFileDataA);
                else
                #endif //ZENLIB_NO_WIN9X_SUPPORT
                    hFind=FindFirstFileW(Dir_Name.c_str(), &FindFileDataW);
            #else
                WIN32_FIND_DATA FindFileData;
                HANDLE hFind=FindFirstFile(Dir_Name.c_str(), &FindFileData);
            #endif //UNICODE

            if (hFind==INVALID_HANDLE_VALUE)
                return ZtringList();

            BOOL ReturnValue;
            do
            {
                #ifdef UNICODE
                    Ztring File_Name;
                    #ifndef ZENLIB_NO_WIN9X_SUPPORT
                    if (IsWin9X_Fast())
                        File_Name=FindFileDataA.cFileName;
                    else
                    #endif //ZENLIB_NO_WIN9X_SUPPORT
                        File_Name=FindFileDataW.cFileName;
                #else
                    Ztring File_Name(FindFileData.cFileName);
                #endif //UNICODE
                if (File_Name!=__T(".") && File_Name!=__T("..")) //Avoid . an ..
                {
                    Ztring File_Name_Complete=Path+__T("\\")+File_Name;
                    if (Exists(File_Name_Complete))
                    {
                        if (Options&Include_Dirs)
                            ToReturn.push_back(File_Name_Complete); //A dir
                        if (Options&Parse_SubDirs)
                            ToReturn+=GetAllFileNames(File_Name_Complete, Options); //A SubDir
                    }
                    else if ((Options&Include_Files) && ((Options&Include_Hidden) || (!File_Name.empty() && File_Name[0]!=__T('.'))))
                        ToReturn.push_back(File_Name_Complete); //A file
                }
                #ifdef UNICODE
                    #ifndef ZENLIB_NO_WIN9X_SUPPORT
                    if (IsWin9X_Fast())
                        ReturnValue=FindNextFileA(hFind, &FindFileDataA);
                    else
                    #endif //ZENLIB_NO_WIN9X_SUPPORT
                        ReturnValue=FindNextFileW(hFind, &FindFileDataW);
                #else
                    ReturnValue=FindNextFile(hFind, &FindFileData);
                #endif //UNICODE
            }
            while (ReturnValue);

            FindClose(hFind);
        #else //WINDOWS
            //A file?
            if (File::Exists(Dir_Name))
            {
               ToReturn.push_back(Dir_Name); //TODO
               return ToReturn;
            }

            //A dir?
            if (!Dir::Exists(Dir_Name))
                return ToReturn; //Does not exist

            //open
            #ifdef UNICODE
                DIR* Dir=opendir(Dir_Name.To_Local().c_str());
            #else
                DIR* Dir=opendir(Dir_Name.c_str());
            #endif //UNICODE
            if (Dir)
            {
                //This is a dir
                //Normalizing dir (the / at the end)
                size_t Dir_Pos=Dir_Name.rfind(FileName_PathSeparator);
                if (Dir_Pos==std::string::npos)
                    Dir_Name+=FileName_PathSeparator;
                else if (Dir_Pos+Ztring(FileName_PathSeparator).size()!=Dir_Name.size())
                    Dir_Name+=FileName_PathSeparator;

                struct dirent *DirEnt;
                while((DirEnt=readdir(Dir))!=NULL)
                {
                    //A file
                    Ztring File_Name(DirEnt->d_name);
                    if (File_Name!=__T(".") && File_Name!=__T("..")) //Avoid . an ..
                    {
                        Ztring File_Name_Complete=Dir_Name+File_Name;
                        if (Exists(File_Name_Complete))
                        {
                            if (Options&Parse_SubDirs)
                                ToReturn+=GetAllFileNames(File_Name_Complete, Options); //A SubDir
                        }
                        else if ((Options&Include_Hidden) || (!File_Name.empty() && File_Name[0]!=__T('.')))
                            ToReturn.push_back(File_Name_Complete); //A file
                    }
                }

                //Close it
                closedir(Dir);
            }
            else
            {
                glob_t globbuf;
                if (glob(Dir_Name.To_Local().c_str(), GLOB_NOSORT, NULL, &globbuf)==0)
                {
                    for (int Pos=0; Pos<globbuf.gl_pathc; Pos++)
                        ToReturn.push_back(Ztring().From_Local(globbuf.gl_pathv[Pos]));
                }
            }
        #endif
    #endif //ZENLIB_USEWX

    return ToReturn;
}
示例#18
0
int main(int argc, char **argv) {
  /*
   *   chilli_query [ -s <unix-socket> ] <command> [<argument>]
   *   (or maybe this should get the unix-socket from the config file)
   */

#ifdef HAVE_GLOB
  char *cmdsock = DEFSTATEDIR"/chilli*.sock";
  glob_t globbuf;
  int i;
#else
  char *cmdsock = DEFSTATEDIR"/chilli.sock";
#endif
  int s;
  int cmdsockport = 0;
  struct sockaddr_un remote;
  char *cmd;
  int argidx = 1;
  int len;

  struct itimerval itval;

#ifdef ENABLE_CLUSTER
  int peerid = -1;
#endif

  int query_timeout = QUERY_TIMEOUT;

  if (getenv("QUERY_TIMEOUT")) {
    query_timeout = atoi(getenv("QUERY_TIMEOUT"));
  }

  set_signal(SIGALRM, timeout_alarm);

  memset(&itval, 0, sizeof(itval));
  itval.it_interval.tv_sec = query_timeout;
  itval.it_interval.tv_usec = 0;
  itval.it_value.tv_sec = query_timeout;
  itval.it_value.tv_usec = 0;

  if (setitimer(ITIMER_REAL, &itval, NULL)) {
    syslog(LOG_ERR, "%s: setitimer() failed!", strerror(errno));
  }

  if (argc < 2) return usage(argv[0]);

  if (*argv[argidx] == '/') {
    /* for backward support, ignore a unix-socket given as first arg */
    if (argc < 3) return usage(argv[0]);
    cmdsock = argv[argidx++];
  }

  memset(&request,0,sizeof(request));

  while (argidx < argc && *argv[argidx] == '-') {
    if (!strcmp(argv[argidx], "-s")) {
      argidx++;
      if (argidx >= argc) return usage(argv[0]);
      cmdsock = argv[argidx++];
#ifdef ENABLE_CLUSTER
    } else if (!strcmp(argv[argidx], "-p")) {
      argidx++;
      if (argidx >= argc) return usage(argv[0]);
      peerid = atoi(argv[argidx++]);
#endif
    } else if (!strcmp(argv[argidx], "-json")) {
      request.options |= CMDSOCK_OPT_JSON;
      argidx++;
    } else if (!strcmp(argv[argidx], "-P")) {
      argidx++;
      if (argidx >= argc) return usage(argv[0]);
      cmdsockport = atoi(argv[argidx++]);
    }
  }

  if (argidx >= argc) return usage(argv[0]);

  cmd = argv[argidx++];
  for (s = 0; commands[s].command; s++) {
    if (!strcmp(cmd, commands[s].command)) {
      request.type = commands[s].type;

      switch(request.type) {

#ifdef ENABLE_INSPECT
        case CMDSOCK_INSPECT:
#endif
#if defined(ENABLE_LOCATION) && defined(HAVE_AVL)
        case CMDSOCK_LISTLOC:
        case CMDSOCK_LISTLOCSUM:
#endif
        case CMDSOCK_LIST:
        case CMDSOCK_LOGIN:
        case CMDSOCK_LOGOUT:
        case CMDSOCK_UPDATE:
        case CMDSOCK_AUTHORIZE:
        case CMDSOCK_ADD_GARDEN:
        case CMDSOCK_REM_GARDEN:
          argidx = process_args(argc, argv, argidx);
          if (request.type != CMDSOCK_LOGOUT || argidx >= argc)
            break;
          /* else, drop through */
        case CMDSOCK_DHCP_DROP:
        case CMDSOCK_DHCP_RELEASE:
          {
            if (argc < argidx+1) {
              fprintf(stderr, "%s requires a MAC address argument\n", cmd);
              return usage(argv[0]);
            }

            if (parse_mac(request.mac, argv[argidx]))
              return usage(argv[0]);

            /* do another switch to pick up param configs for authorize */
          }
          break;
#ifdef ENABLE_MULTIROUTE
        case CMDSOCK_ROUTE:
        case CMDSOCK_ROUTE_GW:
          {
            unsigned int temp[PKT_ETH_ALEN];
            char macstr[RADIUS_ATTR_VLEN];
            int macstrlen;
            int i;

            if (argc < argidx + 2) {
              break;
            }

            if ((macstrlen = strlen(argv[argidx])) >= (RADIUS_ATTR_VLEN-1)) {
              fprintf(stderr, "%s: bad MAC address\n", argv[argidx]);
              break;
            }

            memcpy(macstr, argv[argidx], macstrlen);
            macstr[macstrlen] = 0;

            for (i=0; i<macstrlen; i++)
              if (!isxdigit((int) macstr[i]))
                macstr[i] = 0x20;

            if (sscanf(macstr, "%2x %2x %2x %2x %2x %2x",
                       &temp[0], &temp[1], &temp[2],
                       &temp[3], &temp[4], &temp[5]) != 6) {
              fprintf(stderr, "%s: bad MAC address\n", argv[argidx]);
              break;
            }

            for (i = 0; i < PKT_ETH_ALEN; i++)
              request.mac[i] = temp[i];

            argidx++;
            request.d.sess.params.routeidx = atoi(argv[argidx]);

            if (request.type != CMDSOCK_ROUTE_GW)
              request.type = CMDSOCK_ROUTE_SET;

            /* do another switch to pick up param configs for authorize */
          }
          break;
#endif
      }
      break;
    }
  }

  if (!commands[s].command) {
    fprintf(stderr,"unknown command: %s\n",cmd);
    exit(1);
  }

#ifdef ENABLE_CLUSTER
  if (peerid > -1) {

    struct sockaddr_in s;
    int blen = sizeof(struct pkt_chillihdr_t);
    uint8_t b[blen];

    int fd = socket(AF_INET, SOCK_DGRAM, 0);

    printf("blen %d\n", blen);

    if (fd < 0) {
      syslog(LOG_ERR, "%s: socket() failed", strerror(errno));
      exit(1);
    }

    memset(&s, 0, sizeof(struct sockaddr_in));
    s.sin_family = AF_INET;
    s.sin_port = htons(10203);
    s.sin_addr.s_addr = htonl(INADDR_BROADCAST);

    (void) safe_sendto(fd, b, blen, 0,
		       (struct sockaddr *)&s,
		       sizeof(struct sockaddr_in));

    return 0;
  }
#endif

  if (cmdsockport) {
    struct sockaddr_in remote_port;
    struct in_addr addr;

    if ((s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
      perror("socket");
      exit(1);
    }

    inet_aton("127.0.0.1", &addr);
    memset(&remote_port, 0, sizeof(struct sockaddr_in));
    remote_port.sin_family = AF_INET;
    remote_port.sin_port = htons(cmdsockport);
    remote_port.sin_addr.s_addr = addr.s_addr;

    if (connect(s, (struct sockaddr *)&remote_port, sizeof(remote_port)) == -1) {
      perror("connect");
      exit(1);
    }

    if (chilli_communicate(s, &request, sizeof(request)) != 0) {
      perror("write");
      exit(1);
    }

    shutdown(s, 2);
    close(s);

    return 0;
  }

#ifdef HAVE_GLOB
  globbuf.gl_offs = 0;
  glob(cmdsock, GLOB_DOOFFS, NULL, &globbuf);

  if (!globbuf.gl_pathc) {
    fprintf(stderr,"no cmdsock sockets: %s\n",cmdsock);
    exit(1);
  }

  for (i=0 ; i < globbuf.gl_pathc; i++) {
    cmdsock = globbuf.gl_pathv[i];
    if (globbuf.gl_pathc>1) {
      char header[256];
      int headerlen;
      safe_snprintf(header, sizeof(header), "\nQuerying socket %s\n", cmdsock);
      headerlen=strlen(header);
      if (write(1, header, strlen(header))!=headerlen) {
        perror("write");
        exit(1);
      }
    }
#endif

    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
      perror("socket");
      exit(1);
    }

    remote.sun_family = AF_UNIX;
    strcpy(remote.sun_path, cmdsock);

#if defined (__FreeBSD__)  || defined (__APPLE__) || defined (__OpenBSD__)
    remote.sun_len = strlen(remote.sun_path) + 1;
#endif

    len = offsetof(struct sockaddr_un, sun_path) + strlen(remote.sun_path);

    if (connect(s, (struct sockaddr *)&remote, len) == -1) {
      perror("connect");
      exit(1);
    }

    if (chilli_communicate(s, &request, sizeof(request)) != 0) {
      perror("write");
      exit(1);
    }

    shutdown(s, 2);
    close(s);

#ifdef HAVE_GLOB
  }
  globfree(&globbuf);
#endif

  return 0;
}
示例#19
0
文件: spe_autocomp.c 项目: Fusiow/msh
static int			make_glob_list(char *cmd, glob_t *list)
{
	glob(ft_strjoin(cmd, "*"), GLOB_NOCHECK, 0, list);
	return (1);
}
示例#20
0
文件: emperor.c 项目: ahua/c
// this is the monitor for glob patterns
void uwsgi_imperial_monitor_glob(struct uwsgi_emperor_scanner *ues) {

	glob_t g;
	int i;
	struct stat st;
	struct uwsgi_instance *ui_current;

	if (glob(ues->arg, GLOB_MARK | GLOB_NOCHECK, NULL, &g)) {
		uwsgi_error("glob()");
		return;
	}

	for (i = 0; i < (int) g.gl_pathc; i++) {

		if (!uwsgi_emperor_is_valid(g.gl_pathv[i]))
			continue;

		if (stat(g.gl_pathv[i], &st))
			continue;

		if (!S_ISREG(st.st_mode))
			continue;

		ui_current = emperor_get(g.gl_pathv[i]);

		uid_t t_uid = st.st_uid;
                gid_t t_gid = st.st_gid;

                if (uwsgi.emperor_tyrant && uwsgi.emperor_tyrant_nofollow) {
                        struct stat lst;
                        if (lstat(g.gl_pathv[i], &lst)) {
                                uwsgi_error("[emperor-tyrant]/lstat()");
                                if (ui_current) {
                                        uwsgi_log("!!! availability of file %s changed. stopping the instance... !!!\n", g.gl_pathv[i]);
                                        emperor_stop(ui_current);
                                }
                                continue;
                        }
                        t_uid = lst.st_uid;
                        t_gid = lst.st_gid;
                }

		if (ui_current) {
			// check if uid or gid are changed, in such case, stop the instance
			if (uwsgi.emperor_tyrant) {
				if (t_uid != ui_current->uid || t_gid != ui_current->gid) {
					uwsgi_log("!!! permissions of file %s changed. stopping the instance... !!!\n", g.gl_pathv[i]);
					emperor_stop(ui_current);
					continue;
				}
			}
			// check if mtime is changed and the uWSGI instance must be reloaded
			if (st.st_mtime > ui_current->last_mod) {
				emperor_respawn(ui_current, st.st_mtime);
			}
		}
		else {
			char *socket_name = emperor_check_on_demand_socket(g.gl_pathv[i]);
			emperor_add(ues, g.gl_pathv[i], st.st_mtime, NULL, 0, t_uid, t_gid, socket_name);
			if (socket_name) free(socket_name);
		}

	}
	globfree(&g);

	// now check for removed instances
	struct uwsgi_instance *c_ui = ui->ui_next;

	while (c_ui) {
		if (c_ui->scanner == ues) {
			if (c_ui->zerg) {
                                char *colon = strrchr(c_ui->name, ':');
                                if (!colon) {
                                        emperor_stop(c_ui);
                                }
                                else {
                                        char *filename = uwsgi_calloc(0xff);
                                        memcpy(filename, c_ui->name, colon - c_ui->name);
                                        if (stat(filename, &st)) {
                                                emperor_stop(c_ui);
                                        }
                                        free(filename);
                                }
                        }
                        else {
                                if (stat(c_ui->name, &st)) { 
                                        emperor_stop(c_ui);
                                }       
                        }
		}
		c_ui = c_ui->ui_next;
	}


}
示例#21
0
文件: image.c 项目: jcsogo/darktable
uint32_t dt_image_import(const int32_t film_id, const char *filename, gboolean override_ignore_jpegs)
{
  if(!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
    return 0;
  const char *cc = filename + strlen(filename);
  for(; *cc!='.'&&cc>filename; cc--);
  if(!strcmp(cc, ".dt")) return 0;
  if(!strcmp(cc, ".dttags")) return 0;
  if(!strcmp(cc, ".xmp")) return 0;
  char *ext = g_ascii_strdown(cc+1, -1);
  if(override_ignore_jpegs == FALSE && (!strcmp(ext, "jpg") ||
                                        !strcmp(ext, "jpeg")) && dt_conf_get_bool("ui_last/import_ignore_jpegs"))
    return 0;
  int supported = 0;
  char **extensions = g_strsplit(dt_supported_extensions, ",", 100);
  for(char **i=extensions; *i!=NULL; i++)
    if(!strcmp(ext, *i))
    {
      supported = 1;
      break;
    }
  g_strfreev(extensions);
  if(!supported)
  {
    g_free(ext);
    return 0;
  }
  int rc;
  uint32_t id = 0;
  // select from images; if found => return
  gchar *imgfname;
  imgfname = g_path_get_basename((const gchar*)filename);
  sqlite3_stmt *stmt;
  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db),
                              "select id from images where film_id = ?1 and filename = ?2",
                              -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, film_id);
  DT_DEBUG_SQLITE3_BIND_TEXT(stmt, 2, imgfname, strlen(imgfname), SQLITE_STATIC);
  if(sqlite3_step(stmt) == SQLITE_ROW)
  {
    id = sqlite3_column_int(stmt, 0);
    g_free(imgfname);
    sqlite3_finalize(stmt);
    g_free(ext);
    const dt_image_t *cimg = dt_image_cache_read_get(darktable.image_cache, id);
    dt_image_t *img = dt_image_cache_write_get(darktable.image_cache, cimg);
    img->flags &= ~DT_IMAGE_REMOVE;
    dt_image_cache_write_release(darktable.image_cache, img, DT_IMAGE_CACHE_RELAXED);
    dt_image_cache_read_release(darktable.image_cache, img);
    return id;
  }
  sqlite3_finalize(stmt);

  // also need to set the no-legacy bit, to make sure we get the right presets (new ones)
  uint32_t flags = dt_conf_get_int("ui_last/import_initial_rating");
  if(flags > 5)
  {
    flags = 1;
    dt_conf_set_int("ui_last/import_initial_rating", 1);
  }
  flags |= DT_IMAGE_NO_LEGACY_PRESETS;
  // insert dummy image entry in database
  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db),
                              "insert into images (id, film_id, filename, caption, description, "
                              "license, sha1sum, flags) values (null, ?1, ?2, '', '', '', '', ?3)",
                              -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, film_id);
  DT_DEBUG_SQLITE3_BIND_TEXT(stmt, 2, imgfname, strlen(imgfname),
                             SQLITE_TRANSIENT);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 3, flags);
  rc = sqlite3_step(stmt);
  if (rc != SQLITE_DONE) fprintf(stderr, "sqlite3 error %d\n", rc);
  sqlite3_finalize(stmt);

  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db),
                              "select id from images where film_id = ?1 and filename = ?2",
                              -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, film_id);
  DT_DEBUG_SQLITE3_BIND_TEXT(stmt, 2, imgfname, strlen(imgfname),
                             SQLITE_STATIC);
  if(sqlite3_step(stmt) == SQLITE_ROW) id = sqlite3_column_int(stmt, 0);
  sqlite3_finalize(stmt);

  // Try to find out if this should be grouped already.
  gchar *basename = g_strdup(imgfname);
  gchar *cc2 = basename + strlen(basename);
  for(; *cc2!='.'&&cc2>basename; cc2--);
  *cc2='\0';
  gchar *sql_pattern = g_strconcat(basename, ".%", NULL);
  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select group_id from images where film_id = ?1 and filename like ?2 and id != ?3", -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, film_id);
  DT_DEBUG_SQLITE3_BIND_TEXT(stmt, 2, sql_pattern, -1, SQLITE_TRANSIENT);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 3, id);
  int group_id;
  if(sqlite3_step(stmt) == SQLITE_ROW) group_id = sqlite3_column_int(stmt, 0);
  else                                 group_id = id;
  sqlite3_finalize(stmt);
  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "update images set group_id = ?1 where id = ?2", -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, group_id);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 2, id);
  sqlite3_step(stmt);
  sqlite3_finalize(stmt);

  // printf("[image_import] importing `%s' to img id %d\n", imgfname, id);

  // lock as shortly as possible:
  const dt_image_t *cimg = dt_image_cache_read_get(darktable.image_cache, id);
  dt_image_t *img = dt_image_cache_write_get(darktable.image_cache, cimg);
  img->group_id = group_id;

  // read dttags and exif for database queries!
  (void) dt_exif_read(img, filename);
  char dtfilename[DT_MAX_PATH_LEN];
  g_strlcpy(dtfilename, filename, DT_MAX_PATH_LEN);
  dt_image_path_append_version(id, dtfilename, DT_MAX_PATH_LEN);
  char *c = dtfilename + strlen(dtfilename);
  sprintf(c, ".xmp");
  (void)dt_exif_xmp_read(img, dtfilename, 0);

  // write through to db, but not to xmp.
  dt_image_cache_write_release(darktable.image_cache, img, DT_IMAGE_CACHE_RELAXED);
  dt_image_cache_read_release(darktable.image_cache, img);

  // add a tag with the file extension
  guint tagid = 0;
  char tagname[512];
  snprintf(tagname, 512, "darktable|format|%s", ext);
  g_free(ext);
  dt_tag_new(tagname, &tagid);
  dt_tag_attach(tagid,id);

  // Search for sidecar files and import them if found.
  glob_t *globbuf = g_malloc(sizeof(glob_t));

  // Add version wildcard
  gchar *fname = g_strdup(filename);
  gchar pattern[DT_MAX_PATH_LEN];
  g_snprintf(pattern, DT_MAX_PATH_LEN, "%s", filename);
  char *c1 = pattern + strlen(pattern);
  while(*c1 != '.' && c1 > pattern) c1--;
  snprintf(c1, pattern + DT_MAX_PATH_LEN - c1, "_*");
  char *c2 = fname + strlen(fname);
  while(*c2 != '.' && c2 > fname) c2--;
  snprintf(c1+2, pattern + DT_MAX_PATH_LEN - c1 - 2, "%s.xmp", c2);

  if (!glob(pattern, 0, NULL, globbuf))
  {
    for (int i=0; i < globbuf->gl_pathc; i++)
    {
      int newid = -1;
      newid = dt_image_duplicate(id);

      const dt_image_t *cimg = dt_image_cache_read_get(darktable.image_cache, newid);
      dt_image_t *img = dt_image_cache_write_get(darktable.image_cache, cimg);
      (void)dt_exif_xmp_read(img, globbuf->gl_pathv[i], 0);
      dt_image_cache_write_release(darktable.image_cache, img, DT_IMAGE_CACHE_RELAXED);
      dt_image_cache_read_release(darktable.image_cache, img);
    }
    globfree(globbuf);
  }

  g_free(imgfname);
  g_free(fname);
  g_free(basename);
  g_free(sql_pattern);
  g_free(globbuf);

  dt_control_signal_raise(darktable.signals,DT_SIGNAL_IMAGE_IMPORT,id);
  return id;
}
示例#22
0
int main(int argc, char* argv[])
{
	IBNibRef nibRef;
	OSStatus err;
	glob_t g;
    
	// check the correct BASS was loaded
	if (HIWORD(BASS_GetVersion())!=BASSVERSION) {
		Error("An incorrect version of BASS was loaded");
		return 0;
	}

	// initialize default output device
	if (!BASS_Init(-1,44100,0,NULL,NULL)) {
		Error("Can't initialize device");
		return 0;
	}

	// Create Window and stuff
	err = CreateNibReference(CFSTR("plugins"), &nibRef);
	if (err) return err;
	err = CreateWindowFromNib(nibRef, CFSTR("Window"), &win);
	if (err) return err;
	DisposeNibReference(nibRef);

	DataBrowserCallbacks dbc;
	dbc.version=kDataBrowserLatestCallbacks;
	InitDataBrowserCallbacks(&dbc);
	dbc.u.v1.itemDataCallback=MyDataBrowserItemDataCallback;
	ControlRef list=GetControl(20);
	SetDataBrowserCallbacks(list,&dbc);

	{ // look for plugins (in the executable directory)
		char path[300];
		DWORD l=sizeof(path);
		_NSGetExecutablePath(path,&l);
		strcpy(strrchr(path,'/')+1,"libbass*.dylib");
		if (!glob(path,0,0,&g)) {
			int a;
			for (a=0;a<g.gl_pathc;a++) {
				if (BASS_PluginLoad(g.gl_pathv[a],0)) { // plugin loaded,  add it to the list...
					char *p=strrchr(g.gl_pathv[a],'/')+1;
					AddDataBrowserItems(list,kDataBrowserNoItem,1,(DataBrowserItemID*)&p,kDataBrowserItemNoProperty);
				}
			}
		}
		DWORD c;
		GetDataBrowserItemCount(list,kDataBrowserNoItem,FALSE,kDataBrowserItemNoState,(DataBrowserItemState*)&c);
		if (!c) { // no plugins...
			static const char *noplugins="no plugins - visit the BASS webpage to get some";
			AddDataBrowserItems(list,kDataBrowserNoItem,1,(DataBrowserItemID*)&noplugins,kDataBrowserItemNoProperty);
		}
	}

	SetupControlHandler(10,kEventControlHit,OpenEventHandler);
	SetControlAction(GetControl(12),NewControlActionUPP(PosEventHandler));

	EventLoopTimerRef timer;
	InstallEventLoopTimer(GetCurrentEventLoop(),kEventDurationNoWait,kEventDurationSecond/2,NewEventLoopTimerUPP(TimerProc),0,&timer);

	ShowWindow(win);
	RunApplicationEventLoop();

	globfree(&g);

	// "free" the output device and all plugins
	BASS_Free();
	BASS_PluginFree(0);

    return 0; 
}
示例#23
0
文件: ini.c 项目: 7799/pacman
/**
 * @brief INI parser backend.
 *
 * @param file path to the config file
 * @param cb callback for key/value pairs
 * @param data caller defined data to be passed to the callback
 * @param section_name the name of the current section
 * @param line buffer to read into, must be at least PATH_MAX long
 * @param depth recursion depth, should initially be 0
 *
 * @return 0 on success, 1 on parsing errors, the callback return value
 * otherwise
 */
static int _parse_ini(const char *file, ini_parser_fn cb, void *data,
		char **section_name, char *line, int depth)
{
	FILE *fp = NULL;
	int linenum = 0;
	int ret = 0;

	if(depth >= ini_max_recursion) {
		pm_printf(ALPM_LOG_ERROR,
				_("config parsing exceeded max recursion depth of %d.\n"),
				ini_max_recursion);
		ret = 1;
		goto cleanup;
	}

	pm_printf(ALPM_LOG_DEBUG, "config: attempting to read file %s\n", file);
	fp = fopen(file, "r");
	if(fp == NULL) {
		pm_printf(ALPM_LOG_ERROR, _("config file %s could not be read: %s\n"),
				file, strerror(errno));
		ret = 1;
		goto cleanup;
	}

	while(fgets(line, PATH_MAX, fp)) {
		char *key, *value, *ptr;
		size_t line_len;

		linenum++;

		/* ignore whole line and end of line comments */
		if((ptr = strchr(line, '#'))) {
			*ptr = '\0';
		}

		line_len = strtrim(line);

		if(line_len == 0) {
			continue;
		}

		if(line[0] == '[' && line[line_len - 1] == ']') {
			char *name;
			/* only possibility here is a line == '[]' */
			if(line_len <= 2) {
				pm_printf(ALPM_LOG_ERROR, _("config file %s, line %d: bad section name.\n"),
						file, linenum);
				ret = 1;
				goto cleanup;
			}
			/* new config section, skip the '[' */
			name = strdup(line + 1);
			name[line_len - 2] = '\0';

			ret = cb(file, linenum, name, NULL, NULL, data);
			free(*section_name);
			*section_name = name;

			/* we're at a new section; perform any post-actions for the prior */
			if(ret) {
				goto cleanup;
			}
			continue;
		}

		/* directive */
		/* strsep modifies the 'line' string: 'key \0 value' */
		key = line;
		value = line;
		strsep(&value, "=");
		strtrim(key);
		strtrim(value);

		if(key == NULL) {
			pm_printf(ALPM_LOG_ERROR, _("config file %s, line %d: syntax error in config file- missing key.\n"),
					file, linenum);
			ret = 1;
			goto cleanup;
		}
		/* Include is allowed in both options and repo sections */
		if(strcmp(key, "Include") == 0) {
			glob_t globbuf;
			int globret;
			size_t gindex;

			if(value == NULL) {
				pm_printf(ALPM_LOG_ERROR, _("config file %s, line %d: directive '%s' needs a value\n"),
						file, linenum, key);
				ret = 1;
				goto cleanup;
			}
			/* Ignore include failures... assume non-critical */
			globret = glob(value, GLOB_NOCHECK, NULL, &globbuf);
			switch(globret) {
				case GLOB_NOSPACE:
					pm_printf(ALPM_LOG_DEBUG,
							"config file %s, line %d: include globbing out of space\n",
							file, linenum);
					break;
				case GLOB_ABORTED:
					pm_printf(ALPM_LOG_DEBUG,
							"config file %s, line %d: include globbing read error for %s\n",
							file, linenum, value);
					break;
				case GLOB_NOMATCH:
					pm_printf(ALPM_LOG_DEBUG,
							"config file %s, line %d: no include found for %s\n",
							file, linenum, value);
					break;
				default:
					for(gindex = 0; gindex < globbuf.gl_pathc; gindex++) {
						pm_printf(ALPM_LOG_DEBUG, "config file %s, line %d: including %s\n",
								file, linenum, globbuf.gl_pathv[gindex]);
						ret =_parse_ini(globbuf.gl_pathv[gindex], cb, data,
								section_name, line, depth + 1);
						if(ret) {
							globfree(&globbuf);
							goto cleanup;
						}
					}
					break;
			}
			globfree(&globbuf);
			continue;
		}
		if((ret = cb(file, linenum, *section_name, key, value, data)) != 0) {
			goto cleanup;
		}
	}

	if(depth == 0) {
		ret = cb(NULL, 0, NULL, NULL, NULL, data);
	}

cleanup:
	if(fp) {
		fclose(fp);
	}
	if(depth == 0) {
		free(*section_name);
		*section_name = NULL;
	}
	pm_printf(ALPM_LOG_DEBUG, "config: finished parsing %s\n", file);
	return ret;
}
mf_t* open_mf(char * filename){
#if defined(HAVE_GLOB) || defined(__MINGW32__)
 glob_t        gg;
 struct stat   fs;
 int           i;
 char        * fname;
 mf_t        * mf;
 int           error_count = 0;
 int	       count = 0;

 mf=calloc( 1,sizeof( mf_t ) );

 if( filename[0] == '@' )
  {
   FILE *lst_f=fopen(filename + 1,"r");
   if ( lst_f )
    {
     fname=malloc(PATH_MAX);
     while ( fgets( fname,PATH_MAX,lst_f ) )
      {
       /* remove spaces from end of fname */
       char *t=fname + strlen( fname ) - 1;
       while ( t > fname && isspace( *t ) ) *(t--)=0;
       if ( stat( fname,&fs ) )
        {
         mp_msg( MSGT_STREAM,MSGL_V,"[mf] file not found: '%s'\n",fname );
        }
        else
        {
         mf->names=realloc( mf->names,( mf->nr_of_files + 1 ) * sizeof( char* ) );
         mf->names[mf->nr_of_files]=strdup( fname );
         mf->nr_of_files++;
        }
      }
      fclose( lst_f );

      mp_msg( MSGT_STREAM,MSGL_INFO,"[mf] number of files: %d\n",mf->nr_of_files );
      goto exit_mf;
    }
    mp_msg( MSGT_STREAM,MSGL_INFO,"[mf] %s is not indirect filelist\n",filename+1 );
  }

 if( strchr( filename,',') )
  {
   mp_msg( MSGT_STREAM,MSGL_INFO,"[mf] filelist: %s\n",filename );

   while ( ( fname=strsep( &filename,"," ) ) )
    {
     if ( stat( fname,&fs ) )
      {
       mp_msg( MSGT_STREAM,MSGL_V,"[mf] file not found: '%s'\n",fname );
      }
      else
      {
       mf->names=realloc( mf->names,( mf->nr_of_files + 1 ) * sizeof( char* ) );
       mf->names[mf->nr_of_files]=strdup( fname );
//       mp_msg( MSGT_STREAM,MSGL_V,"[mf] added file %d.: %s\n",mf->nr_of_files,mf->names[mf->nr_of_files] );
       mf->nr_of_files++;
      }
    }
   mp_msg( MSGT_STREAM,MSGL_INFO,"[mf] number of files: %d\n",mf->nr_of_files );

   goto exit_mf;
  }

 fname=malloc( strlen( filename ) + 32 );

 if ( !strchr( filename,'%' ) )
  {
   strcpy( fname,filename );
   if ( !strchr( filename,'*' ) ) strcat( fname,"*" );

   mp_msg( MSGT_STREAM,MSGL_INFO,"[mf] search expr: %s\n",fname );

   if ( glob( fname,0,NULL,&gg ) )
    { free( mf ); free( fname ); return NULL; }

   mf->nr_of_files=gg.gl_pathc;
   mf->names=calloc( gg.gl_pathc, sizeof( char* ) );

   mp_msg( MSGT_STREAM, MSGL_INFO, "[mf] number of files: %d (%zu)\n", mf->nr_of_files, gg.gl_pathc * sizeof( char* ) );

   for( i=0;i < gg.gl_pathc;i++ )
    {
     stat( gg.gl_pathv[i],&fs );
     if( S_ISDIR( fs.st_mode ) ) continue;
     mf->names[i]=strdup( gg.gl_pathv[i] );
//     mp_msg( MSGT_STREAM,MSGL_DBG2,"[mf] added file %d.: %s\n",i,mf->names[i] );
    }
   globfree( &gg );
   goto exit_mf;
  }

 mp_msg( MSGT_STREAM,MSGL_INFO,"[mf] search expr: %s\n",filename );

 while ( error_count < 5 )
  {
   sprintf( fname,filename,count++ );
   if ( stat( fname,&fs ) )
    {
     error_count++;
     mp_msg( MSGT_STREAM,MSGL_V,"[mf] file not found: '%s'\n",fname );
    }
    else
    {
     mf->names=realloc( mf->names,( mf->nr_of_files + 1 ) * sizeof( char* ) );
     mf->names[mf->nr_of_files]=strdup( fname );
//     mp_msg( MSGT_STREAM,MSGL_V,"[mf] added file %d.: %s\n",mf->nr_of_files,mf->names[mf->nr_of_files] );
     mf->nr_of_files++;
    }
  }

 mp_msg( MSGT_STREAM,MSGL_INFO,"[mf] number of files: %d\n",mf->nr_of_files );

exit_mf:
 free( fname );
 return mf;
#else
 mp_msg(MSGT_STREAM,MSGL_FATAL,"[mf] mf support is disabled on your os\n");
 return 0;
#endif
}
示例#25
0
static void
fixurl(const char *gfarm_url)
{
	char *gfarm_file, *local_path, *e;
	struct stat sb;
	int len_path, is_invalid = 0, is_directory = 0;
	glob_t pglob;
	char **pathp, *pat;
	struct gfs_stat gs;

	e = gfarm_canonical_path(gfarm_url_prefix_skip(gfarm_url), &gfarm_file);
	if (e != NULL) {
		/*
		 * no path info, try to delete invalid physical files
		 * or directories
		 */
		e = gfarm_canonical_path_for_creation(
			gfarm_url_prefix_skip(gfarm_url), &gfarm_file);
		if (e != NULL) {
			/* in this case, give up searching invalid files */
			print_errmsg(gfarm_url, e);
			return;
		}
		is_invalid = 1;
	}
	else {
		/* check it is a directory or not */
		e = gfs_stat(gfarm_url, &gs);
		if (e != NULL) {
			if (e != GFARM_ERR_NO_FRAGMENT_INFORMATION) {
				/* maybe permission denied */
				print_errmsg(gfarm_url, e);
				goto error_gfarm_file;
			}
			/* no fragment information case */
		}
		else {
			is_directory = GFARM_S_ISDIR(gs.st_mode);
			gfs_stat_free(&gs);
		}
	}
	/*
	 * Check local_path; if it is invalid or not a directory,
	 * delete it.  Otherwise, check it recursively.
	 */
	e = gfarm_path_localize(gfarm_file, &local_path);
	if (e == NULL && stat(local_path, &sb) == 0) {
		if (is_invalid || !is_directory || !S_ISDIR(sb.st_mode)) {
			print_errmsg(local_path, "invalid file or directory");
			delete_invalid_file_or_directory(local_path);
		}
		else if (chdir(local_path) == 0)
			(void)fixdir(".", gfarm_url);
		/* continue */
	}
	if (e != NULL) {
		print_errmsg(gfarm_url, e);
		goto error_gfarm_file;
	}

	/* investigate file sections */
	len_path = strlen(local_path);
	pat = malloc(len_path + 3);
	if (pat == NULL) {
		print_errmsg(gfarm_url, "not enough memory");
		free(local_path);
		goto error_gfarm_file;
	}
	strcpy(pat, local_path);
	strcat(pat, ":*");
	free(local_path);

	pglob.gl_offs = 0;
	glob(pat, GLOB_DOOFFS, NULL, &pglob);
	free(pat);
	
	pathp = pglob.gl_pathv;
	while (*pathp) {
		char *sec = &((*pathp)[len_path + 1]);

		if (is_invalid || is_directory) {
			print_errmsg_with_section(
				gfarm_url, sec, "invalid file");
			delete_invalid_file_or_directory(*pathp);
			++pathp;
			continue;
		}
		e = fixfrag_i(*pathp, gfarm_file, sec);
		if (e != NULL) {
			if (e != GFARM_ERR_ALREADY_EXISTS) {
				print_errmsg_with_section(gfarm_url, sec, e);
				delete_invalid_file_or_directory(*pathp);
			}
		}
		else
			printf("%s (%s) on %s: fixed\n", gfarm_url, sec,
			       gfarm_host_get_self_name());
		++pathp;
	}
	globfree(&pglob);

 error_gfarm_file:
	free(gfarm_file);
	return;
}
示例#26
0
文件: lex.c 项目: gearsforwork/bareos
/*
 * Open a new configuration file. We push the
 * state of the current file (lf) so that we
 * can do includes.  This is a bit of a hammer.
 * Instead of passing back the pointer to the
 * new packet, I simply replace the contents
 * of the caller's packet with the new packet,
 * and link the contents of the old packet into
 * the next field.
 */
LEX *lex_open_file(LEX *lf,
                   const char *filename,
                   LEX_ERROR_HANDLER *scan_error,
                   LEX_WARNING_HANDLER *scan_warning)
{
   FILE *fd;
   BPIPE *bpipe = NULL;
   char *bpipe_filename = NULL;

   if (filename[0] == '|') {
      bpipe_filename = bstrdup(filename);
      if ((bpipe = open_bpipe(bpipe_filename + 1, 0, "rb")) == NULL) {
         free(bpipe_filename);
         return NULL;
      }
      free(bpipe_filename);
      fd = bpipe->rfd;
      return lex_add(lf, filename, fd, bpipe, scan_error, scan_warning);
   } else {
#ifdef HAVE_GLOB
      int globrc;
      glob_t fileglob;
      char *filename_expanded = NULL;

      /*
       * Flag GLOB_NOMAGIC is a GNU extension, therefore manually check if string is a wildcard string.
       */

      /*
       * Clear fileglob at least required for mingw version of glob()
       */
      memset(&fileglob, 0, sizeof(fileglob));
      globrc = glob(filename, 0, NULL, &fileglob);

      if ((globrc == GLOB_NOMATCH) && (is_wildcard_string(filename))) {
         /*
          * fname is a wildcard string, but no matching files have been found.
          * Ignore this include statement and continue.
          */
         return lf;
      } else if (globrc != 0) {
         /*
          * glob() error has occurred. Giving up.
          */
         return NULL;
      }

      Dmsg2(100, "glob %s: %i files\n", filename, fileglob.gl_pathc);
      for (size_t i = 0; i < fileglob.gl_pathc; i++) {
         filename_expanded = fileglob.gl_pathv[i];
         if ((fd = fopen(filename_expanded, "rb")) == NULL) {
            globfree(&fileglob);
            return NULL;
         }
         lf = lex_add(lf, filename_expanded, fd, bpipe, scan_error, scan_warning);
      }
      globfree(&fileglob);
#else
      if ((fd = fopen(filename, "rb")) == NULL) {
         return NULL;
      }
      lf = lex_add(lf, filename, fd, bpipe, scan_error, scan_warning);
#endif
      return lf;
   }
}
示例#27
0
gboolean tm_workspace_create_global_tags(const char *pre_process, const char **includes,
	int includes_count, const char *tags_file, int lang)
{
#ifdef HAVE_GLOB_H
	glob_t globbuf;
	size_t idx_glob;
#endif
	int idx_inc;
	char *command;
	guint i;
	FILE *fp;
	TMWorkObject *source_file;
	GPtrArray *tags_array;
	GHashTable *includes_files_hash;
	GList *includes_files = NULL;
	gchar *temp_file = create_temp_file("tmp_XXXXXX.cpp");
	gchar *temp_file2 = create_temp_file("tmp_XXXXXX.cpp");

	if (NULL == temp_file || NULL == temp_file2 ||
		NULL == theWorkspace || NULL == (fp = g_fopen(temp_file, "w")))
	{
		g_free(temp_file);
		g_free(temp_file2);
		return FALSE;
	}

	includes_files_hash = g_hash_table_new_full (tm_file_inode_hash,
												 g_direct_equal,
												 NULL, g_free);

#ifdef HAVE_GLOB_H
	globbuf.gl_offs = 0;

	if (includes[0][0] == '"')	/* leading \" char for glob matching */
	for(idx_inc = 0; idx_inc < includes_count; idx_inc++)
	{
 		int dirty_len = strlen(includes[idx_inc]);
		char *clean_path = g_malloc(dirty_len - 1);

		strncpy(clean_path, includes[idx_inc] + 1, dirty_len - 1);
		clean_path[dirty_len - 2] = 0;

#ifdef TM_DEBUG
		g_message ("[o][%s]\n", clean_path);
#endif
		glob(clean_path, 0, NULL, &globbuf);

#ifdef TM_DEBUG
		g_message ("matches: %d\n", globbuf.gl_pathc);
#endif

		for(idx_glob = 0; idx_glob < globbuf.gl_pathc; idx_glob++)
		{
#ifdef TM_DEBUG
			g_message (">>> %s\n", globbuf.gl_pathv[idx_glob]);
#endif
			if (!g_hash_table_lookup(includes_files_hash,
									globbuf.gl_pathv[idx_glob]))
			{
				char* file_name_copy = strdup(globbuf.gl_pathv[idx_glob]);
				g_hash_table_insert(includes_files_hash, file_name_copy,
									file_name_copy);
#ifdef TM_DEBUG
				g_message ("Added ...\n");
#endif
			}
		}
		globfree(&globbuf);
		g_free(clean_path);
  	}
  	else
#endif
	/* no glob support or globbing not wanted */
	for(idx_inc = 0; idx_inc < includes_count; idx_inc++)
	{
		if (!g_hash_table_lookup(includes_files_hash,
									includes[idx_inc]))
		{
			char* file_name_copy = strdup(includes[idx_inc]);
			g_hash_table_insert(includes_files_hash, file_name_copy,
								file_name_copy);
		}
  	}

	/* Checks for duplicate file entries which would case trouble */
	g_hash_table_foreach(includes_files_hash, tm_move_entries_to_g_list,
						 &includes_files);

	includes_files = g_list_reverse (includes_files);

#ifdef TM_DEBUG
	g_message ("writing out files to %s\n", temp_file);
#endif
	if (pre_process != NULL)
		write_includes_file(fp, includes_files);
	else
		append_to_temp_file(fp, includes_files);

	g_list_free (includes_files);
	g_hash_table_destroy(includes_files_hash);
	includes_files_hash = NULL;
	includes_files = NULL;
	fclose(fp);

	if (pre_process != NULL)
	{
		gint ret;
		gchar *tmp_errfile = create_temp_file("tmp_XXXXXX");
		gchar *errors = NULL;
		command = g_strdup_printf("%s %s >%s 2>%s",
								pre_process, temp_file, temp_file2, tmp_errfile);
#ifdef TM_DEBUG
		g_message("Executing: %s", command);
#endif
		ret = system(command);
		g_free(command);
		g_unlink(temp_file);
		g_free(temp_file);
		g_file_get_contents(tmp_errfile, &errors, NULL, NULL);
		if (errors && *errors)
			g_printerr("%s", errors);
		g_free(errors);
		g_unlink(tmp_errfile);
		g_free(tmp_errfile);
		if (ret == -1)
		{
			g_unlink(temp_file2);
			return FALSE;
		}
	}
	else
	{
		/* no pre-processing needed, so temp_file2 = temp_file */
		g_unlink(temp_file2);
		g_free(temp_file2);
		temp_file2 = temp_file;
		temp_file = NULL;
	}
	source_file = tm_source_file_new(temp_file2, TRUE, tm_source_file_get_lang_name(lang));
	if (NULL == source_file)
	{
		g_unlink(temp_file2);
		return FALSE;
	}
	g_unlink(temp_file2);
	g_free(temp_file2);
	if ((NULL == source_file->tags_array) || (0 == source_file->tags_array->len))
	{
		tm_source_file_free(source_file);
		return FALSE;
	}
	tags_array = tm_tags_extract(source_file->tags_array, tm_tag_max_t);
	if ((NULL == tags_array) || (0 == tags_array->len))
	{
		if (tags_array)
			g_ptr_array_free(tags_array, TRUE);
		tm_source_file_free(source_file);
		return FALSE;
	}
	if (FALSE == tm_tags_sort(tags_array, global_tags_sort_attrs, TRUE))
	{
		tm_source_file_free(source_file);
		return FALSE;
	}
	if (NULL == (fp = g_fopen(tags_file, "w")))
	{
		tm_source_file_free(source_file);
		return FALSE;
	}
	fprintf(fp, "# format=tagmanager\n");
	for (i = 0; i < tags_array->len; ++i)
	{
		tm_tag_write(TM_TAG(tags_array->pdata[i]), fp, tm_tag_attr_type_t
		  | tm_tag_attr_scope_t | tm_tag_attr_arglist_t | tm_tag_attr_vartype_t
		  | tm_tag_attr_pointer_t);
	}
	fclose(fp);
	tm_source_file_free(source_file);
	g_ptr_array_free(tags_array, TRUE);
	return TRUE;
}
示例#28
0
int load_font_textures ()
{
	size_t i = 0;
	char *glob_pattern;
#ifdef WINDOWS
	struct _finddata_t c_file;
	long hFile;
#else //WINDOWS
	int ret;
	glob_t glob_res;
	size_t j;
#endif //WINDOWS
	char file[60] = "";
	char str[60] = "";

	if (fonts[0] == NULL || fonts[1] == NULL || fonts[2] == NULL || fonts[3]==NULL )
	{
		for (i = 0; i < FONTS_ARRAY_SIZE; i++) {
			if (fonts[i] != NULL)
				free (fonts[i]);
			fonts[i] = NULL;
		}
		if ( !init_fonts () ) return 0;
	}

	fonts[0]->texture_id = load_texture_cached("textures/font.dds", tt_font);
	i = 1;
	// Force the selection of the base font.
	add_multi_option("chat_font", "Type 1");
	add_multi_option("name_font", "Type 1");
	// Find what font's exist and load them
	glob_pattern = malloc(strlen(datadir)+sizeof(texture_dir)+10+1); //+10 = font*.bmp*
	sprintf(glob_pattern, "%s%sfont*.dds", datadir, texture_dir);
#ifdef WINDOWS
	if( (hFile = _findfirst( glob_pattern, &c_file )) == -1L ){
		free(glob_pattern);
		return 0;
	}
	do {
		int	len;

		safe_strncpy(file, c_file.name, sizeof(file));
#else //!WINDOWS
	ret = glob(glob_pattern, 0, NULL, &glob_res);
	if(ret != 0) {
		LOG_ERROR("Unable to find any font textures\n");
		free(glob_pattern);
		return 0;
	}
	j = 0;
	while (j < glob_res.gl_pathc && i < FONTS_ARRAY_SIZE) {
		int	len;

		safe_strncpy(file, glob_res.gl_pathv[j]+sizeof(texture_dir)-1+strlen(datadir), sizeof(file));
#endif //WINDOWS
		len= strlen(file);
		if (((len + sizeof(texture_dir) - 1) < sizeof(str)) && !strncasecmp(file, "font", 4)
			&& has_suffix(file, len, ".dds", 4))
		{
			safe_snprintf(str, sizeof(str), "./textures/%s", file); //Use a relative path here, load_texture_cache_deferred() is using the path wrappers.
			file[len - 4] = 0;
			fonts[i]->texture_id = load_texture_cached(str, tt_font);
			safe_snprintf(font_names[i], sizeof(font_names[i]), "Type %i - %s", i + 1, file);
			add_multi_option("chat_font", font_names[i]);
			add_multi_option("name_font", font_names[i]);
			i++;
		}
#ifndef WINDOWS
		j++;
#endif //WINDOWS
	}
#ifdef WINDOWS
	while ( _findnext( hFile, &c_file ) == 0 );
	_findclose( hFile );
#else //!WINDOWS
	globfree(&glob_res);
#endif //WINDOWS
	free(glob_pattern);

	//set the default font
	cur_font_num = 0;
	font_text = fonts[0]->texture_id;

	return 1;
}

int set_font_parameters (int num)
{
	int	i;

	// error checking
	if(num < 0 || num >= FONTS_ARRAY_SIZE)
		{
			return -1;
		}
	// allocate space if needed
	if(fonts[num] == NULL)
		{
			fonts[num]=(font_info *)calloc(1, sizeof(font_info));
			if(fonts[num] == NULL)
				{
					LOG_ERROR(cant_load_font);
					return -1;
				}
		}
	//watch the highest font
	if(num >= max_fonts)
		{
			max_fonts=num+1;
		}
	// set default font info
	fonts[num]->spacing=0;

	// load font information
	// TODO: write this and remove the hack!
	for(i=0; i<FONTS_ARRAY_SIZE*FONT_CHARS_PER_LINE; i++) fonts[num]->widths[i]=12;
	if(num==1){
		static int widths[]={
			4,2,7,11,8,12,12,2,7,7,9,10,3,8,
			2,10,10,10,8,8,10,7,9,9,9,9,3,3,
			10,10,10,9,12,12,9,10,10,9,9,10,9,8,
			7,11,8,11,10,11,9,11,11,9,10,9,12,12,
			12,12,10,6,10,6,10,12,3,11,9,9,9,9,
			8,9,9,4,6,10,4,11,9,10,9,9,8,8,
			8,9,10,12,10,10,9,8,2,8,10,8,12,12,
			12,12,12,12,12,12,12,12,12,12,12,12,12,12,
			12,12,12,12,12,12,12,12,12,12,12,12,12,12,
			12,12,12,12,12,12,12,12,12,12,12,12,12,12,
		};
		memcpy(fonts[num]->widths, widths, sizeof(widths));
		fonts[num]->spacing=4;
	}
	if(num==2){
		static int widths[]={
			 8,  8,  8, 10,  8, 10, 10,  8,  8,  8,  8, 10,  8,  8,
			 8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
			10, 10, 10,  8, 12, 10, 10, 10, 10, 10, 10, 10, 10, 10,
			10, 10, 10, 10, 10, 10, 10, 10,  8, 10, 10, 10, 10, 10,
			10, 10, 10, 10, 10, 10, 10,  8,  8,  8,  8,  8,  8,  8,
			10,  8,  8,  8,  8,  8,  8, 10,  8,  8,  8,  8,  8,  8,
			 8,  8,  8, 10,  8,  8,  8, 10,  8, 10, 10,  8, 10,  8,
			 8,  8, 10, 10, 10,  8, 10, 10,  8,  8,  8, 12, 12, 12,
			10, 10, 12, 10, 12, 12, 12,
		};
		memcpy(fonts[num]->widths, widths, sizeof(widths));
		fonts[num]->spacing=2;
	}

	//and return
	return num;
}
示例#29
0
static int Open (vlc_object_t *p_this)
{
    decoder_t *p_dec = (decoder_t *)p_this;

    if (p_dec->fmt_in.i_codec != VLC_CODEC_MIDI)
        return VLC_EGENERIC;

    decoder_sys_t *p_sys = (decoder_sys_t *)malloc (sizeof (*p_sys));			// sunqueen modify
    if (unlikely(p_sys == NULL))
        return VLC_ENOMEM;

    p_sys->settings = new_fluid_settings ();
    p_sys->synth = new_fluid_synth (p_sys->settings);
    p_sys->soundfont = -1;

    char *font_path = var_InheritString (p_this, "soundfont");
    if (font_path != NULL)
    {
        msg_Dbg (p_this, "loading sound fonts file %s", font_path);
        p_sys->soundfont = fluid_synth_sfload (p_sys->synth, font_path, 1);
        if (p_sys->soundfont == -1)
            msg_Err (p_this, "cannot load sound fonts file %s", font_path);
        free (font_path);
    }
#ifdef _POSIX_VERSION
    else
    {
        glob_t gl;

        glob ("/usr/share/sounds/sf2/*.sf2", GLOB_NOESCAPE, NULL, &gl);
        for (size_t i = 0; i < gl.gl_pathc; i++)
        {
            const char *path = gl.gl_pathv[i];

            msg_Dbg (p_this, "loading sound fonts file %s", path);
            p_sys->soundfont = fluid_synth_sfload (p_sys->synth, path, 1);
            if (p_sys->soundfont != -1)
                break; /* it worked! */
            msg_Err (p_this, "cannot load sound fonts file %s", path);
        }
        globfree (&gl);
    }
#endif

    if (p_sys->soundfont == -1)
    {
        msg_Err (p_this, "sound font file required for synthesis");
        dialog_Fatal (p_this, _("MIDI synthesis not set up"),
            _("A sound font file (.SF2) is required for MIDI synthesis.\n"
              "Please install a sound font and configure it "
              "from the VLC preferences "
              "(Input / Codecs > Audio codecs > FluidSynth).\n"));
        delete_fluid_synth (p_sys->synth);
        delete_fluid_settings (p_sys->settings);
        free (p_sys);
        return VLC_EGENERIC;
    }

    fluid_synth_set_chorus_on (p_sys->synth,
                               var_InheritBool (p_this, "synth-chorus"));
    fluid_synth_set_gain (p_sys->synth,
                          var_InheritFloat (p_this, "synth-gain"));
    fluid_synth_set_polyphony (p_sys->synth,
                               var_InheritInteger (p_this, "synth-polyphony"));
    fluid_synth_set_reverb_on (p_sys->synth,
                               var_InheritBool (p_this, "synth-reverb"));

    p_dec->fmt_out.i_cat = AUDIO_ES;
    p_dec->fmt_out.audio.i_rate =
        var_InheritInteger (p_this, "synth-sample-rate");;
//    fluid_synth_set_sample_rate (p_sys->synth, p_dec->fmt_out.audio.i_rate);			// sunqueen delete
    p_dec->fmt_out.audio.i_channels = 2;
    p_dec->fmt_out.audio.i_original_channels =
    p_dec->fmt_out.audio.i_physical_channels =
        AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
    p_dec->fmt_out.i_codec = VLC_CODEC_FL32;
    p_dec->fmt_out.audio.i_bitspersample = 32;
    date_Init (&p_sys->end_date, p_dec->fmt_out.audio.i_rate, 1);
    date_Set (&p_sys->end_date, 0);

    p_dec->p_sys = p_sys;
    p_dec->pf_decode_audio = DecodeBlock;
    return VLC_SUCCESS;
}
/*
 *	The "detail.work" file doesn't exist.  Let's see if we can rename one.
 */
static int work_rename(proto_detail_file_thread_t *thread)
{
	proto_detail_file_t const *inst = thread->inst;
	unsigned int	i;
	int		found;
	time_t		chtime;
	char const	*filename;
	glob_t		files;
	struct stat	st;

	DEBUG3("proto_detail (%s): polling for detail files in %s",
	       thread->name, inst->directory);

	memset(&files, 0, sizeof(files));
	if (glob(inst->filename, 0, NULL, &files) != 0) {
	noop:
		DEBUG3("proto_detail (%s): no matching files for %s",
		       thread->name, inst->filename);
		globfree(&files);
		return -1;
	}

	/*
	 *	Loop over the glob'd files, looking for the
	 *	oldest one.
	 */
	chtime = 0;
	found = -1;
	for (i = 0; i < files.gl_pathc; i++) {
		if (stat(files.gl_pathv[i], &st) < 0) continue;

		if ((i == 0) || (st.st_ctime < chtime)) {
			chtime = st.st_ctime;
			found = i;
		}
	}

	/*
	 *	No matching files, reset the timer and continue.
	 */
	if (found < 0) goto noop;

	/*
	 *	Rename detail to detail.work
	 */
	filename = files.gl_pathv[found];

	DEBUG("proto_detail (%s): Renaming %s -> %s", thread->name, filename, inst->filename_work);
	if (rename(filename, inst->filename_work) < 0) {
		ERROR("detail (%s): Failed renaming %s to %s: %s",
		      thread->name, filename, inst->filename_work, fr_syserror(errno));
		goto noop;
	}

	globfree(&files);	/* Shouldn't be using anything in files now */

	/*
	 *	The file should now exist, return the open'd FD.
	 */
	return open(inst->filename_work, inst->mode);
}