Ejemplo n.º 1
0
int getepvariablesFMU( char*  const fileName, 
					   char*  const myOutputVarsName, 
					   char*  const myOutputVarsType, 
					   int*   const myNumOutputVars, 
					   char*  const myInputKeys, 
					   int*   const myNumInputKeys, 
				       char*  const myInputVars, 
					   int*   const myNumInputVars,
					   int*   const myInputVarsType,
					   int*   const myStrLen){

  FILE * fd;
  XML_Parser p;
  int i, j, count, ret;
  //ret = check_variable_cfg_Validate(fileName);
  //if(-1 == ret) 
    //return -1;

  fd = fopen(fileName, "r");
  if(!fd){
    fprintf(stderr, "Error: Could not open file '%s' when getting EnergyPlus variables.\n", fileName);
    return -1;
  }
  p = XML_ParserCreate(NULL);
  if(!p){
    fprintf(stderr, "Error: Could not allocate memory for parser in function 'getepvariables'.\n");
    return -1;
  }
  
  outputVarsName = myOutputVarsName;
  outputVarsType = myOutputVarsType;
  numOutputVars = myNumOutputVars;
  inputVars = myInputVars;
  inputVarsType = myInputVarsType;
  numInputVars = myNumInputVars;
  numInputKeys = *myNumInputKeys;
  strLen = myStrLen;
  i=0; j=0; count=0;
  inputKeys = NULL;
  while(1){
    if(myInputKeys[count] == '\0') {
      if(inputKeys[i][j] != '\0')
        inputKeys[i][j] = '\0';
      break;
    }
    if(myInputKeys[count] == ','){
      inputKeys[i][j]='\0';
      i++;
      j=0;
      count++;
    }
    else {
      if(j == 0) {
        inputKeys = (char**) realloc(inputKeys, sizeof(char*) * (i+1) );
        if(inputKeys == NULL) {
          fprintf(stderr, "Error: Memory allocation failed in 'utilXml.c'\n");
          return -1;
        }
        inputKeys[i] = NULL;
      }
          
      inputKeys[i] = (char*)realloc(inputKeys[i], sizeof(char) * (j+2) );
      if(inputKeys[i] == NULL) {
        fprintf(stderr, "Error: Memory allocation failed in 'utilXml.c'.\n");
        return -1;
      }
      inputKeys[i][j] = myInputKeys[count];
      j++; count++;
    }
  }
  if((i+1) != *myNumInputKeys ){
    fprintf(stderr, 
	    "Error: Number of input variables keys found does not match:\nFound %d, expected %d\n", 
	    i+1, * myNumInputKeys);
    freeResource(inputKeys, i+1);
    return -1;
  }
  *numOutputVars = 0;
  *numInputVars = 0;
  outputVarsName[0] = '\0';
  outputVarsType[0] = '\0';
  inputVars[0] = '\0';
  source = -1;
  ERROR_STATUS = 0;
  XML_SetElementHandler(p, EPstart, EPend);

  for (;;) {
    int done;
    int len;

    len = (int)fread(Buff, 1, BUFFSIZE, fd);
    if (ferror(fd)) {
      fprintf(stderr, "Error when reading xml variables in '%s'.\n", fileName);
      freeResource(inputKeys, numInputKeys);
      return -1;
    }
    done = feof(fd);

    if (XML_Parse(p, Buff, len, done) == XML_STATUS_ERROR
	|| ERROR_STATUS == 1) {
      fprintf(stderr, "Error: Parser error in file '%s':\n%s\n",
	      fileName,
	      XML_ErrorString(XML_GetErrorCode(p)));
      freeResource(inputKeys, numInputKeys);
      return -1;
    }

    if (done)
      break;
  }
  XML_ParserFree(p);
  fclose(fd);
  freeResource(inputKeys, numInputKeys);
  return 0;
}
Ejemplo n.º 2
0
int
main (int argc, char *argv[])
{
	wchar_t *tprev, *tthis;
	FILE *ifp, *ofp;
	int ch, comp;
	size_t prevbuflen, thisbuflen, b1;
	char *prevline, *thisline, *p;
	const char *ifn;
	cap_rights_t rights;

	(void) setlocale(LC_ALL, "");

	obsolete(argv);
	while ((ch = getopt(argc, argv, "cdif:s:u")) != -1)
		switch (ch) {
		case 'c':
			cflag = 1;
			break;
		case 'd':
			dflag = 1;
			break;
		case 'i':
			iflag = 1;
			break;
		case 'f':
			numfields = strtol(optarg, &p, 10);
			if (numfields < 0 || *p)
				errx(1, "illegal field skip value: %s", optarg);
			break;
		case 's':
			numchars = strtol(optarg, &p, 10);
			if (numchars < 0 || *p)
				errx(1, "illegal character skip value: %s", optarg);
			break;
		case 'u':
			uflag = 1;
			break;
		case '?':
		default:
			usage();
		}

	argc -= optind;
	argv += optind;

	if (argc > 2)
		usage();

	ifp = stdin;
	ifn = "stdin";
	ofp = stdout;
	if (argc > 0 && strcmp(argv[0], "-") != 0)
		ifp = file(ifn = argv[0], "r");
	cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
	if (cap_rights_limit(fileno(ifp), &rights) < 0 && errno != ENOSYS)
		err(1, "unable to limit rights for %s", ifn);
	cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
	if (argc > 1)
		ofp = file(argv[1], "w");
	else
		cap_rights_set(&rights, CAP_IOCTL);
	if (cap_rights_limit(fileno(ofp), &rights) < 0 && errno != ENOSYS) {
		err(1, "unable to limit rights for %s",
		    argc > 1 ? argv[1] : "stdout");
	}
	if (cap_rights_is_set(&rights, CAP_IOCTL)) {
		unsigned long cmd;

		cmd = TIOCGETA; /* required by isatty(3) in printf(3) */

		if (cap_ioctls_limit(fileno(ofp), &cmd, 1) < 0 &&
		    errno != ENOSYS) {
			err(1, "unable to limit ioctls for %s",
			    argc > 1 ? argv[1] : "stdout");
		}
	}

	strerror_init();
	if (cap_enter() < 0 && errno != ENOSYS)
		err(1, "unable to enter capability mode");

	prevbuflen = thisbuflen = 0;
	prevline = thisline = NULL;

	if (getline(&prevline, &prevbuflen, ifp) < 0) {
		if (ferror(ifp))
			err(1, "%s", ifn);
		exit(0);
	}
	tprev = convert(prevline);

	tthis = NULL;
	while (getline(&thisline, &thisbuflen, ifp) >= 0) {
		if (tthis != NULL)
			free(tthis);
		tthis = convert(thisline);

		if (tthis == NULL && tprev == NULL)
			comp = inlcmp(thisline, prevline);
		else if (tthis == NULL || tprev == NULL)
			comp = 1;
		else
			comp = wcscoll(tthis, tprev);

		if (comp) {
			/* If different, print; set previous to new value. */
			show(ofp, prevline);
			p = prevline;
			b1 = prevbuflen;
			prevline = thisline;
			prevbuflen = thisbuflen;
			if (tprev != NULL)
				free(tprev);
			tprev = tthis;
			thisline = p;
			thisbuflen = b1;
			tthis = NULL;
			repeats = 0;
		} else
			++repeats;
	}
	if (ferror(ifp))
		err(1, "%s", ifn);
	show(ofp, prevline);
	exit(0);
}
Ejemplo n.º 3
0
/** @brief Get the icewm style.
  *
  * When icewm changes the style, it writes the new style to the ~/.icewm/theme
  * or $ICEWM_PRIVCFG/theme file and then restarts.  The ~/.icewm/theme file
  * looks like:
  *
  *   Theme="Penguins/default.theme"
  *   #Theme="Airforce/default.theme"
  *   ##Theme="Penguins/default.theme"
  *   ###Theme="Pedestals/default.theme"
  *   ####Theme="Penguins/default.theme"
  *   #####Theme="Airforce/default.theme"
  *   ######Theme="Archlinux/default.theme"
  *   #######Theme="Airforce/default.theme"
  *   ########Theme="Airforce/default.theme"
  *   #########Theme="Airforce/default.theme"
  *   ##########Theme="Penguins/default.theme"
  *
  */
static char *
get_style_ICEWM()
{
	FILE *f;
	struct stat st;
	char *stylefile, *themerc, *buf, *pos, *trm;
	int i, len, beg, end;
	size_t read, total;

	get_rcfile_ICEWM();
	len = strlen(wm->pdir) + strlen("/theme") + 1;
	themerc = calloc(len, sizeof(*themerc));
	snprintf(themerc, len, "%s/theme", wm->pdir);

	if (!(f = fopen(themerc, "r"))) {
		EPRINTF("%s: %s\n", themerc, strerror(errno));
		goto no_themerc;
	}
	if (fstat(fileno(f), &st)) {
		EPRINTF("%s: %s\n", themerc, strerror(errno));
		goto no_stat;
	}
	buf = calloc(st.st_size + 1, sizeof(*buf));
	/* read entire file into buffer */
	total = 0;
	while (total < st.st_size) {
		read = fread(buf + total, 1, st.st_size - total, f);
		total += read;
		if (total >= st.st_size)
			break;
		if (ferror(f)) {
			EPRINTF("%s: %s\n", themerc, strerror(errno));
			goto no_buf;
		}
		if (feof(f))
			break;
	}
	pos = trm = buf;
	if (strncmp(pos, "Theme=\"", 7) != 0) {
		EPRINTF("no theme at start of rc file\n");
		goto no_theme;
	}
	pos += 7;
	if (!(trm = strchr(pos, '"'))) {
		EPRINTF("no theme at start of rc file\n");
		goto no_theme;
	}
	*trm = '\0';
	free(wm->stylename);
	wm->stylename = strdup(pos);
	stylefile = calloc(PATH_MAX, sizeof(*stylefile));
	if (options.user && !options.system) {
		beg = 0;
		end = 2;
	}
	else if (options.system && !options.user) {
		beg = 2;
		end = CHECK_DIRS;
	}
	else {
		beg = 0;
		end = CHECK_DIRS;
	}
	for (i = beg; i < end; i++) {
		if (!wm->dirs[i] || !wm->dirs[i][0])
			continue;
		snprintf(stylefile, PATH_MAX, "%s/themes/%s", wm->dirs[i], wm->stylename);
		if (xde_check_file(stylefile))
			break;
	}
	if (i < end) {
		free(wm->style);
		wm->style = strdup(stylefile);
	}
	free(stylefile);
	return wm->style;
      no_theme:
      no_buf:
	free(buf);
      no_stat:
	fclose(f);
      no_themerc:
	free(themerc);
	return NULL;
}
Ejemplo n.º 4
0
int
main (int argc, char *argv[]) 
{
  const char *program = raptor_basename(argv[0]);
  const char *filename;
  FILE *fh;
  int rc = 0;
  unsigned int line = 1;
  size_t max_c2_len = 0;
  size_t max_c4_len = 0;
  int passes = 0;
  int fails = 0;

  if(argc != 2) {
    fprintf(stderr,
            "USAGE %s [path to NormalizationTest.txt]\n"
            "Get it at http://unicode.org/Public/UNIDATA/NormalizationTest.txt\n",
            program);
    return 1;
  }
  
  filename = argv[1];
  fh = fopen(filename, "r");
  if(!fh) {
    fprintf(stderr, "%s: file '%s' open failed - %s\n",
            program, filename, strerror(errno));
    return 1;
  }

#define LINE_BUFFER_SIZE 1024

/* FIXME big enough for Unicode 4 (c2 max 16; c4 max 33) */
#define UNISTR_SIZE 40

  for(;!feof(fh); line++) {
    char buffer[LINE_BUFFER_SIZE];
    char *p, *start;
    unsigned char column2[UNISTR_SIZE];
    unsigned char column4[UNISTR_SIZE];
    size_t column2_len, column4_len;
    int nfc_rc;
    int error;
    
    p = fgets(buffer, LINE_BUFFER_SIZE, fh);
    if(!p) {
      if(ferror(fh)) {
        fprintf(stderr, "%s: file '%s' read failed - %s\n",
                program, filename, strerror(errno));
        rc = 1;
        break;
      }
      /* assume feof */
      break;
    };

#if 0
    fprintf(stderr, "%s:%d: line '%s'\n", program, line, buffer);
#endif

    /* skip lines */
    if(*p == '@' || *p == '#')
      continue;

    if(line != 56)
      continue;
    

    /* skip column 1 */
    while(*p++ != ';')
      ;

    /* read column 2 into column2, column2_len */
    start = p;
    /* find end column 2 */
    while(*p++ != ';')
      ;

    column2_len = decode_to_utf8(column2, UNISTR_SIZE, start, p-1);
    if(column2_len > max_c2_len)
      max_c2_len = column2_len;
    
    /* skip column 3 */
    while(*p++ != ';')
      ;

    /* read column 4 into column4, column4_len */
    start = p;
    /* find end column 4 */
    while(*p++ != ';')
      ;

    column4_len = decode_to_utf8(column4, UNISTR_SIZE, start, p-1);
    if(column4_len > max_c4_len)
      max_c4_len = column4_len;

    if(!raptor_unicode_check_utf8_string(column2, column2_len)) {
      fprintf(stderr, "%s:%d: UTF8 column 2 failed on: '", filename, line);
      utf8_print(column2, column2_len, stderr);
      fputs("'\n", stderr);
      fails++;
    } else
      passes++;

    /* Column 2 must be NFC */
    nfc_rc = raptor_nfc_check(column2, column2_len, &error);
    if(!nfc_rc) {
      fprintf(stderr, "%s:%d: NFC column 2 failed on: '", filename, line);
      utf8_print(column2, column2_len, stderr);
      fprintf(stderr, "' at byte %d of %d\n", error, (int)column2_len);
      fails++;
    } else
      passes++;

    if(column2_len == column4_len && !memcmp(column2, column4, column2_len))
      continue;

    if(!raptor_unicode_check_utf8_string(column4, column4_len)) {
      fprintf(stderr, "%s:%d: UTF8 column 4 failed on: '", filename, line);
      utf8_print(column4, column4_len, stderr);
      fputs("'\n", stderr);
      fails++;
    } else
      passes++;

    /* Column 4 must be in NFC */
    nfc_rc = raptor_nfc_check(column4, column4_len, &error);
    if(!nfc_rc) {
      fprintf(stderr, "%s:%d: NFC column 4 failed on: '", filename, line);
      utf8_print(column4, column4_len, stderr);
      fprintf(stderr, "' at byte %d of %d\n", error, (int)column4_len);
      fails++;
    } else
      passes++;
  }

  fclose(fh);

  fprintf(stderr, "%s: max column 2 len: %d,  max column 4 len: %d\n", program,
          (int)max_c2_len, (int)max_c4_len);
  fprintf(stderr, "%s: passes: %d fails: %d\n", program,
          passes, fails);

  return rc;
}
Ejemplo n.º 5
0
int
list(void)
{
	ARCHD *arcn;
	int res;
	time_t now;

	arcn = &archd;
	/*
	 * figure out archive type; pass any format specific options to the
	 * archive option processing routine; call the format init routine. We
	 * also save current time for ls_list() so we do not make a system
	 * call for each file we need to print. If verbose (vflag) start up
	 * the name and group caches.
	 */
	if ((get_arc() < 0) || ((*frmt->options)() < 0) ||
	    ((*frmt->st_rd)() < 0))
		return 1;

	now = time(NULL);

	/*
	 * step through the archive until the format says it is done
	 */
	while (next_head(arcn) == 0) {
		if (arcn->type == PAX_GLL || arcn->type == PAX_GLF) {
			/*
			 * we need to read, to get the real filename
			 */
			off_t cnt;
			if (!(*frmt->rd_data)(arcn, -arcn->type, &cnt))
				(void)rd_skip(cnt + arcn->pad);
			continue;
		}

		/*
		 * check for pattern, and user specified options match.
		 * When all patterns are matched we are done.
		 */
		if ((res = pat_match(arcn)) < 0)
			break;

		if ((res == 0) && (sel_chk(arcn) == 0)) {
			/*
			 * pattern resulted in a selected file
			 */
			if (pat_sel(arcn) < 0)
				break;

			/*
			 * modify the name as requested by the user if name
			 * survives modification, do a listing of the file
			 */
			if ((res = mod_name(arcn, RENM)) < 0)
				break;
			if (res == 0) {
				if (arcn->name[0] == '/' && !check_Aflag()) {
					memmove(arcn->name, arcn->name + 1, 
					    strlen(arcn->name));
				}
				ls_list(arcn, now, stdout);
			}
			/*
			 * if there's an error writing to stdout then we must
			 * stop now -- we're probably writing to a pipe that
			 * has been closed by the reader.
			 */
			if (ferror(stdout)) {
				syswarn(1, errno, "Listing incomplete.");
				break;
			}
		}
		/*
		 * skip to next archive format header using values calculated
		 * by the format header read routine
		 */
		if (rd_skip(arcn->skip + arcn->pad) == 1)
			break;
	}

	/*
	 * all done, let format have a chance to cleanup, and make sure that
	 * the patterns supplied by the user were all matched
	 */
	(void)(*frmt->end_rd)();
	(void)sigprocmask(SIG_BLOCK, &s_mask, NULL);
	ar_close();
	pat_chk();

	return 0;
}
Ejemplo n.º 6
0
/**
 * Print information about each option.
 *
 * @param[in] opts      the program options
 * @param[in] exit_code whether or not there was a usage error reported.
 *                      used to select full usage versus abbreviated.
 */
static void
print_usage_details(tOptions * opts, int exit_code)
{
    {
        char const * pOptTitle = NULL;
        int flen;

        /*
         *  Determine which header and which option formatting strings to use
         */
        if (do_gnu_usage(opts)) {
            flen = setGnuOptFmts(opts, &pOptTitle);
            sprintf(line_fmt_buf, zFmtFmt, flen);
            fputc(NL, option_usage_fp);

        } else {
            flen = setStdOptFmts(opts, &pOptTitle);
            sprintf(line_fmt_buf, zFmtFmt, flen);

            /*
             *  When we exit with EXIT_SUCCESS and the first option is a doc
             *  option, we do *NOT* want to emit the column headers.
             *  Otherwise, we do.
             */
            if (  (exit_code != EXIT_SUCCESS)
               || ((opts->pOptDesc->fOptState & OPTST_DOCUMENT) == 0) )

                fputs(pOptTitle, option_usage_fp);
        }

        flen = 4 - ((flen + 15) / 8);
        if (flen > 0)
            tab_skip_ct = flen;
        prt_opt_usage(opts, exit_code, pOptTitle);
    }

    /*
     *  Describe the mechanics of denoting the options
     */
    switch (opts->fOptSet & OPTPROC_L_N_S) {
    case OPTPROC_L_N_S:     fputs(zFlagOkay, option_usage_fp); break;
    case OPTPROC_SHORTOPT:  break;
    case OPTPROC_LONGOPT:   fputs(zNoFlags,  option_usage_fp); break;
    case 0:                 fputs(zOptsOnly, option_usage_fp); break;
    }

    if ((opts->fOptSet & OPTPROC_NUM_OPT) != 0)
        fputs(zNumberOpt, option_usage_fp);

    if ((opts->fOptSet & OPTPROC_REORDER) != 0)
        fputs(zReorder, option_usage_fp);

    if (opts->pzExplain != NULL)
        fputs(opts->pzExplain, option_usage_fp);

    /*
     *  IF the user is asking for help (thus exiting with SUCCESS),
     *  THEN see what additional information we can provide.
     */
    if (exit_code == EXIT_SUCCESS)
        prt_prog_detail(opts);

    /*
     * Give bug notification preference to the packager information
     */
    if (HAS_pzPkgDataDir(opts) && (opts->pzPackager != NULL))
        fputs(opts->pzPackager, option_usage_fp);

    else if (opts->pzBugAddr != NULL)
        fprintf(option_usage_fp, zPlsSendBugs, opts->pzBugAddr);

    fflush(option_usage_fp);

    if (ferror(option_usage_fp) != 0)
        fserr_exit(opts->pzProgName, zwriting, (option_usage_fp == stderr)
                   ? zstderr_name : zstdout_name);
}
Ejemplo n.º 7
0
cct_status _cct_source_subrip_read(cct_source_ctx *ctx, cct_sub_entry **entry, unsigned int *eos)
{
    (*entry) = NULL;
    *eos = 0;
    cct_source_subrip_ctx *sctx = (cct_source_subrip_ctx *) ctx->ctx_data;
    char buffer[SRT_MAX_LINE_LENGTH];
    if (!fgets(buffer, SRT_MAX_LINE_LENGTH, sctx->file)) {
        if (feof(sctx->file)) {
            *eos = 1;
            return CCT_OK;
        } else if (ferror(sctx->file)) {
            perror("_cct_subrip_source_read: can't read entry counter");
            return CCT_FATAL;
        }
        fprintf(stderr, "_cct_subrip_source_read: unhandled branch for counter\n");
        return CCT_FATAL;
    }

    unsigned long counter = 0;
    sctx->counter++;
    sscanf(buffer, "%lu", &counter);
    if (counter != sctx->counter) {
        fprintf(stderr, "_cct_subrip_source_read: counter missing: expected %lu, got %lu\n", sctx->counter, counter);
        sctx->counter = counter;
    }

    if (!fgets(buffer, SRT_MAX_LINE_LENGTH, sctx->file)) {
        if (feof(sctx->file)) {
            fprintf(stderr, "_cct_subrip_source_read: premature end of file (time)\n");
            return CCT_FATAL;
        } else if (ferror(sctx->file)) {
            perror("_cct_subrip_source_read: can't read time");
            return CCT_FATAL;
        }
        fprintf(stderr, "_cct_subrip_source_read: unhandled branch for time\n");
        return CCT_FATAL;
    }

    unsigned int st_h, st_m, st_s, st_ms,
            et_h, et_m, et_s, et_ms;

    unsigned long start_time, end_time;

    sscanf(buffer, "%u:%u:%u,%u --> %u:%u:%u,%u", //TODO add display coords handling
           &st_h, &st_m, &st_s, &st_ms,
           &et_h, &et_m, &et_s, &et_ms);

    start_time = st_ms + (st_s * 1000) + (st_m * 1000 * 60) + (st_h * 1000 * 60 * 60);
    end_time = et_ms + (et_s * 1000) + (et_m * 1000 * 60) + (et_h * 1000 * 60 * 60);

    unsigned int lines_count = 0;
    char lines_buffer[SRT_MAX_LINES][SRT_MAX_LINE_LENGTH];
    memset(lines_buffer, 0, SRT_MAX_LINES * SRT_MAX_LINE_LENGTH * sizeof(char));

    while (fgets(lines_buffer[lines_count], SRT_MAX_LINE_LENGTH, sctx->file) && lines_count < SRT_MAX_LINES) {
        //removing trailing \r\n or \n first
        char *c_ptr = strrchr(lines_buffer[lines_count], '\n');
        if (c_ptr) {
            *c_ptr = '\0';
        }
        c_ptr = strrchr(lines_buffer[lines_count], '\r');
        if (c_ptr) {
            *c_ptr = '\0';
        }
        if (!strlen(lines_buffer[lines_count])) {
            if (lines_count == 0) {
                fprintf(stderr, "_cct_subrip_source_read: unexpected empty line\n");
            }
            //done reading entry
            break;
        }
        lines_count++;
    }

    if (lines_count == SRT_MAX_LINES) {
        fprintf(stdout, "_cct_subrip_source_read: too much lines\n");
        return CCT_FATAL;
    }

    if (feof(sctx->file) && lines_count == 0) {
        fprintf(stderr, "_cct_subrip_source_read: premature end of file (lines)\n");
        return CCT_FATAL;
    }
    if (ferror(sctx->file)) {
        perror("_cct_subrip_source_read: cant read lines");
        return CCT_FATAL;
    }

    cct_sub_entry *new_entry = malloc(sizeof(cct_sub_entry));
    if (!new_entry) {
        perror("_cct_subrip_source_read: malloc() new_entry failed");
        return CCT_FATAL;
    }

    new_entry->counter = counter;
    new_entry->start_time = start_time;
    new_entry->end_time = end_time;
    new_entry->lines_count = lines_count;
    new_entry->lines = (char **) malloc(new_entry->lines_count * sizeof(char*));
    if (!new_entry->lines) {
        perror("_cct_subrip_source_read: malloc() new_entry->lines failed");
        return CCT_FATAL;
    }
    for (unsigned int i = 0; i < lines_count; i++) {
        new_entry->lines[i] = strdup(lines_buffer[i]);
        if (!new_entry->lines[i]) {
            perror("_cct_subrip_source_read: strdup() new_entry->lines[i] failed");
            return CCT_FATAL;
        }
    }

    (*entry) = new_entry;
    return CCT_OK;
}
/* Find an appropriate scope fits to given conditions */
static Dwarf_Die *find_best_scope(struct probe_finder *pf, Dwarf_Die *die_mem)
{
	struct find_scope_param fsp = {
		.function = pf->pev->point.function,
		.file = pf->fname,
		.line = pf->lno,
		.diff = INT_MAX,
		.die_mem = die_mem,
		.found = false,
	};

	cu_walk_functions_at(&pf->cu_die, pf->addr, find_best_scope_cb, &fsp);

	return fsp.found ? die_mem : NULL;
}

static int probe_point_line_walker(const char *fname, int lineno,
				   Dwarf_Addr addr, void *data)
{
	struct probe_finder *pf = data;
	Dwarf_Die *sc_die, die_mem;
	int ret;

	if (lineno != pf->lno || strtailcmp(fname, pf->fname) != 0)
		return 0;

	pf->addr = addr;
	sc_die = find_best_scope(pf, &die_mem);
	if (!sc_die) {
		pr_warning("Failed to find scope of probe point.\n");
		return -ENOENT;
	}

	ret = call_probe_finder(sc_die, pf);

	/* Continue if no error, because the line will be in inline function */
	return ret < 0 ? ret : 0;
}

/* Find probe point from its line number */
static int find_probe_point_by_line(struct probe_finder *pf)
{
	return die_walk_lines(&pf->cu_die, probe_point_line_walker, pf);
}

/* Find lines which match lazy pattern */
static int find_lazy_match_lines(struct list_head *head,
				 const char *fname, const char *pat)
{
	FILE *fp;
	char *line = NULL;
	size_t line_len;
	ssize_t len;
	int count = 0, linenum = 1;

	fp = fopen(fname, "r");
	if (!fp) {
		pr_warning("Failed to open %s: %s\n", fname, strerror(errno));
		return -errno;
	}

	while ((len = getline(&line, &line_len, fp)) > 0) {

		if (line[len - 1] == '\n')
			line[len - 1] = '\0';

		if (strlazymatch(line, pat)) {
			line_list__add_line(head, linenum);
			count++;
		}
		linenum++;
	}

	if (ferror(fp))
		count = -errno;
	free(line);
	fclose(fp);

	if (count == 0)
		pr_debug("No matched lines found in %s.\n", fname);
	return count;
}
Ejemplo n.º 9
0
static void check_flo(file_list **lst, char *nm)
{
    FILE	*fp;
    off_t	off;
    struct	flock fl;
    char	buf[PATH_MAX], buf2[PATH_MAX], *p, *q;
    int		disposition;
    struct stat stbuf;

    if ((fp = fopen(nm,"r+")) == NULL) {
	/*
	 * If no flo file, return.
	 */
	return;
    }

    Syslog('o', "check_flo(\"%s\")",FTND_SS(nm));

    fl.l_type   = F_RDLCK;
    fl.l_whence = 0;
    fl.l_start  = 0L;
    fl.l_len    = 0L;

    if (fcntl(fileno(fp), F_SETLK, &fl) != 0) {
	if (errno != EAGAIN)
	    WriteError("$Can't read-lock \"%s\"", FTND_SS(nm));
	else 
	    Syslog('o',"flo file busy");
	fclose(fp);
	return;
    }

    if (stat(nm, &stbuf) != 0) {
	WriteError("$Can't access \"%s\"", FTND_SS(nm));
	fclose(fp);
	return;
    }

    while (!feof(fp) && !ferror(fp)) {
	off = ftell(fp);
	if (fgets(buf, sizeof(buf)-1, fp) == NULL) 
	    continue;
	if (buf[0] == '~') 
	    continue; /* skip sent files */
	if (*(p=buf + strlen(buf) -1) == '\n') 
	    *p-- = '\0';
	if (*p == '\r') 
	    *p = '\0';

	switch (buf[0]) {
	    case '#':	p=buf+1; disposition=TFS; break;
	    case '-':
	    case '^':	p=buf+1; disposition=KFS; break;
	    case '@':	p=buf+1; disposition=LEAVE; break;
	    case 0:	continue;
	    default:	p=buf; disposition=LEAVE; break;
	}

	memset(&buf2, 0, sizeof(buf2));
	if (strlen(CFG.dospath)) {
	    if (strncasecmp(p, CFG.dospath, strlen(CFG.dospath)) == 0) {
		strcpy(buf2,uxoutbound);
		for (p+=strlen(CFG.dospath), q=buf2+strlen(buf2); *p; p++, q++)
		    *q = ((*p) == '\\')?'/':tolower(*p);
		*q = '\0';
		p = buf2;
	    }
	}

	if ((q=strrchr(p,'/')))
	    q++;
	else
	    q = p;
	add_list(lst, p, q, disposition, off, fp, 1);
    }

    /*
     * Add flo file to file list
     */
    add_list(lst, nm, NULL, KFS, -1L, fp, 1);

    /* here, we leave .flo file open, it will be closed by */
    /* execute_disposition */

    return;
}
Ejemplo n.º 10
0
static int add_mount(
                const char *what,
                const char *where,
                const char *fstype,
                const char *opts,
                int passno,
                bool noauto,
                bool nofail,
                bool automount,
                const char *post,
                const char *source) {

        _cleanup_free_ char
                *name = NULL, *unit = NULL, *lnk = NULL,
                *automount_name = NULL, *automount_unit = NULL,
                *filtered = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        int r;

        assert(what);
        assert(where);
        assert(opts);
        assert(source);

        if (streq_ptr(fstype, "autofs"))
                return 0;

        if (!is_path(where)) {
                log_warning("Mount point %s is not a valid path, ignoring.", where);
                return 0;
        }

        if (mount_point_is_api(where) ||
            mount_point_ignore(where))
                return 0;

        if (path_equal(where, "/")) {
                /* The root disk is not an option */
                automount = false;
                noauto = false;
                nofail = false;
        }

        name = unit_name_from_path(where, ".mount");
        if (!name)
                return log_oom();

        unit = strjoin(arg_dest, "/", name, NULL);
        if (!unit)
                return log_oom();

        f = fopen(unit, "wxe");
        if (!f) {
                if (errno == EEXIST)
                        log_error("Failed to create mount unit file %s, as it already exists. Duplicate entry in /etc/fstab?", unit);
                else
                        log_error_errno(errno, "Failed to create unit file %s: %m", unit);
                return -errno;
        }

        fprintf(f,
                "# Automatically generated by systemd-fstab-generator\n\n"
                "[Unit]\n"
                "SourcePath=%s\n"
                "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n",
                source);

        if (post && !noauto && !nofail && !automount)
                fprintf(f, "Before=%s\n", post);

        if (passno != 0) {
                r = generator_write_fsck_deps(f, arg_dest, what, where, fstype);
                if (r < 0)
                        return r;
        }

        fprintf(f,
                "\n"
                "[Mount]\n"
                "What=%s\n"
                "Where=%s\n",
                what,
                where);

        if (!isempty(fstype) && !streq(fstype, "auto"))
                fprintf(f, "Type=%s\n", fstype);

        r = generator_write_timeouts(arg_dest, what, where, opts, &filtered);
        if (r < 0)
                return r;

        if (!isempty(filtered) && !streq(filtered, "defaults"))
                fprintf(f, "Options=%s\n", filtered);

        fflush(f);
        if (ferror(f))
                return log_error_errno(errno, "Failed to write unit file %s: %m", unit);

        if (!noauto && post) {
                lnk = strjoin(arg_dest, "/", post, nofail || automount ? ".wants/" : ".requires/", name, NULL);
                if (!lnk)
                        return log_oom();

                mkdir_parents_label(lnk, 0755);
                if (symlink(unit, lnk) < 0)
                        return log_error_errno(errno, "Failed to create symlink %s: %m", lnk);
        }

        if (automount) {
                automount_name = unit_name_from_path(where, ".automount");
                if (!automount_name)
                        return log_oom();

                automount_unit = strjoin(arg_dest, "/", automount_name, NULL);
                if (!automount_unit)
                        return log_oom();

                fclose(f);
                f = fopen(automount_unit, "wxe");
                if (!f)
                        return log_error_errno(errno, "Failed to create unit file %s: %m", automount_unit);

                fprintf(f,
                        "# Automatically generated by systemd-fstab-generator\n\n"
                        "[Unit]\n"
                        "SourcePath=%s\n"
                        "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n",
                        source);

                if (post)
                        fprintf(f,
                                "Before=%s\n",
                                post);

                fprintf(f,
                        "[Automount]\n"
                        "Where=%s\n",
                        where);

                fflush(f);
                if (ferror(f))
                        return log_error_errno(errno, "Failed to write unit file %s: %m", automount_unit);

                free(lnk);
                lnk = strjoin(arg_dest, "/", post, nofail ? ".wants/" : ".requires/", automount_name, NULL);
                if (!lnk)
                        return log_oom();

                mkdir_parents_label(lnk, 0755);
                if (symlink(automount_unit, lnk) < 0)
                        return log_error_errno(errno, "Failed to create symlink %s: %m", lnk);
        }

        return 0;
}
void buildOpenCLKernels_tea_leaf_zeqxty_kernel(int xdim0, int xdim1,
                                               int xdim2) {

  // int ocl_fma = OCL_FMA;
  if (!isbuilt_tea_leaf_zeqxty_kernel) {
    buildOpenCLKernels();
    // clSafeCall( clUnloadCompiler() );
    cl_int ret;
    char *source_filename[1] = {(char *)"./OpenCL/tea_leaf_zeqxty_kernel.cl"};

    // Load the kernel source code into the array source_str
    FILE *fid;
    char *source_str[1];
    size_t source_size[1];

    for (int i = 0; i < 1; i++) {
      fid = fopen(source_filename[i], "r");
      if (!fid) {
        fprintf(stderr, "Can't open the kernel source file!\n");
        exit(1);
      }

      source_str[i] = (char *)malloc(4 * 0x1000000);
      source_size[i] = fread(source_str[i], 1, 4 * 0x1000000, fid);
      if (source_size[i] != 4 * 0x1000000) {
        if (ferror(fid)) {
          printf("Error while reading kernel source file %s\n",
                 source_filename[i]);
          exit(-1);
        }
        if (feof(fid))
          printf("Kernel source file %s succesfuly read.\n",
                 source_filename[i]);
        // printf("%s\n",source_str[i]);
      }
      fclose(fid);
    }

    printf("Compiling tea_leaf_zeqxty_kernel %d source -- start \n", OCL_FMA);

    // Create a program from the source
    OPS_opencl_core.program = clCreateProgramWithSource(
        OPS_opencl_core.context, 1, (const char **)&source_str,
        (const size_t *)&source_size, &ret);
    clSafeCall(ret);

    // Build the program
    char buildOpts[255 * 3];
    char *pPath = NULL;
    pPath = getenv("OPS_INSTALL_PATH");
    if (pPath != NULL)
      if (OCL_FMA)
        sprintf(buildOpts, "-cl-mad-enable -DOCL_FMA -I%s/c/include "
                           "-DOPS_WARPSIZE=%d  "
                           "-Dxdim0_tea_leaf_zeqxty_kernel=%d  "
                           "-Dxdim1_tea_leaf_zeqxty_kernel=%d  "
                           "-Dxdim2_tea_leaf_zeqxty_kernel=%d ",
                pPath, 32, xdim0, xdim1, xdim2);
      else
        sprintf(buildOpts, "-cl-mad-enable -I%s/c/include -DOPS_WARPSIZE=%d  "
                           "-Dxdim0_tea_leaf_zeqxty_kernel=%d  "
                           "-Dxdim1_tea_leaf_zeqxty_kernel=%d  "
                           "-Dxdim2_tea_leaf_zeqxty_kernel=%d ",
                pPath, 32, xdim0, xdim1, xdim2);
    else {
      sprintf((char *)"Incorrect OPS_INSTALL_PATH %s\n", pPath);
      exit(EXIT_FAILURE);
    }

    ret = clBuildProgram(OPS_opencl_core.program, 1, &OPS_opencl_core.device_id,
                         buildOpts, NULL, NULL);

    if (ret != CL_SUCCESS) {
      char *build_log;
      size_t log_size;
      clSafeCall(clGetProgramBuildInfo(
          OPS_opencl_core.program, OPS_opencl_core.device_id,
          CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size));
      build_log = (char *)malloc(log_size + 1);
      clSafeCall(clGetProgramBuildInfo(
          OPS_opencl_core.program, OPS_opencl_core.device_id,
          CL_PROGRAM_BUILD_LOG, log_size, build_log, NULL));
      build_log[log_size] = '\0';
      fprintf(
          stderr,
          "=============== OpenCL Program Build Info ================\n\n%s",
          build_log);
      fprintf(stderr,
              "\n========================================================= \n");
      free(build_log);
      exit(EXIT_FAILURE);
    }
    printf("compiling tea_leaf_zeqxty_kernel -- done\n");

    // Create the OpenCL kernel
    OPS_opencl_core.kernel[41] = clCreateKernel(
        OPS_opencl_core.program, "ops_tea_leaf_zeqxty_kernel", &ret);
    clSafeCall(ret);

    isbuilt_tea_leaf_zeqxty_kernel = true;
  }
}
Ejemplo n.º 12
0
// initialize the auto update system, start the downloading
void    init_update()
{
	FILE    *fp;

	if(update_busy){
		return;
	}
	// initialize variables
	update_busy++;
	update_attempt_count= 0;	// no downloads have been attempted
	temp_counter= 0;			//start with download name with 0
	restart_required= 0;		// no restart needed yet
	allow_restart= 1;			// automated restart allowed

	// create the mutex & init the download que
	if(!download_mutex){
//		file_update_clear_old();	// There is no reason to delete all the previous files. We only remove the ones out of date.
		download_mutex= SDL_CreateMutex();
		download_queue_size= 0;
		memset(download_queue, 0, sizeof(download_queue));
		download_cur_file= NULL;
		download_cur_md5= NULL;
	}
	
	// load the server list
	num_update_servers= 0;
	update_server[0]= '\0';
	fp = open_file_data("mirrors.lst", "r");
	if(fp == NULL){
		LOG_ERROR("%s: %s \"mirrors.lst\": %s\n", reg_error_str, cant_open_file, strerror(errno));
	} else {
		char    buffer[1024];
		char	*ptr;
		
		ptr= fgets(buffer, sizeof(buffer), fp);
		while(ptr && !ferror(fp) && num_update_servers < sizeof(update_servers)){
			int len= strlen(buffer);
			
			// is this line worth handling?
			if(len > 6 && *buffer > ' ' && *buffer != '#'){
				while(isspace(buffer[len-1])){
					buffer[len-1]= '\0';
					len--;
				}
				if(len > 6){
					update_servers[num_update_servers++]= strdup(buffer);
				}
			}
			// read the next line
			ptr= fgets(buffer, sizeof(buffer), fp);
		}
		if(fp){
			fclose(fp);
		}
	}
	if(!num_update_servers) {
		// oops, no mirror file, no downloading
		update_servers[0]= "";
		return;
	}
	
	// start the process
	if(download_mutex){
		strcpy(files_lst, "files.lst");
		is_this_files_lst= 1;
		handle_update_download(NULL);
	}
}
Ejemplo n.º 13
0
char *file2strl(
    const char *path,
    unsigned int *file_len_out
)
{
    FILE *file;


    if (!(file = fopen(path, "rb")))
    {
        fprintf(stderr, "Unable to open file %s\n", path);
        return NULL;
    }

    if (-1 == fseek(file, 0, SEEK_END))
    {
        fprintf(stderr, "Unable to seek file %s\n", path);
        fclose(file);
        return NULL;
    }

    unsigned long file_len;
    unsigned long bytes_read;
    if (-1 == (file_len = ftell(file)))
    {
        fprintf(stderr, "Unable to ftell() file %s\n", path);
        fclose(file);
        return NULL;
    }

    if (-1 == fseek(file, 0, SEEK_SET))
    {
        fprintf(stderr, "Unable to seek file %s\n", path);
        fclose(file);
        return NULL;
    }

    char *contents;
    if (!(contents = malloc(file_len + 1)))
    {
        fprintf(stderr, "Memory error!\n");
        fclose(file);
        return NULL;
    }

    bytes_read = fread(contents, file_len, 1, file);
    if(bytes_read == 0 && ferror(file)) {
        fprintf(stderr, "Read error");
        free(contents);
        fclose(file);
        return NULL;   
    }
    fclose(file);

    contents[file_len] = '\0';

    if (file_len_out)
        *file_len_out = file_len + 1;

    return contents;
}
Ejemplo n.º 14
0
////////////////////////////////////////////////////////////////
/// This is a general function that returns the value according to \c exp
///
/// \c exp mimics the xPath expression.
/// Its format is //el1/../eln[@attr]
/// which will return the \c attr value of \c eln, 
/// where \c eln is the n-th child of \c el1
///
/// Example: //variable/EnergyPlus[@name] will return the name attributes of EnergyPlus
/// which is equivalent to //EnergyPlus[@name]
///
///\param fileName the xml file name.  
///\param exp the xPath expression.
///\param myVals string to store the found values, semicolon separated.
///\param mynumVals number of values found.
///\param myStrLen length of the string that is passed.
////////////////////////////////////////////////////////////////
int 
getxmlvalues(char* const fileName, 
             char* const exp, 
             char* const myVals, 
             int*  const myNumVals,
             int   const myStrLen){

  char* temp;
  int i,j;
  FILE * fd;
  XML_Parser p;
  vals = myVals;
  numVals = myNumVals;
  *numVals = 0;
  strLen = &myStrLen;
  att = NULL;
  expStk.head = NULL;
  expStk.top = -1;
  expStk.cur = -1;
  fd = fopen(fileName, "r");
  if(!fd) {
    fprintf(stderr, "Error: Could not open file '%s'.\n", fileName);
    return -1;
  }
  p = XML_ParserCreate(NULL);
  if (!p) {
    fprintf(stderr, "Error: Could not allocate memory for parser in function 'getxmlvalue'.\n");
    return -1;
  }
  i=2; j=0;
  if(!exp || '\0' == exp[0]) 
    return -1;
  if( exp[0] != '/' || exp[1] != '/')
    return -1;

  temp = NULL;
  while(exp[i] != '\0'){
    if( exp[i] == '/' || exp[i] == '[' || exp[i] == ']') {
      if(0==j && 0==expStk.top) {
        fprintf(stderr, "Error when parsing expression in 'utilXml.c'.\n");
        return -1;
      }
      i++;
      if(strchr(temp, '@'))
        break;
      stackPushBCVTB(temp);
      free(temp);
      temp = NULL;
      j=0;
    }
    else {
      j++;  
      temp = (char*) realloc(temp, sizeof(char)*(j+1));
      if(temp == NULL) {
        fprintf(stderr, "Error: Memory allocation failed in 'utilXml.c'.\n");
        return -1;
      }
      temp[j-1]=exp[i];
      temp[j]='\0';
      i++;
    }
  }
  if(temp[0] == '@'){
    att = (char*) malloc(sizeof(char) * (strlen(temp) ) );
    if(att == NULL) {
      fprintf(stderr, "Error: Memory allocation failed in 'utilXml.c'.\n");
	  free(temp);
      return -1;
    }
    for(i=1; i<strlen(temp); i++) 
      att[i-1] = temp[i];
    att[i-1]='\0';
    free(temp);
  }
  else {
    fprintf(stderr, "Error when parsing expression in 'utilXml.c'.\n");
	free(temp);
	free(att);
	while(i!= -1) stackPopBCVTB();
    return -1;
  }
  expStk.cur = 0;
  if(1 == PARSEVALUE)
    vals[0]='\0';
  *numVals = 0;
  XML_SetElementHandler(p, start, end);

  for (;;) {
    int done;
    int len;

    len = (int)fread(Buff, 1, BUFFSIZE, fd);
    if (ferror(fd)) {
      fprintf(stderr, "Error when reading xml variables in '%s'.\n", fileName);
      return -1;
    }
    done = feof(fd);

    if (XML_Parse(p, Buff, len, done) == XML_STATUS_ERROR) {
      fprintf(stderr, "Error: Parse error in file '%s':\n%s\n",
	      fileName,
              XML_ErrorString(XML_GetErrorCode(p)));
      return -1;
    }

    if (done)
      break;
  }
  if( 0 == *numVals ){
	  fprintf(stderr, "Error: Did not find xml value\n       for expression '%s'.\n       in file '%s'\n", 
		  exp, fileName);
  }
  while( i != -1 ) 
    i = stackPopBCVTB();  
  att = NULL;
  XML_ParserFree(p);
  fclose(fd);
  return 0;

}
Ejemplo n.º 15
0
void
process(const char *name)
{
	char *cp;
	int c;
	int incomm = 0;
	int ret;

	printf("extern char\txstr[];\n");
	for (;;) {
		if (fgets(linebuf, sizeof linebuf, stdin) == NULL) {
			if (ferror(stdin))
				err(3, "%s", name);
			break;
		}
		if (linebuf[0] == '#') {
			if (linebuf[1] == ' ' && isdigit(linebuf[2]))
				printf("#line%s", &linebuf[1]);
			else
				printf("%s", linebuf);
			continue;
		}
		for (cp = linebuf; (c = *cp++);) switch (c) {

		case '"':
			if (incomm)
				goto def;
			if ((ret = (int) yankstr(&cp)) == -1)
				goto out;
			printf("(&xstr[%d])", ret);
			break;

		case '\'':
			if (incomm)
				goto def;
			putchar(c);
			if (*cp)
				putchar(*cp++);
			break;

		case '/':
			if (incomm || *cp != '*')
				goto def;
			incomm = 1;
			cp++;
			printf("/*");
			continue;

		case '*':
			if (incomm && *cp == '/') {
				incomm = 0;
				cp++;
				printf("*/");
				continue;
			}
			goto def;

def:
		default:
			putchar(c);
			break;
		}
	}
out:
	if (ferror(stdout))
		warn("x.c"), onintr(0);
}
Ejemplo n.º 16
0
void execute_disposition(file_list *fl)
{
    FILE    *fp=NULL;
    char    *nm, tpl='~';

    Syslog('o', "execute_disposition(%s)", fl->local);
    nm = fl->local;
    if (fl->flofp) {
	/*
	 * Check for special case: flo-file 
	 */
	if (fl->floff == -1) {
	    /*
	     * We check if there are any files left for transmission
	     * in the flo-file to decide whether to remove or leave
	     * it on disk.
	     */
	    char    buf[PATH_MAX];
	    int	    files_remain = 0;

	    if (fseek(fl->flofp, 0L, 0) == 0) {
		while (!feof(fl->flofp) && !ferror(fl->flofp)) {
		    if (fgets(buf, sizeof(buf)-1, fl->flofp) == NULL)
			continue;

		    /*
		     * Count nr of files which haven't been sent yet
		     */
		    if (buf[0] != '~')
			files_remain++;
		}

	    } else {
		WriteError("$Error seeking in .flo to 0");
		files_remain = -1; /* Keep flo-file */
	    }

	    if (files_remain) {
		Syslog('o', "Leaving flo-file \"%s\", %d files remaining", FTND_SS(nm), files_remain);
		fl->disposition = LEAVE;
	    } else {
		fl->disposition = KFS;
	    }
	} else {
	    /*
	     * Mark files as sent in flo-file
	     */
	    if (fseek(fl->flofp, fl->floff, 0) == 0) {
		if (fwrite(&tpl,1,1,fl->flofp) != 1) {
		    WriteError("$Error writing '~' to .flo at %u", (unsigned int)fl->floff);
		} else {
		    Syslog('o', "Marked file \"%s\" as sent", FTND_SS(nm));
		}
		fflush(fl->flofp);
#ifdef HAVE_FDATASYNC
		fdatasync(fileno(fl->flofp));
#else
#ifdef HAVE_FSYNC		
		fsync(fileno(fl->flofp));
#endif
#endif
	    } else 
		WriteError("$error seeking in .flo to %u", (unsigned int)fl->floff);
	}
    }

    switch (fl->disposition) {
	case DSF:
	case LEAVE: break;

	case TFS:   Syslog('o', "Truncating sent file \"%s\"",FTND_SS(nm));
		    if ((fp=fopen(nm,"w"))) 
			fclose(fp);
		    else 
			WriteError("$Cannot truncate file \"%s\"",FTND_SS(nm));
		    break;

	case KFS:   Syslog('o', "Removing sent file \"%s\"",FTND_SS(nm));
		    if (unlink(nm) != 0) {
			if (errno == ENOENT)
			    Syslog('o', "Cannot unlink nonexistent file \"%s\"", FTND_SS(nm));
			else
			    WriteError("$Cannot unlink file \"%s\"", FTND_SS(nm));
		    }
		    break;

	default:    WriteError("execute_disposition: unknown disp %d for \"%s\"", fl->disposition,FTND_SS(nm));
		    break;
    }

    return;
}
Ejemplo n.º 17
0
int main(int argc, char* argv[]) {
	// Set the character locale, so we can produce proper output.
	setlocale(LC_CTYPE, "");

	// Create the pool that is used to allocate everything
	GuPool* pool = gu_new_pool();
	int status = EXIT_SUCCESS;
	if (argc != 4) {
		fprintf(stderr, "usage: %s pgf cat from_lang\n", argv[0]);
		status = EXIT_FAILURE;
		goto fail;
	}
	char* filename = argv[1];

	GuString cat = gu_str_string(argv[2], pool);

	GuString from_lang = gu_str_string(argv[3], pool);
	
	// Create an exception frame that catches all errors.
	GuExn* err = gu_new_exn(NULL, gu_kind(type), pool);

	// Read the PGF grammar.
	PgfPGF* pgf = pgf_read(filename, pool, err);

	// If an error occured, it shows in the exception frame
	if (!gu_ok(err)) {
		fprintf(stderr, "Reading PGF failed\n");
		status = EXIT_FAILURE;
		goto fail;
	}

	pgf_load_meta_child_probs(pgf, "../../../treebanks/PennTreebank/ParseEngAbs3.probs", pool, err);
	if (!gu_ok(err)) {
		fprintf(stderr, "Loading meta child probs failed\n");
		status = EXIT_FAILURE;
		goto fail;
	}

	// Look up the source and destination concrete categories
	PgfConcr* from_concr = pgf_get_language(pgf, from_lang);
	if (!from_concr) {
		fprintf(stderr, "Unknown language\n");
		status = EXIT_FAILURE;
		goto fail_concr;
	}
	
	// Register a callback for the literal category Symbol
	pgf_parser_add_literal(from_concr, gu_str_string("Symb", pool),
	                       &pgf_nerc_literal_callback);

	// We will keep the latest results in the 'ppool' and
	// we will iterate over them by using 'result'.
	GuPool* ppool = NULL;

	// The interactive translation loop.
	// XXX: This currently reads stdin directly, so it doesn't support
	// encodings properly. TODO: use a locale reader for input
	while (true) {
		char buf[4096];
		char* line = fgets(buf, sizeof(buf), stdin);
		if (line == NULL) {
			if (ferror(stdin)) {
				fprintf(stderr, "Input error\n");
				status = EXIT_FAILURE;
			}
			break;
		} else if (strcmp(line, "") == 0) {
			// End nicely on empty input
			break;
		}
		
		// We create a temporary pool for translating a single
		// sentence, so our memory usage doesn't increase over time.
		ppool = gu_new_pool();

		GuReader *rdr =
			gu_string_reader(gu_str_string(line, ppool), ppool);
		PgfLexer *lexer =
			pgf_new_simple_lexer(rdr, ppool);

		pgf_print_chunks(from_concr, cat, lexer, ppool);
		
		// Free all resources allocated during parsing and linearization
		gu_pool_free(ppool);
	}
fail_concr:
fail:
	gu_pool_free(pool);
	return status;
}
Ejemplo n.º 18
0
void print_results( FILE *stream, AS_INF *inf_ptr, BIRTH_DB *data,
       AS_INF_EXT *aie_ptr, BITS mode, NUM house_mode,
       DATA_PACKET *dpk, char *comment )
{
 COUNT i;
 AS_INF *inf;
 AS_INF_EXT *aiep;
 char buf1[60];
 const char *report;
 NUM maxp, file = -1, aspfile = -1, hsfile = -1, midfile = -1;
 int sign, cusp, k, global = -1, table = -1, ruler;
 static char fmt8[] = { "<%s:>\x80" };

 if ( mode & ASTEROID )
	maxp = CHIRON;
 else if ( mode & VERT_EAST )
    maxp = EAST_POINT;
 else
    maxp = PART_FORTU;

 if ( mode & TEXT ) {
    if ( mode & ASPECTS )
       aspfile = open_asp_files( ASPECT_FILE );
    file = open_files( PLANET_FILE );
    if ( mode & HOUSES )
       hsfile = open_files( HOUSE_FILE );
	if ( mode & (BASE_MID|HALF_MID|FULL_MID) )
	   midfile = open_asp_files( MIDPOINT_SIGN );
    }
 if ( mode & NOBIRTHTIM && ( dpk->rdp->rect_system == SOLARCHART ||
		 dpk->rdp->rect_system == FLATCHART ) )
    house_mode = EQUAL;
 table = get_tables( REPORT_NAME, &global );
 if ( table == -1 ) {
    er_close1:
    close_files( file );
    close_files_asp( aspfile );
    close_files( hsfile );
    close_files( midfile );
    return;
    }
 if ( dpk->chart_code & RELOC_CH )
    k = CHH_RELOC;
 else
    k = CHH_TITLE;
 if ( ( report = get_report( table, global, k ) ) == NULL ) {
    goto er_close1;
    }
 else
    output_title( stream, data->name, comment, "", (char *)report );
 if ( output_birth_head_group( stream, mode, data, table, house_mode,
						comment, dpk, global ) ) {
    goto er_close1;
    }
 rppl = get_report( table, global, CH__PLANET );
 rphs = get_report( table, global, CH__PLAN_HOUSE );
 rpah = get_report( table, global, CH__ASPECT_HD );
 rpas = get_report( table, global, CH__ASPECT );
 rpmsc = get_report( table, global, CH__MISC );
 if ( rppl == NULL || rphs == NULL || rpas == NULL || rpah == NULL || rpmsc == NULL ) {
    er_close2:
    close_tables( table, global );
    close_files( file );
    close_files_asp( aspfile );
    close_files( hsfile );
    close_files( midfile );
    return;
    }
 fputs("\n\n", stream );
 if ( ferror( stream ) ) {
    goto er_close2;
    }
 for ( i = 0, aiep = aie_ptr, inf = inf_ptr; i <= maxp; ++i, ++inf, ++aiep ) {
	 if ( !inf->calced )
		 continue;
	 if ( x_kb_check() )
	   break;
     print_entry( stream, inf, i, mode, file, aspfile, hsfile, midfile, aiep,
	       data->name, comment, table, global );
     if ( ferror( stream ) ) {
        goto er_close2;
        }
     }
 if ( mode & TEXT ) {
    close_files( file );
    close_files_asp( aspfile );
    close_files( hsfile );
    close_files( midfile );
    }
 if ( x_kb_check() )
    return;
 if ( mode & HOUSES ) {
    if ( mode & TEXT ) {
       if ( ( hsfile = open_files( SIGN_HOUSE_FILE ) ) == -1 )
	  mode &= ( 0xffff ^ TEXT );
       }
    if ( mode & HOUSES )
       out_do_house_cusps(stream,data->name, comment, "",
					table, global, house_cusps, CH__HOUSE_HEAD );
 if ( ( report = get_report( table, global, CH__HS_SGN_HED ) ) == NULL ) {
    er_close3:
    close_tables( table, global );
    close_files( hsfile );
    return;
    }
 else
    output_title( stream, data->name, comment, "", (char *)report );
 if ( ( report = get_report( table, global, CH__HOUSE_SIGN ) ) == NULL ) {
    goto er_close3;
    }
 if ( ( rphs = strdup( report )) == NULL )
    goto er_close3;
 for ( i = 1; i <= 12; ++i ) {
     if ( x_kb_check() )
	break;
     output_house_sign( stream, i, house_cusps[i], &cusp, &sign,
						     data->name, (char *)rphs );
     ruler = sign_rulers[sign];
	 if ( cusp == -1 ) {
	if ( mode & TEXT )
	   get_transfer_text( sign, i, hsfile, stream );
	   get_transfer_text( ruler, 13, hsfile, stream );
	}
     else {
	if ( mode & TEXT ) {
	   fprintf( stream, (char *)fmt8, sign_str( sign ) );
	   get_transfer_text( sign, i, hsfile, stream );
	   fprintf( stream, (char *)fmt8, sign_str( cusp ) );
	   get_transfer_text( cusp, i, hsfile, stream );
	   get_transfer_text( ruler, 13, hsfile, stream );
	   }
	}
     }
 if ( mode & TEXT )
    close_files( hsfile );
 }
 if ( x_kb_check() ) {
    close_tables( table, global );
    return;
    }
 close_tables( table, global );
 table = get_tables( SUMMARY_NAME, &global );
 if ( table == -1 )
    return;
 if ( mode & SUMMARY )
    print_summary(stream, mode, table, global, data->name, comment );
 close_tables( table, global );
}
Ejemplo n.º 19
0
/*=export_func  optionUsage
 * private:
 *
 * what:  Print usage text
 * arg:   + tOptions * + opts + program options descriptor +
 * arg:   + int        + exitCode + exit code for calling exit(3) +
 *
 * doc:
 *  This routine will print usage in both GNU-standard and AutoOpts-expanded
 *  formats.  The descriptor specifies the default, but AUTOOPTS_USAGE will
 *  over-ride this, providing the value of it is set to either "gnu" or
 *  "autoopts".  This routine will @strong{not} return.
 *
 *  If "exitCode" is "AO_EXIT_REQ_USAGE" (normally 64), then output will to
 *  to stdout and the actual exit code will be "EXIT_SUCCESS".
=*/
void
optionUsage(tOptions * opts, int usage_exit_code)
{
    int exit_code = (usage_exit_code == AO_EXIT_REQ_USAGE)
        ? EXIT_SUCCESS : usage_exit_code;

    displayEnum = false;
    set_usage_flags(opts, NULL);

    /*
     *  Paged usage will preset option_usage_fp to an output file.
     *  If it hasn't already been set, then set it to standard output
     *  on successful exit (help was requested), otherwise error out.
     *
     *  Test the version before obtaining pzFullUsage or pzShortUsage.
     *  These fields do not exist before revision 30.
     */
    {
        char const * pz;

        if (exit_code == EXIT_SUCCESS) {
            pz = (opts->structVersion >= 30 * 4096)
                ? opts->pzFullUsage : NULL;

            if (option_usage_fp == NULL)
                option_usage_fp = print_exit ? stderr : stdout;

        } else {
            pz = (opts->structVersion >= 30 * 4096)
                ? opts->pzShortUsage : NULL;

            if (option_usage_fp == NULL)
                option_usage_fp = stderr;
        }

        if (((opts->fOptSet & OPTPROC_COMPUTE) == 0) && (pz != NULL)) {
            if ((opts->fOptSet & OPTPROC_TRANSLATE) != 0)
                optionPrintParagraphs(pz, true, option_usage_fp);
            else
                fputs(pz, option_usage_fp);
            goto flush_and_exit;
        }
    }

    fprintf(option_usage_fp, opts->pzUsageTitle, opts->pzProgName);

    if ((exit_code == EXIT_SUCCESS) ||
        (! skip_misuse_usage(opts)))

        print_usage_details(opts, usage_exit_code);
    else
        print_offer_usage(opts);
    
 flush_and_exit:
    fflush(option_usage_fp);
    if (ferror(option_usage_fp) != 0)
        fserr_exit(opts->pzProgName, zwriting, (option_usage_fp == stdout)
                   ? zstdout_name : zstderr_name);

    option_exits(exit_code);
}
Ejemplo n.º 20
0
int load_env_file(const char *fname, char ***rl) {

        _cleanup_fclose_ FILE *f;
        _cleanup_strv_free_ char **m = NULL;
        _cleanup_free_ char *c = NULL;

        assert(fname);
        assert(rl);

        /* This reads an environment file, but will not complain about
         * any invalid assignments, that needs to be done by the
         * caller */

        f = fopen(fname, "re");
        if (!f)
                return -errno;

        while (!feof(f)) {
                char l[LINE_MAX], *p, *cs, *b;

                if (!fgets(l, sizeof(l), f)) {
                        if (ferror(f))
                                return -errno;

                        /* The previous line was a continuation line?
                         * Let's process it now, before we leave the
                         * loop */
                        if (c)
                                goto process;

                        break;
                }

                /* Is this a continuation line? If so, just append
                 * this to c, and go to next line right-away */
                cs = endswith(l, "\\\n");
                if (cs) {
                        *cs = '\0';
                        b = strappend(c, l);
                        if (!b)
                                return -ENOMEM;

                        free(c);
                        c = b;
                        continue;
                }

                /* If the previous line was a continuation line,
                 * append the current line to it */
                if (c) {
                        b = strappend(c, l);
                        if (!b)
                                return -ENOMEM;

                        free(c);
                        c = b;
                }

        process:
                p = strstrip(c ? c : l);

                if (*p && !strchr(COMMENTS, *p)) {
                        _cleanup_free_ char *u;
                        int k;

                        u = normalize_env_assignment(p);
                        if (!u)
                                return -ENOMEM;

                        k = strv_extend(&m, u);
                        if (k < 0)
                                return -ENOMEM;
                }

                free(c);
                c = NULL;
        }

        *rl = m;
        m = NULL;

        return 0;
}
Ejemplo n.º 21
0
MagickExport MagickBooleanType IdentifyImage(Image *image,FILE *file,
  const MagickBooleanType verbose)
{
#define IdentifyFormat "    %s:\n      min: " QuantumFormat  \
  " (%g)\n      max: " QuantumFormat " (%g)\n"  \
  "      mean: %g (%g)\n      standard deviation: %g (%g)\n"  \
  "      kurtosis: %g\n      skewness: %g\n"

  char
    color[MaxTextExtent],
    format[MaxTextExtent],
    key[MaxTextExtent];

  ColorspaceType
    colorspace;

  const char
    *artifact,
    *name,
    *property,
    *registry,
    *value;

  const MagickInfo
    *magick_info;

  const PixelPacket
    *pixels;

  double
    elapsed_time,
    user_time;

  ExceptionInfo
    *exception;

  ImageType
    type;

  long
    y;

  MagickBooleanType
    ping;

  register long
    i,
    x;

  unsigned long
    scale;

  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  if (file == (FILE *) NULL)
    file=stdout;
  *format='\0';
  elapsed_time=GetElapsedTime(&image->timer);
  user_time=GetUserTime(&image->timer);
  GetTimerInfo(&image->timer);
  if (verbose == MagickFalse)
    {
      /*
        Display summary info about the image.
      */
      if (*image->magick_filename != '\0')
        if (LocaleCompare(image->magick_filename,image->filename) != 0)
          (void) fprintf(file,"%s=>",image->magick_filename);
       if ((GetPreviousImageInList(image) == (Image *) NULL) &&
           (GetNextImageInList(image) == (Image *) NULL) && (image->scene == 0))
        (void) fprintf(file,"%s ",image->filename);
      else
        (void) fprintf(file,"%s[%lu] ",image->filename,image->scene);
      (void) fprintf(file,"%s ",image->magick);
      if ((image->magick_columns != 0) || (image->magick_rows != 0))
        if ((image->magick_columns != image->columns) ||
            (image->magick_rows != image->rows))
          (void) fprintf(file,"%lux%lu=>",image->magick_columns,
            image->magick_rows);
      (void) fprintf(file,"%lux%lu ",image->columns,image->rows);
      if ((image->page.width != 0) || (image->page.height != 0) ||
          (image->page.x != 0) || (image->page.y != 0))
        (void) fprintf(file,"%lux%lu%+ld%+ld ",image->page.width,
          image->page.height,image->page.x,image->page.y);
      (void) fprintf(file,"%lu-bit ",image->depth);
      if (image->type != UndefinedType)
        (void) fprintf(file,"%s ",MagickOptionToMnemonic(MagickTypeOptions,
          (long) image->type));
      if (image->storage_class == DirectClass)
        {
          (void) fprintf(file,"DirectClass ");
          if (image->total_colors != 0)
            {
              (void) FormatMagickSize(image->total_colors,MagickFalse,format);
              (void) fprintf(file,"%s ",format);
            }
        }
      else
        if (image->total_colors <= image->colors)
          (void) fprintf(file,"PseudoClass %luc ",image->colors);
        else
          (void) fprintf(file,"PseudoClass %lu=>%luc ",image->total_colors,
            image->colors);
      if (image->error.mean_error_per_pixel != 0.0)
        (void) fprintf(file,"%ld/%f/%fdb ",(long)
          (image->error.mean_error_per_pixel+0.5),
          image->error.normalized_mean_error,
          image->error.normalized_maximum_error);
      if (GetBlobSize(image) != 0)
        {
          (void) FormatMagickSize(GetBlobSize(image),MagickFalse,format);
          (void) fprintf(file,"%s ",format);
        }
      (void) fprintf(file,"%0.3fu %ld:%02ld.%03ld",user_time,(long)
        (elapsed_time/60.0),(long) floor(fmod(elapsed_time,60.0)),
        (long) (1000.0*(elapsed_time-floor(elapsed_time))));
      (void) fprintf(file,"\n");
      (void) fflush(file);
      return(ferror(file) != 0 ? MagickFalse : MagickTrue);
    }
  /*
    Display verbose info about the image.
  */
  exception=AcquireExceptionInfo();
  pixels=GetVirtualPixels(image,0,0,1,1,exception);
  exception=DestroyExceptionInfo(exception);
  ping=pixels == (const PixelPacket *) NULL ? MagickTrue : MagickFalse;
  type=GetImageType(image,&image->exception);
  (void) SignatureImage(image);
  (void) fprintf(file,"Image: %s\n",image->filename);
  if (*image->magick_filename != '\0')
    if (LocaleCompare(image->magick_filename,image->filename) != 0)
      {
        char
          filename[MaxTextExtent];

        GetPathComponent(image->magick_filename,TailPath,filename);
        (void) fprintf(file,"  Base filename: %s\n",filename);
      }
  magick_info=GetMagickInfo(image->magick,&image->exception);
  if ((magick_info == (const MagickInfo *) NULL) ||
      (*GetMagickDescription(magick_info) == '\0'))
    (void) fprintf(file,"  Format: %s\n",image->magick);
  else
    (void) fprintf(file,"  Format: %s (%s)\n",image->magick,
      GetMagickDescription(magick_info));
  (void) fprintf(file,"  Class: %s\n",MagickOptionToMnemonic(MagickClassOptions,
    (long) image->storage_class));
  (void) fprintf(file,"  Geometry: %lux%lu%+ld%+ld\n",image->columns,
    image->rows,image->tile_offset.x,image->tile_offset.y);
  if ((image->magick_columns != 0) || (image->magick_rows != 0))
    if ((image->magick_columns != image->columns) ||
        (image->magick_rows != image->rows))
      (void) fprintf(file,"  Base geometry: %lux%lu\n",image->magick_columns,
        image->magick_rows);
  if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
    {
      (void) fprintf(file,"  Resolution: %gx%g\n",image->x_resolution,
        image->y_resolution);
      (void) fprintf(file,"  Print size: %gx%g\n",(double) image->columns/
        image->x_resolution,(double) image->rows/image->y_resolution);
    }
  (void) fprintf(file,"  Units: %s\n",MagickOptionToMnemonic(
    MagickResolutionOptions,(long) image->units));
  (void) fprintf(file,"  Type: %s\n",MagickOptionToMnemonic(MagickTypeOptions,
    (long) type));
  if (image->type != UndefinedType)
    (void) fprintf(file,"  Base type: %s\n",MagickOptionToMnemonic(
      MagickTypeOptions,(long) image->type));
  (void) fprintf(file,"  Endianess: %s\n",MagickOptionToMnemonic(
    MagickEndianOptions,(long) image->endian));
  /*
    Detail channel depth and extrema.
  */
  (void) fprintf(file,"  Colorspace: %s\n",MagickOptionToMnemonic(
    MagickColorspaceOptions,(long) image->colorspace));
  if (ping == MagickFalse)
    {
      ChannelStatistics
        *channel_statistics;

      unsigned long
        depth;

      depth=GetImageDepth(image,&image->exception);
      if (image->depth == depth)
        (void) fprintf(file,"  Depth: %lu-bit\n",image->depth);
      else
        (void) fprintf(file,"  Depth: %lu/%lu-bit\n",image->depth,depth);
      channel_statistics=GetImageChannelStatistics(image,&image->exception);
      (void) fprintf(file,"  Channel depth:\n");
      colorspace=image->colorspace;
      if (IsGrayImage(image,&image->exception) != MagickFalse)
        colorspace=GRAYColorspace;
      switch (colorspace)
      {
        case RGBColorspace:
        default:
        {
          (void) fprintf(file,"    red: %lu-bit\n",
            channel_statistics[RedChannel].depth);
          (void) fprintf(file,"    green: %lu-bit\n",
            channel_statistics[GreenChannel].depth);
          (void) fprintf(file,"    blue: %lu-bit\n",
            channel_statistics[BlueChannel].depth);
          if (image->matte != MagickFalse)
            (void) fprintf(file,"    alpha: %lu-bit\n",
              channel_statistics[OpacityChannel].depth);
          break;
        }
        case CMYKColorspace:
        {
          (void) fprintf(file,"    cyan: %lu-bit\n",
            channel_statistics[CyanChannel].depth);
          (void) fprintf(file,"    magenta: %lu-bit\n",
            channel_statistics[MagentaChannel].depth);
          (void) fprintf(file,"    yellow: %lu-bit\n",
            channel_statistics[YellowChannel].depth);
          (void) fprintf(file,"    black: %lu-bit\n",
            channel_statistics[BlackChannel].depth);
          if (image->matte != MagickFalse)
            (void) fprintf(file,"    alpha: %lu-bit\n",
              channel_statistics[OpacityChannel].depth);
          break;
        }
        case GRAYColorspace:
        {
          (void) fprintf(file,"    gray: %lu-bit\n",
            channel_statistics[GrayChannel].depth);
          if (image->matte != MagickFalse)
            (void) fprintf(file,"    alpha: %lu-bit\n",
              channel_statistics[OpacityChannel].depth);
          break;
        }
      }
      scale=1;
      if (image->depth <= MAGICKCORE_QUANTUM_DEPTH)
        scale=QuantumRange/((unsigned long) QuantumRange >> ((unsigned long)
          MAGICKCORE_QUANTUM_DEPTH-image->depth));
      (void) fprintf(file,"  Channel statistics:\n");
      switch (colorspace)
      {
        case RGBColorspace:
        default:
        {
          (void) fprintf(file,IdentifyFormat,"red",(Quantum)
            (channel_statistics[RedChannel].minima/scale),(double)
            channel_statistics[RedChannel].minima/(double) QuantumRange,
            (Quantum) (channel_statistics[RedChannel].maxima/scale),(double)
            channel_statistics[RedChannel].maxima/(double) QuantumRange,
            channel_statistics[RedChannel].mean/(double) scale,
            channel_statistics[RedChannel].mean/(double) QuantumRange,
            channel_statistics[RedChannel].standard_deviation/(double) scale,
            channel_statistics[RedChannel].standard_deviation/(double)
            QuantumRange,channel_statistics[RedChannel].kurtosis,
            channel_statistics[RedChannel].skewness);
          (void) fprintf(file,IdentifyFormat,"green",(Quantum)
            (channel_statistics[GreenChannel].minima/scale),(double)
            channel_statistics[GreenChannel].minima/(double) QuantumRange,
            (Quantum) (channel_statistics[GreenChannel].maxima/scale),(double)
            channel_statistics[GreenChannel].maxima/(double) QuantumRange,
            channel_statistics[GreenChannel].mean/(double) scale,
            channel_statistics[GreenChannel].mean/(double) QuantumRange,
            channel_statistics[GreenChannel].standard_deviation/(double) scale,
            channel_statistics[GreenChannel].standard_deviation/(double)
            QuantumRange,
            channel_statistics[GreenChannel].kurtosis,
            channel_statistics[GreenChannel].skewness);
          (void) fprintf(file,IdentifyFormat,"blue",(Quantum)
            (channel_statistics[BlueChannel].minima/scale),(double)
            channel_statistics[BlueChannel].minima/(double) QuantumRange,
            (Quantum) (channel_statistics[BlueChannel].maxima/scale),(double)
            channel_statistics[BlueChannel].maxima/(double) QuantumRange,
            channel_statistics[BlueChannel].mean/(double) scale,
            channel_statistics[BlueChannel].mean/(double) QuantumRange,
            channel_statistics[BlueChannel].standard_deviation/(double) scale,
            channel_statistics[BlueChannel].standard_deviation/(double)
            QuantumRange,channel_statistics[BlueChannel].kurtosis,
            channel_statistics[BlueChannel].skewness);
          break;
        }
        case CMYKColorspace:
        {
          (void) fprintf(file,IdentifyFormat,"cyan",(Quantum)
            (channel_statistics[CyanChannel].minima/scale),(double)
            channel_statistics[CyanChannel].minima/(double) QuantumRange,
            (Quantum) (channel_statistics[CyanChannel].maxima/scale),(double)
            channel_statistics[CyanChannel].maxima/(double) QuantumRange,
            channel_statistics[CyanChannel].mean/(double) scale,
            channel_statistics[CyanChannel].mean/(double) QuantumRange,
            channel_statistics[CyanChannel].standard_deviation/(double) scale,
            channel_statistics[CyanChannel].standard_deviation/(double)
            QuantumRange,channel_statistics[CyanChannel].kurtosis,
            channel_statistics[CyanChannel].skewness);
          (void) fprintf(file,IdentifyFormat,"magenta",(Quantum)
            (channel_statistics[MagentaChannel].minima/scale),(double)
            channel_statistics[MagentaChannel].minima/(double) QuantumRange,
            (Quantum) (channel_statistics[MagentaChannel].maxima/scale),(double)
            channel_statistics[MagentaChannel].maxima/(double) QuantumRange,
            channel_statistics[MagentaChannel].mean/(double) scale,
            channel_statistics[MagentaChannel].mean/(double) QuantumRange,
            channel_statistics[MagentaChannel].standard_deviation/(double)
            scale,channel_statistics[MagentaChannel].standard_deviation/(double)
            QuantumRange,channel_statistics[MagentaChannel].kurtosis,
            channel_statistics[MagentaChannel].skewness);
          (void) fprintf(file,IdentifyFormat,"yellow",(Quantum)
            (channel_statistics[YellowChannel].minima/scale),(double)
            channel_statistics[YellowChannel].minima/(double) QuantumRange,
            (Quantum) (channel_statistics[YellowChannel].maxima/scale),(double)
            channel_statistics[YellowChannel].maxima/(double) QuantumRange,
            channel_statistics[YellowChannel].mean/(double) scale,
            channel_statistics[YellowChannel].mean/(double) QuantumRange,
            channel_statistics[YellowChannel].standard_deviation/(double) scale,
            channel_statistics[YellowChannel].standard_deviation/(double)
            QuantumRange,channel_statistics[YellowChannel].kurtosis,
            channel_statistics[YellowChannel].skewness);
          (void) fprintf(file,IdentifyFormat,"black",(Quantum)
            (channel_statistics[BlackChannel].minima/scale),(double)
            channel_statistics[BlackChannel].minima/(double) QuantumRange,
            (Quantum) (channel_statistics[BlackChannel].maxima/scale),(double)
            channel_statistics[BlackChannel].maxima/(double) QuantumRange,
            channel_statistics[BlackChannel].mean/(double) scale,
            channel_statistics[BlackChannel].mean/(double) QuantumRange,
            channel_statistics[BlackChannel].standard_deviation/(double) scale,
            channel_statistics[BlackChannel].standard_deviation/(double)
            QuantumRange,channel_statistics[BlackChannel].kurtosis,
            channel_statistics[BlackChannel].skewness);
          break;
        }
        case GRAYColorspace:
        {
          (void) fprintf(file,IdentifyFormat,"gray",(Quantum)
            (channel_statistics[GrayChannel].minima/scale),(double)
            channel_statistics[GrayChannel].minima/(double) QuantumRange,
            (Quantum) (channel_statistics[GrayChannel].maxima/scale),(double)
            channel_statistics[GrayChannel].maxima/(double) QuantumRange,
            channel_statistics[GrayChannel].mean/(double) scale,
            channel_statistics[GrayChannel].mean/(double) QuantumRange,
            channel_statistics[GrayChannel].standard_deviation/(double) scale,
            channel_statistics[GrayChannel].standard_deviation/(double)
            QuantumRange,channel_statistics[GrayChannel].kurtosis,
            channel_statistics[GrayChannel].skewness);
          break;
        }
      }
      if (image->matte != MagickFalse)
        (void) fprintf(file,IdentifyFormat,"alpha",(Quantum)
          ((QuantumRange-channel_statistics[AlphaChannel].maxima)/scale),
          (double) (QuantumRange-channel_statistics[AlphaChannel].maxima)/
          (double) QuantumRange, (Quantum) ((QuantumRange-
          channel_statistics[AlphaChannel].minima)/scale),(double)
          (QuantumRange-channel_statistics[AlphaChannel].minima)/(double)
          QuantumRange,(QuantumRange-channel_statistics[AlphaChannel].mean)/
          (double) scale,(QuantumRange-channel_statistics[AlphaChannel].mean)/
          (double) QuantumRange,
          channel_statistics[AlphaChannel].standard_deviation/(double) scale,
          channel_statistics[AlphaChannel].standard_deviation/(double)
          QuantumRange,channel_statistics[AlphaChannel].kurtosis,
          channel_statistics[AlphaChannel].skewness);
      if (colorspace != GRAYColorspace)
        {
          (void) fprintf(file,"  Image statistics:\n");
          (void) fprintf(file,IdentifyFormat,"Overall",(Quantum)
            (channel_statistics[AllChannels].minima/scale),(double)
            channel_statistics[AllChannels].minima/(double) QuantumRange,
            (Quantum) (channel_statistics[AllChannels].maxima/scale),(double)
            channel_statistics[AllChannels].maxima/(double) QuantumRange,
            channel_statistics[AllChannels].mean/(double) scale,
            channel_statistics[AllChannels].mean/(double) QuantumRange,
            channel_statistics[AllChannels].standard_deviation/(double) scale,
            channel_statistics[AllChannels].standard_deviation/(double)
            QuantumRange,channel_statistics[AllChannels].kurtosis,
            channel_statistics[AllChannels].skewness);
        }
      channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
        channel_statistics);
      if (image->colorspace == CMYKColorspace)
        (void) fprintf(file,"  Total ink density: %.0f%%\n",100.0*
          GetImageTotalInkDensity(image)/(double) QuantumRange);
      x=0;
      if (image->matte != MagickFalse)
        {
          register const IndexPacket
            *indexes;

          register const PixelPacket
            *p;

          p=(PixelPacket *) NULL;
          indexes=(IndexPacket *) NULL;
          for (y=0; y < (long) image->rows; y++)
          {
            p=GetVirtualPixels(image,0,y,image->columns,1,exception);
            if (p == (const PixelPacket *) NULL)
              break;
            indexes=GetVirtualIndexQueue(image);
            for (x=0; x < (long) image->columns; x++)
            {
              if (p->opacity == (Quantum) TransparentOpacity)
                break;
              p++;
            }
            if (x < (long) image->columns)
              break;
          }
          if ((x < (long) image->columns) || (y < (long) image->rows))
            {
              char
                tuple[MaxTextExtent];

              MagickPixelPacket
                pixel;

              GetMagickPixelPacket(image,&pixel);
              SetMagickPixelPacket(image,p,indexes+x,&pixel);
              (void) QueryMagickColorname(image,&pixel,SVGCompliance,tuple,
                &image->exception);
              (void) fprintf(file,"  Alpha: %s ",tuple);
              GetColorTuple(&pixel,MagickTrue,tuple);
              (void) fprintf(file,"  %s\n",tuple);
            }
        }
      if (ping == MagickFalse)
        {
          artifact=GetImageArtifact(image,"identify:unique");
          if ((artifact != (const char *) NULL) &&
              (IsMagickTrue(artifact) != MagickFalse))
            (void) fprintf(file,"  Colors: %lu\n",GetNumberColors(image,
              (FILE *) NULL,&image->exception));
          if (IsHistogramImage(image,&image->exception) != MagickFalse)
            {
              (void) fprintf(file,"  Histogram:\n");
              (void) GetNumberColors(image,file,&image->exception);
            }
        }
    }
Ejemplo n.º 22
0
/* Decompress from file source to file dest until stream ends or EOF.
   inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
   allocated for processing, Z_DATA_ERROR if the deflate data is
   invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
   the version of the library linked do not match, or Z_ERRNO if there
   is an error reading or writing the files. */
static int inf(FILE *source, FILE *dest, z_stream *strm,
	       unsigned char *in, unsigned char *out)
{
	int ret = Z_OK;
	int rc;
	long start_offs;
	long read_offs = 0;
	long have;

	strm->avail_in = 0;
	strm->next_in = Z_NULL;

	start_offs = ftell(source);
	read_offs = 0;

	/* decompress until deflate stream ends or end of file */
	do {
		strm->avail_in = fread(in, 1, CHUNK_i, source);
		if (ferror(source)) {
			fprintf(stderr, "fread error\n");
			return Z_ERRNO;
		}
		if (0 == strm->avail_in)
			break;
		strm->next_in = in;
__more_inf:
		/* run inflate() on input until output buffer not full */
		do {
			strm->avail_out = CHUNK_o;
			strm->next_out = out;
			ret = inflate(strm, Z_NO_FLUSH /* Z_SYNC_FLUSH */);
			assert(ret != Z_STREAM_ERROR);	/* not clobbered */

			switch (ret) {
			case Z_OK:
				/* Need to continue with Read more data */
				break;
			case Z_STREAM_END:
				read_offs += strm->total_in;
				break;
			case Z_NEED_DICT:
				fprintf(stderr, "NEED Dict........\n");
				ret = Z_DATA_ERROR;	/* and fall through */
			case Z_DATA_ERROR:
			case Z_MEM_ERROR:
				fprintf(stderr, "Fault..... %d\n", ret);
				return ret;
			}
			have = CHUNK_o - strm->avail_out;
			if (fwrite(out, 1, have, dest) != (size_t)have ||
				ferror(dest)) {
				fprintf(stderr, "fwrite fault\n");
				return Z_ERRNO;
			}
		} while (strm->avail_out == 0);
		/* done when inflate() says it's done */
	} while (ret != Z_STREAM_END);

	/* FIXME: this goto and the limit check is not nice. */
	if (strm->avail_in > (16 * 1024)) {
		inflateReset(strm);	/* reset and continue */
		goto __more_inf;
	}

	/* Set the file position right after the absorbed input */
	start_offs += read_offs;	/* Add to seek offset */
	rc = fseek(source, start_offs, SEEK_SET);
	if (rc == -1)
		fprintf(stderr, "err: fseek rc=%d\n", rc);

	inflateReset(strm);
	return ret;
}
Ejemplo n.º 23
0
/*
 * ex_mkexrc -- :mkexrc[!] [file]
 *
 * Create (or overwrite) a .exrc file with the current info.
 *
 * PUBLIC: int ex_mkexrc __P((SCR *, EXCMD *));
 */
int
ex_mkexrc(SCR *sp, EXCMD *cmdp)
{
	struct stat sb;
	FILE *fp;
	int fd, sverrno;
	char *fname;
	size_t flen;

	switch (cmdp->argc) {
	case 0:
		fname = _PATH_EXRC;
		break;
	case 1:
		INT2CHAR(sp, cmdp->argv[0]->bp, cmdp->argv[0]->len + 1, 
			    fname, flen);
		set_alt_name(sp, fname);
		break;
	default:
		abort();
	}

	if (!FL_ISSET(cmdp->iflags, E_C_FORCE) && !stat(fname, &sb)) {
		msgq_str(sp, M_ERR, fname,
		    "137|%s exists, not written; use ! to override");
		return (1);
	}

	/* Create with max permissions of rw-r--r--. */
	if ((fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY,
	    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
		msgq_str(sp, M_SYSERR, fname, "%s");
		return (1);
	}

	if ((fp = fdopen(fd, "w")) == NULL) {
		sverrno = errno;
		(void)close(fd);
		goto e2;
	}

	if (seq_save(sp, fp, "abbreviate ", SEQ_ABBREV) || ferror(fp))
		goto e1;
	if (seq_save(sp, fp, "map ", SEQ_COMMAND) || ferror(fp))
		goto e1;
	if (seq_save(sp, fp, "map! ", SEQ_INPUT) || ferror(fp))
		goto e1;
	if (opts_save(sp, fp) || ferror(fp))
		goto e1;
	if (fclose(fp)) {
		sverrno = errno;
		goto e2;
	}

	msgq_str(sp, M_INFO, fname, "138|New exrc file: %s");
	return (0);

e1:	sverrno = errno;
	(void)fclose(fp);
e2:	errno = sverrno;
	msgq_str(sp, M_SYSERR, fname, "%s");
	return (1);
}
Ejemplo n.º 24
0
/**
 * FIXME Verbose mode missing yet.
 */
static int do_list_contents(FILE *fp, char *out_f, int list_contents)
{
	int rc;
	struct stat st;
	uint32_t d, crc32, size, compressed_size;
	float ratio = 0.0;
	z_stream strm;
	uint8_t in[4096];
	uint8_t out[4096];
	gz_header head;
	uint8_t extra[64 * 1024];
	uint8_t comment[1024];
	uint8_t name[1024];
	int window_bits = 31;	/* GZIP */
	const char *mon[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
			      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

	rc = fstat(fileno(fp), &st);
	if (rc != 0)
		return rc;

	memset(&strm, 0, sizeof(strm));
	strm.avail_in = 0;
	strm.next_in = Z_NULL;
	rc = inflateInit2(&strm, window_bits);
	if (Z_OK != rc)
		return rc;

	strm.next_out = out;
	strm.avail_out = sizeof(out);
	strm.next_in = in;
	strm.avail_in = fread(in, 1, sizeof(in), fp);
	if (ferror(fp))
		return Z_ERRNO;

	head.extra = extra;
	head.extra_len = 0;
	head.extra_max = sizeof(extra);

	head.comment = comment;
	head.comm_max = sizeof(comment);

	head.name = name;
	head.name_max = sizeof(name);

	rc = inflateGetHeader(&strm, &head);
	if (Z_OK != rc) {
		fprintf(stderr, "err: Cannot read gz header! rc=%d\n", rc);
		return rc;
	}

	rc = inflate(&strm, Z_BLOCK);
	if (Z_OK != rc) {
		fprintf(stderr, "err: inflate(Z_BLOCK) failed rc=%d\n", rc);
		return rc;
	}

	if (head.done == 0) {
		fprintf(stderr, "err: gzip header not entirely decoded! "
			"total_in=%ld total_out=%ld head.done=%d\n",
			strm.total_in, strm.total_out, head.done);
		return Z_DATA_ERROR;
	}

	rc = fseek(fp, st.st_size - 2 * sizeof(uint32_t), SEEK_SET);
	if (rc != 0)
		return rc;

	rc = fread(&d, sizeof(d), 1, fp);
	if (rc != 1)
		return -1;
	crc32 = __le32_to_cpu(d);

	rc = fread(&d, sizeof(d), 1, fp);
	if (rc != 1)
		return -1;
	size = __le32_to_cpu(d);

	/* Compressed size is total file size reduced by gzip header
	   size and 8 bytes for the gzip trailer. */
	compressed_size = st.st_size - strm.total_in - 8;
	if (size)
		ratio = 100 - (float)compressed_size * 100 / size;

	if (!verbose) {
		fprintf(stderr,
			"         compressed        uncompressed  ratio "
			"uncompressed_name\n"
			"%19lld %19d  %2.2f%% %s\n",
			(long long)st.st_size, size, ratio,
			out_f);
	} else {
		time_t t = time(NULL);
		struct tm *tm = localtime(&t);
		/* (const time_t *)&head.time */

		fprintf(stderr, "method  crc     date  time           "
			"compressed        uncompressed  ratio "
			"uncompressed_name\n"
			"%s %x %s %2d %d:%d %19lld %19d  %2.2f%% %s\n",
			"defla", crc32,
			mon[tm->tm_mon], tm->tm_mday, tm->tm_hour, tm->tm_min,
			(long long)st.st_size, size, ratio,
			out_f);
	}

	if (list_contents > 1)
		do_print_gzip_hdr(&head, stderr);

	return 0;
}
Ejemplo n.º 25
0
int
main(int argc, char **argv) {
	isc_result_t result;
	isc_mem_t *mctx = NULL;
	isc_log_t *lctx = NULL;
	isc_logconfig_t *lcfg = NULL;
	isc_logdestination_t destination;
	cfg_parser_t *pctx = NULL;
	cfg_obj_t *cfg = NULL;
	cfg_type_t *type = NULL;
	isc_boolean_t grammar = ISC_FALSE;
	isc_boolean_t memstats = ISC_FALSE;
	char *filename = NULL;

	RUNTIME_CHECK(isc_mem_create(0, 0, &mctx) == ISC_R_SUCCESS);

	result = isc_log_create(mctx, &lctx, &lcfg);
	check_result(result, "isc_log_create()");
	isc_log_setcontext(lctx);

	/*
	 * Create and install the default channel.
	 */
	destination.file.stream = stderr;
	destination.file.name = NULL;
	destination.file.versions = ISC_LOG_ROLLNEVER;
	destination.file.maximum_size = 0;
	result = isc_log_createchannel(lcfg, "_default",
				       ISC_LOG_TOFILEDESC,
				       ISC_LOG_DYNAMIC,
				       &destination, ISC_LOG_PRINTTIME);
	check_result(result, "isc_log_createchannel()");
	result = isc_log_usechannel(lcfg, "_default", NULL, NULL);
	check_result(result, "isc_log_usechannel()");

	/*
	 * Set the initial debug level.
	 */
	isc_log_setdebuglevel(lctx, 2);

	if (argc < 3)
		usage();

	while (argc > 1) {
		if (strcmp(argv[1], "--grammar") == 0) {
			grammar = ISC_TRUE;
		} else if (strcmp(argv[1], "--memstats") == 0) {
			memstats = ISC_TRUE;
		} else if (strcmp(argv[1], "--named") == 0) {
			type = &cfg_type_namedconf;
		} else if (strcmp(argv[1], "--rndc") == 0) {
			type = &cfg_type_rndcconf;
		} else if (argv[1][0] == '-') {
			usage();
		} else {
			filename = argv[1];
		}
		argv++, argc--;
	}

	if (grammar) {
		if (type == NULL)
			usage();
		cfg_print_grammar(type, output, NULL);
	} else {
		if (type == NULL || filename == NULL)
			usage();
		RUNTIME_CHECK(cfg_parser_create(mctx, lctx, &pctx) == ISC_R_SUCCESS);

		result = cfg_parse_file(pctx, filename, type, &cfg);

		fprintf(stderr, "read config: %s\n", isc_result_totext(result));

		if (result != ISC_R_SUCCESS)
			exit(1);

		cfg_print(cfg, output, NULL);

		cfg_obj_destroy(pctx, &cfg);

		cfg_parser_destroy(&pctx);
	}

	isc_log_destroy(&lctx);
	if (memstats)
		isc_mem_stats(mctx, stderr);
	isc_mem_destroy(&mctx);

	fflush(stdout);
	if (ferror(stdout)) {
		fprintf(stderr, "write error\n");
		return (1);
	} else
		return (0);
}
Ejemplo n.º 26
0
/* compress or decompress from stdin to stdout */
int main(int argc, char **argv)
{
	int rc = Z_OK;
	bool compress = true;
	int list_contents = 0;
	bool force = false;
	bool quiet __attribute__((unused)) = false;
	int window_bits = 31;	/* GZIP */
	int level = Z_DEFAULT_COMPRESSION;
	char *prog = basename(argv[0]);
	const char *in_f = NULL;
	char out_f[PATH_MAX];
	FILE *i_fp = stdin;
	FILE *o_fp = NULL;
	const char *suffix = "gz";
	int force_software = 0;
	int cpu = -1;
	unsigned char *in = NULL;
	unsigned char *out = NULL;
	z_stream strm;
	const char *name = NULL;
	char *comment = NULL;
	const char *extra_fname = NULL;
	uint8_t *extra = NULL;
	int extra_len = 0;
	struct stat s;
	const char *accel = "GENWQE";
	const char *accel_env = getenv("ZLIB_ACCELERATOR");
	int card_no = 0;
	const char *card_no_env = getenv("ZLIB_CARD");

	/* Use environment variables as defaults. Command line options
	   can than overrule this. */
	if (accel_env != NULL)
		accel = accel_env;

	if (card_no_env != NULL)
		card_no = atoi(card_no_env);

	/* avoid end-of-line conversions */
	SET_BINARY_MODE(stdin);
	SET_BINARY_MODE(stdout);

	if (strstr(prog, "gunzip") != 0)
		compress = false;

	while (1) {
		int ch;
		int option_index = 0;
		static struct option long_options[] = {
			{ "stdout",	 no_argument,       NULL, 'c' },
			{ "decompress",  no_argument,       NULL, 'd' },
			{ "force",       no_argument,       NULL, 'f' },
			{ "help",	 no_argument,       NULL, 'h' },

			/* list */
			{ "list",	 no_argument,	    NULL, 'l' },
			{ "license",     no_argument,       NULL, 'L' },
			{ "suffix",      required_argument, NULL, 'S' },
			{ "verbose",	 no_argument,       NULL, 'v' },
			{ "version",	 no_argument,       NULL, 'V' },
			{ "fast",	 no_argument,       NULL, '1' },
			{ "best",	 no_argument,       NULL, '9' },

			/* our own options */
			{ "cpu",	 required_argument, NULL, 'X' },
			{ "accelerator-type", required_argument, NULL, 'A' },
			{ "card_no",	 required_argument, NULL, 'B' },
			{ "software",	 no_argument,	    NULL, 's' },
			{ "extra",	 required_argument, NULL, 'E' },
			{ "name",	 required_argument, NULL, 'N' },
			{ "comment",	 required_argument, NULL, 'C' },
			{ "i_bufsize",   required_argument, NULL, 'i' },
			{ "o_bufsize",   required_argument, NULL, 'o' },
			{ 0,		 no_argument,       NULL, 0   },
		};

		ch = getopt_long(argc, argv,
				 "E:N:C:cdfqhlLsS:vV123456789?i:o:X:A:B:",
				 long_options, &option_index);
		if (ch == -1)    /* all params processed ? */
			break;

		switch (ch) {

		case 'X':
			cpu = strtoul(optarg, NULL, 0);
			break;
		case 'A':
			accel = optarg;
			break;
		case 'B':
			card_no = strtol(optarg, (char **)NULL, 0);
			break;

		case 'E':
			extra_fname = optarg;
			break;
		case 'N':
			name = optarg;
			break;
		case 'C':
			comment = optarg;
			break;
		case 'd':
			compress = false;
			break;
		case 'f':
			force = true;
			break;
		case 'q':
			/* Currently does nothing, zless needs it */
			quiet = true;
			break;
		case 'c':
			o_fp = stdout;
			break;
		case 'S':
			suffix = optarg;
			break;
		case 's':
			force_software = true;
			break;
		case 'l':
			list_contents++;
			break;
		case '1':
			level = Z_BEST_SPEED;
			break;
		case '2':
			level = 2;
			break;
		case '3':
			level = 3;
			break;
		case '4':
			level = 4;
			break;
		case '5':
			level = 5;
			break;
		case '6':
			level = 6;
			break;
		case '7':
			level = 7;
			break;
		case '8':
			level = 8;
			break;
		case '9':
			level = Z_BEST_COMPRESSION;
			break;
		case 'v':
			verbose++;
			break;
		case 'V':
			fprintf(stdout, "%s\n", version);
			exit(EXIT_SUCCESS);
			break;
		case 'i':
			CHUNK_i = str_to_num(optarg);
			break;
		case 'o':
			CHUNK_o = str_to_num(optarg);
			break;
		case 'L':
			userinfo(stdout, prog, version);
			exit(EXIT_SUCCESS);
			break;
		case 'h':
		case '?':
			usage(stdout, prog, argc, argv);
			exit(EXIT_SUCCESS);
			break;
		}
	}

	if (cpu != -1)
		pin_to_cpu(cpu);

	if (force_software) {
		zlib_set_inflate_impl(ZLIB_SW_IMPL);
		zlib_set_deflate_impl(ZLIB_SW_IMPL);
	} else {
		zlib_set_accelerator(accel, card_no);
		zlib_set_inflate_impl(ZLIB_HW_IMPL);
		zlib_set_deflate_impl(ZLIB_HW_IMPL);
	}

	/* FIXME loop over this ... */
	if (optind < argc) {      /* input file */
		in_f = argv[optind++];

		i_fp = fopen(in_f, "r");
		if (!i_fp) {
			pr_err("%s\n", strerror(errno));
			print_args(stderr, argc, argv);
			exit(EX_ERRNO);
		}

		rc = lstat(in_f, &s);
		if ((rc == 0) && S_ISLNK(s.st_mode)) {
			pr_err("%s: Too many levels of symbolic links\n",
			       in_f);
			exit(EXIT_FAILURE);
		}

		if (list_contents) {
			rc = strip_ending(out_f, in_f, PATH_MAX, suffix);
			if (rc < 0) {
				pr_err("No .%s file!\n", suffix);
				print_args(stderr, argc, argv);
				exit(EXIT_FAILURE);
			}

			rc = do_list_contents(i_fp, out_f, list_contents);
			if (rc != 0) {
				pr_err("Unable to list contents.\n");
				print_args(stderr, argc, argv);
				exit(EXIT_FAILURE);
			}
			fclose(i_fp);
			exit(EXIT_SUCCESS);
		}
	}

	if (in_f == NULL)
		o_fp = stdout;	/* should not be a terminal! */

	if (o_fp == NULL) {
		if (compress)
			snprintf(out_f, PATH_MAX, "%s.%s", in_f, suffix);
		else {
			rc = strip_ending(out_f, in_f, PATH_MAX, suffix);
			if (rc < 0) {
				pr_err("No .%s file!\n", suffix);
				print_args(stderr, argc, argv);
				exit(EXIT_FAILURE);
			}
		}

		rc = stat(out_f, &s);
		if (!force && (rc == 0)) {
			pr_err("File %s already exists!\n", out_f);
			print_args(stderr, argc, argv);
			exit(EX_ERRNO);
		}

		o_fp = fopen(out_f, "w+");
		if (!o_fp) {
			pr_err("Cannot open output file %s: %s\n", out_f,
			       strerror(errno));
			print_args(stderr, argc, argv);
			exit(EX_ERRNO);
		}

		/* get mode settings for existing file and ... */
		rc = fstat(fileno(i_fp), &s);
		if (rc == 0) {
			rc = fchmod(fileno(o_fp), s.st_mode);
			if (rc != 0) {
				pr_err("Cannot set mode %s: %s\n", out_f,
				       strerror(errno));
				exit(EX_ERRNO);
			}
		} else /* else ignore ... */
			pr_err("Cannot set mode %s: %s\n", out_f,
			       strerror(errno));


		/* If output does not go to stdout and a filename is
		   given, set it */
		if (name == NULL)
			name = in_f;
	}

	if (isatty(fileno(o_fp))) {
		pr_err("Output must not be a terminal!\n");
		print_args(stderr, argc, argv);
		exit(EXIT_FAILURE);
	}

	if (optind != argc) {   /* now it must fit */
		usage(stderr, prog, argc, argv);
		exit(EXIT_FAILURE);
	}

	in = malloc(CHUNK_i);	/* This is the bigger Buffer by default */
	if (NULL == in) {
		pr_err("%s\n", strerror(errno));
		print_args(stderr, argc, argv);
		exit(EXIT_FAILURE);
	}

	out = malloc(CHUNK_o);	/* This is the smaller Buffer by default */
	if (NULL == out) {
		pr_err("%s\n", strerror(errno));
		print_args(stderr, argc, argv);
		exit(EXIT_FAILURE);
	}

	/* allocate inflate state */
	memset(&strm, 0, sizeof(strm));
	strm.zalloc = Z_NULL;
	strm.zfree = Z_NULL;
	strm.opaque = Z_NULL;

	if (compress) {
		gz_header head;
		struct timeval tv;

		if (extra_fname) {
			extra_len = file_size(extra_fname);
			if (extra_len <= 0) {
				rc = extra_len;
				goto err_out;
			}

			extra = malloc(extra_len);
			if (extra == NULL) {
				rc = -ENOMEM;
				goto err_out;
			}

			rc = file_read(extra_fname, extra, extra_len);
			if (rc != 1) {
				fprintf(stderr, "err: Unable to read extra "
					"data rc=%d\n", rc);
				free(extra);
				goto err_out;
			}

			hexdump(stderr, extra, extra_len);
		}

		/* --------------- DEFALTE ----------------- */
		rc = deflateInit2(&strm, level, Z_DEFLATED, window_bits, 8,
				  Z_DEFAULT_STRATEGY);
		if (Z_OK != rc)
			goto err_out;

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

		gettimeofday(&tv, NULL);
		head.time = tv.tv_sec;
		head.os = 0x03;

		if (extra != NULL) {
			head.extra = extra;
			head.extra_len = extra_len;
			head.extra_max = extra_len;
		}
		if (comment != NULL) {
			head.comment = (Bytef *)comment;
			head.comm_max = strlen(comment) + 1;
		}
		if (name != NULL) {
			head.name = (Bytef *)name;
			head.name_max = strlen(name) + 1;
		}

		rc = deflateSetHeader(&strm, &head);
		if (Z_OK != rc) {
			fprintf(stderr, "err: Cannot set gz header! rc=%d\n",
				rc);
			deflateEnd(&strm);
			goto err_out;
		}

		/* do compression if no arguments */
		rc = def(i_fp, o_fp, &strm, in, out);
		if (Z_OK != rc)
			zerr(rc);

		if (extra != NULL)
			free(extra);

		deflateEnd(&strm);
	} else {
		/* --------------- INFALTE ----------------- */
		strm.avail_in = 0;
		strm.next_in = Z_NULL;
		rc = inflateInit2(&strm, window_bits);
		if (Z_OK != rc)
			goto err_out;

		do {
			rc = inf(i_fp, o_fp, &strm, in, out);
			if (Z_STREAM_END != rc) {
				zerr(rc);
				break;
			}
		} while (!feof(i_fp) && !ferror(i_fp));

		inflateEnd(&strm);
	}

 err_out:
	/* Delete the input file, only if input is not stdin and if
	   output is not stdout */
	if ((rc == EXIT_SUCCESS) && (i_fp != stdin) && (o_fp != stdout)) {
		rc = unlink(in_f);
		if (rc != 0) {
			pr_err("%s\n", strerror(errno));
			print_args(stderr, argc, argv);
			exit(EXIT_FAILURE);
		}
	}

	fclose(i_fp);
	fclose(o_fp);
	free(in);
	free(out);

	exit(rc);
}
Ejemplo n.º 27
0
static profile_param_info_t *ParseParams (char *profile_datadir) {
struct stat stat_buf;
char line[512], path[MAXPATHLEN], *p, *q, *s;
profile_param_info_t *profile_list;
profile_param_info_t **list = &profile_list;

	profile_list = NULL;
	while ( ( fgets(line, 512, stdin) != NULL )) {
		LogInfo("Process line '%s'\n", line);
		line[511] = '\0';

		if ( *list == NULL ) 
			*list = (profile_param_info_t *)malloc(sizeof(profile_param_info_t));
		// else we come from a continue statement with illegal data - overwrite

		if ( !*list) {
			LogError("malloc() error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno) );
			return NULL;
		}

		(*list)->next 		  = NULL;
		(*list)->profilegroup = NULL;
		(*list)->profilename  = NULL;
		(*list)->channelname  = NULL;
		(*list)->channel_sourcelist = NULL;
		(*list)->profiletype  = 0;

		// delete '\n' at the end of line
		// format of stdin config line:
		// <profilegroup>#<profilename>#<profiletype>#<channelname>#<channel_sourcelist>
		p = strchr(line, '\n');
		if ( p ) *p = '\0';

		q = line;
		p = strchr(q, '#');
		if ( p ) 
			*p = '\0';

		s = line;

		// savety check: if no separator found loop to next line
		if ( !p ) {
			LogError("Incomplete line - channel skipped.\n");
			continue;
		}

		q = p;
		q++;

		p = strchr(q, '#');
		if ( p ) 
			*p = '\0';

		snprintf(path, MAXPATHLEN-1, "%s/%s/%s", profile_datadir, s, q);
		path[MAXPATHLEN-1] = '\0';
		if ( stat(path, &stat_buf) || !S_ISDIR(stat_buf.st_mode) ) {
			LogError("profile '%s' not found in group %s. Skipped.\n", q, s);
			continue;
		}

		(*list)->profilegroup = strdup(s);
		(*list)->profilename  = strdup(q);

		// savety check: if no separator found loop to next line
		if ( !p ) {
			LogError("Incomplete line - channel skipped.\n");
			continue;
		}

		q = p;
		q++;

		p = strchr(q, '#');
		if ( p ) 
			*p = '\0';

		s = q;
		while ( *s ) {
			if ( *s < '0' || *s > '9' ) {
				LogError("Not a valid number: %s\n", q);
				s = NULL;
				break;
			}
			s++;
		}
		if ( s == NULL )
			continue;

		(*list)->profiletype = (int)strtol(q, (char **)NULL, 10);

		// savety check: if no separator found loop to next line
		if ( !p ) {
			LogError("Incomplete line - channel skipped.\n");
			continue;
		}

		q = p;
		q++;

		p = strchr(q, '#');
		if ( p ) 
			*p = '\0';

		snprintf(path, MAXPATHLEN-1, "%s/%s/%s/%s", profile_datadir, (*list)->profilegroup, (*list)->profilename, q);
		path[MAXPATHLEN-1] = '\0';
		if ( stat(path, &stat_buf) || !S_ISDIR(stat_buf.st_mode) ) {
			LogError("channel '%s' in profile '%s' not found. Skipped.\n", q, (*list)->profilename);
			continue;
		}

		(*list)->channelname = strdup(q);

		if ( !p ) {
			LogError("Incomplete line - Skipped.\n");
			continue;
		}

		q = p;
		q++;

		p = strchr(q, '#');
		if ( p ) 
			*p = '\0';

		// Skip leading '| chars
		while ( *q && *q == '|' ) {
			q++;
		}
		s = q;

		// if q is already empty ( '\0' ) loop is not processed
		while ( *s ) {
			// as s[0] is not '\0' s[1] may be '\0' but still valid and in range
			if ( s[0] == '|' && s[1] == '|' ) {
				char *t = s;
				t++;
				while ( *t ) {	// delete this empty channel name
					t[0] = t[1];
					t++;
				}
			} else
				s++;
		}
		// we have no doublicate '|' here any more
		// check if last char is an extra '|' 
		if ( *q && (q[strlen(q)-1] == '|') )
			q[strlen(q)-1] = '\0';

		if ( *q && (strcmp(q, "*") != 0) ) 
			(*list)->channel_sourcelist = strdup(q);

		list = &((*list)->next);
	}

	if ( *list != NULL ) {
		free(*list);
		*list = NULL;
	}

	if ( ferror(stdin) ) {
		LogError("fgets() error: %s", strerror(errno));
		return NULL;
	}

	return profile_list;

} // End of ParseParams
Ejemplo n.º 28
0
/**********************************************************************
 *
 * S i g n F i l e
 */
static int
SignFile(FILE *outFile, FILE *inFile, CERTCertificate *cert)
{
    int nb;
    char ibuf[4096], digestdata[32];
    const SECHashObject *hashObj;
    void *hashcx;
    unsigned int len;

    SECItem digest;
    SEC_PKCS7ContentInfo *cinfo;
    SECStatus rv;

    if (outFile == NULL || inFile == NULL || cert == NULL)
        return -1;

    /* XXX probably want to extend interface to allow other hash algorithms */
    hashObj = HASH_GetHashObject(HASH_AlgSHA1);

    hashcx = (*hashObj->create)();
    if (hashcx == NULL)
        return -1;

    (*hashObj->begin)(hashcx);

    for (;;) {
        if (feof(inFile))
            break;
        nb = fread(ibuf, 1, sizeof(ibuf), inFile);
        if (nb == 0) {
            if (ferror(inFile)) {
                PORT_SetError(SEC_ERROR_IO);
                (*hashObj->destroy)(hashcx, PR_TRUE);
                return -1;
            }
            /* eof */
            break;
        }
        (*hashObj->update)(hashcx, (unsigned char *)ibuf, nb);
    }

    (*hashObj->end)(hashcx, (unsigned char *)digestdata, &len, 32);
    (*hashObj->destroy)(hashcx, PR_TRUE);

    digest.data = (unsigned char *)digestdata;
    digest.len = len;

    cinfo = SEC_PKCS7CreateSignedData(cert, certUsageObjectSigner, NULL,
                                      SEC_OID_SHA1, &digest, NULL, NULL);

    if (cinfo == NULL)
        return -1;

    rv = SEC_PKCS7IncludeCertChain(cinfo, NULL);
    if (rv != SECSuccess) {
        SEC_PKCS7DestroyContentInfo(cinfo);
        return -1;
    }

    if (no_time == 0) {
        rv = SEC_PKCS7AddSigningTime(cinfo);
        if (rv != SECSuccess) {
            /* don't check error */
        }
    }

    rv = SEC_PKCS7Encode(cinfo, SignOut, outFile, NULL, NULL, &pwdata);

    SEC_PKCS7DestroyContentInfo(cinfo);

    if (rv != SECSuccess)
        return -1;

    return 0;
}
Ejemplo n.º 29
0
/** @brief Set the icewm style.
  *
  * When icewm changes the style, it writes the new style to the ~/.icewm/theme
  * or $ICEWM_PRIVCFG/theme file and then restarts.  The ~/.icewm/theme file
  * looks like:
  *
  *   Theme="Penguins/default.theme"
  *   #Theme="Airforce/default.theme"
  *   ##Theme="Penguins/default.theme"
  *   ###Theme="Pedestals/default.theme"
  *   ####Theme="Penguins/default.theme"
  *   #####Theme="Airforce/default.theme"
  *   ######Theme="Archlinux/default.theme"
  *   #######Theme="Airforce/default.theme"
  *   ########Theme="Airforce/default.theme"
  *   #########Theme="Airforce/default.theme"
  *   ##########Theme="Penguins/default.theme"
  *
  * icewm cannot distinguish between system an user styles.  The theme name
  * specifies a directory in the /usr/share/icewm/themes, ~/.icewm/themes or
  * $ICEWM_PRIVCFG/themes subdirectories.
  *
  * When xde-session runs, it sets the ICEWM_PRIVCFG environment variable.
  * xde-session and associated tools will always set this environment variable
  * before launching icewm.  icewm respects this environment variable and no
  * special options are necessary when launching icewm.
  *
  * The default configuration directory when ICEWM_PRIVCFG is not specified is
  * ~/.icewm.  The location of all other icewm configuration files are in this
  * directory.  xde-session typically sets ICEWM_PRIVCFG to
  * $XDG_CONFIG_HOME/icewm.
  */
static void
set_style_ICEWM()
{
	FILE *f;
	struct stat st;
	char *stylefile, *themerc, *buf, *pos, *end, *line;
	int n, len;
	size_t read, total;

	if (!(stylefile = find_style_ICEWM())) {
		EPRINTF("cannot find style '%s'\n", options.style);
		goto no_stylefile;
	}
	free(stylefile);

	len = strlen(wm->pdir) + strlen("/theme") + 1;
	themerc = calloc(len, sizeof(*themerc));
	snprintf(themerc, len, "%s/theme", wm->pdir);

	if (!(f = fopen(themerc, "r"))) {
		EPRINTF("%s: %s\n", themerc, strerror(errno));
		goto no_themerc;
	}
	if (fstat(fileno(f), &st)) {
		EPRINTF("%s: %s\n", themerc, strerror(errno));
		goto no_stat;
	}
	buf = calloc(st.st_size + 1, sizeof(*buf));
	/* read entire file into buffer */
	total = 0;
	while (total < st.st_size) {
		read = fread(buf + total, 1, st.st_size - total, f);
		total += read;
		if (total >= st.st_size)
			break;
		if (ferror(f)) {
			EPRINTF("%s: %s\n", themerc, strerror(errno));
			goto no_buf;
		}
		if (feof(f))
			break;
	}

	len = strlen(options.style) + strlen("Theme=\"\"") + 1;
	line = calloc(len, sizeof(*line));
	snprintf(line, len, "Theme=\"%s\"", options.style);
	if (strncmp(buf, line, strlen(line)) == 0) {
		OPRINTF("style %s did not change\n", line);
		goto no_change;
	}

	if (options.dryrun) {
	} else {
		OPRINTF("writing new style %s\n", options.style);
		if (!(f = freopen(themerc, "w", f))) {
			EPRINTF("%s: %s\n", themerc, strerror(errno));
			goto no_change;
		}
		fprintf(f, "Theme=\"%s\"\n", options.style);
		for (n = 0, pos = buf, end = buf + st.st_size; pos < end && n < 10;
		     n++, pos = pos + strlen(pos) + 1) {
			*strchrnul(pos, '\n') = '\0';
			fprintf(f, "#%s\n", pos);
		}
		if (options.reload)
			reload_style_ICEWM();
	}
      no_change:
	free(line);
      no_buf:
	free(buf);
      no_stat:
	fclose(f);
      no_themerc:
	free(themerc);
      no_stylefile:
	return;
}
Ejemplo n.º 30
0
gint32
Mono_Posix_Stdlib_ferror (void* stream)
{
	return ferror (((FILE*) stream));
}