Example #1
0
static unsigned long get_bytes_read(void)
{
	char fname[128];
	char entry[] = "read_bytes: %lu";
	sprintf(fname, "/proc/%u/io", getpid());
	return parse_entry(fname, entry);
}
Example #2
0
/** 
 * parse_ifd_entries() extracts entries from an offset given its type.
 * Throws exif_failure_exception if the exif data state is determined to be invalid
 * such that further entry parsing would be invalid.
 * @Throws exif_failure_exception_t
 */
void entry_reader::parse_ifd_entries(ifd_type_t ifd_type, tiff_handle_t &tiff_handle,
				     size_t ifd_offset, entry_list_t &entries) {
    uint16_t num_entries = tiff_ifd_reader::get_num_entries(tiff_handle, ifd_offset);
#ifdef DEBUG
    cout << "exif_entry.parse_ifd_entries ifd type " << (uint32_t)ifd_type << ", num entries: " << num_entries << " from offset " << ifd_offset << "\n";
#endif
    if (num_entries == 0) {
        return;
    }

    // abort the EXIF if its number of entries is considered excessive
    // truncate excessive entries
    if (num_entries > OPT_MAX_IFD_ENTRIES) throw exif_failure_exception_t();

    // parse each entry
    for (uint16_t i=0; i<num_entries; i++) {
        // quick sanity check - have we parsed more than 64K?
        if (tiff_handle.bytes_read >= OPT_MAX_EXIF_BYTES) throw exif_failure_exception_t();

        uint32_t ifd_entry_offset = tiff_ifd_reader::get_entry_offset(ifd_offset, i);
        if (ifd_entry_offset + 12 > tiff_handle.sbuf->bufsize) throw exif_failure_exception_t();
#ifdef DEBUG
	cout << "exif_entry.parse_ifd_entries ifd_entry_offset: " << ifd_entry_offset << "\n";
#endif

        // parse the entry
        parse_entry(ifd_type, tiff_handle, ifd_entry_offset, entries);
    }
}
Example #3
0
File: ini.c Project: vaughan0/vlib
static int parse_line(Parser* self, const char* line, size_t len) {
  unsigned i = 0;

  // Skip whitespace
  while (i < len && isspace(line[i])) i++;
  
  if (i == len) {
    // Blank line
    return 0;
  }

  switch (line[i]) {

    case ';':
    case '#':
      // Comment
      return 0;

    case '[':
      i++;
      return parse_section(self, line+i, len-i);

    default:
      if (!self->section) {
        self->error = "entry before section header";
        return -1;
      }
      return parse_entry(self, line, len);

  }
}
Example #4
0
/* Convert one or more acl entries in string form to an acl_t */
acl_t
parse_acl_entries(const char *input) {
	acl_t acl_input;
	acl_entry_t newent;
	char *inbuf;
	char *oinbuf;

	char **bufp, *entryv[ACL_MAX_ENTRIES];
#if 0
/* XXX acl_from_text(), when implemented, will presumably use the canonical 
 * text representation format, which is what chmod should be using 
 * We may need to add an entry number to the input
 */
	/* Translate the user supplied ACL entry */
	/* acl_input = acl_from_text(input); */
#else
	inbuf = malloc(MAX_ACL_TEXT_SIZE);
	
    if (inbuf == NULL) {
		// err(1, "malloc() failed");
        fprintf(stderr, "chmod: malloc() failed: %s\n", strerror(errno));
        pthread_exit(NULL);
    }
	strncpy(inbuf, input, MAX_ACL_TEXT_SIZE);
	inbuf[MAX_ACL_TEXT_SIZE - 1] = '\0';

    if ((acl_input = acl_init(1)) == NULL) {
		// err(1, "acl_init() failed");
        fprintf(stderr, "chmod: acl_init() failed: %s\n", strerror(errno));
        pthread_exit(NULL);
    }

	oinbuf = inbuf;

	for (bufp = entryv; (*bufp = strsep(&oinbuf, "\n")) != NULL;)
		if (**bufp != '\0') {
            if (0 != acl_create_entry(&acl_input, &newent)) {
				// err(1, "acl_create_entry() failed");
                fprintf(stderr, "chmod: acl_create_entry() failed: %s\n", strerror(errno));
                pthread_exit(NULL);
            }
			if (0 != parse_entry(*bufp, newent)) {
                // errx(1, "Failed parsing entry '%s'", *bufp);
				fprintf(stderr, "chmod: Failed parsing entry '%s'\n", *bufp);
                pthread_exit(NULL);
			}
			if (++bufp >= &entryv[ACL_MAX_ENTRIES - 1]) {
				// errx(1, "Too many entries");
                fprintf(stderr, "chmod: Too many entries\n");
                pthread_exit(NULL);
			}
		}
	
	free(inbuf);
	return acl_input;
#endif	/* #if 0 */
}
Example #5
0
int parse_block(int fd1,int fd2)
{
    char tag;
    read(fd1,&tag,1);
    switch(GET_TAG(tag))
    {
	case 0x00:
	    parse_titleblock(fd1);
	    break;
	case 0x01:
	    parse_sheet(fd1);
	    break;
	case 0x02:
	    parse_component(fd1,fd2);
	    break;
	case 0x03:
	    parse_wire(fd1);
	    break;
	case 0x04:
	    parse_bus(fd1);
	    break;
	case 0x05:
	    parse_junction(fd1);
	    break;
	case 0x06:
	    parse_port(fd1);
	    break;
	case 0x07:
	    parse_label(fd1);
	    break;
	case 0x08:
	    parse_entry(fd1);
	    break;
	case 0x09:
	    parse_dashed(fd1);
	    break;
	case 0x0a:
	    parse_power(fd1);
	    break;
	case 0x0b:
	    parse_text(fd1);
	    break;
	case 0x0c:
	    parse_marker(fd1);
	    break;
	case 0x0f:
	    return 0;
	    break;
	default:
	    fprintf(stderr,"\nUnknown Block Tag\n");
	    exit(-1);
	    break;
    }


    return 1;
}
Example #6
0
static int
read_kld(char *filename, char *kldname)
{
	struct mod_metadata md;
	struct elf_file ef;
	void **p, **orgp;
	int error, eftype, nmlen;
	long start, finish, entries;
	char kldmodname[MAXMODNAME + 1], cval[MAXMODNAME + 1], *cp;

	if (verbose || dflag)
		printf("%s\n", filename);
	error = ef_open(filename, &ef, verbose);
	if (error) {
		error = ef_obj_open(filename, &ef, verbose);
		if (error) {
			if (verbose)
				warnc(error, "elf_open(%s)", filename);
			return error;
		}
	}
	eftype = EF_GET_TYPE(&ef);
	if (eftype != EFT_KLD && eftype != EFT_KERNEL)  {
		EF_CLOSE(&ef);
		return 0;
	}
	if (!dflag) {
		cp = strrchr(kldname, '.');
		nmlen = (cp != NULL) ? cp - kldname : (int)strlen(kldname);
		if (nmlen > MAXMODNAME)
			nmlen = MAXMODNAME;
		strlcpy(kldmodname, kldname, nmlen);
/*		fprintf(fxref, "%s:%s:%d\n", kldmodname, kldname, 0);*/
	}
	do {
		check(EF_LOOKUP_SET(&ef, MDT_SETNAME, &start, &finish,
		    &entries));
		check(EF_SEG_READ_ENTRY_REL(&ef, start, sizeof(*p) * entries,
		    (void *)&p));
		orgp = p;
		while(entries--) {
			check(EF_SEG_READ_REL(&ef, (Elf_Off)*p, sizeof(md),
			    &md));
			p++;
			check(EF_SEG_READ(&ef, (Elf_Off)md.md_cval,
			    sizeof(cval), cval));
			cval[MAXMODNAME] = '\0';
			parse_entry(&md, cval, &ef, kldname);
		}
		if (error)
			warnc(error, "error while reading %s", filename);
		free(orgp);
	} while(0);
	EF_CLOSE(&ef);
	return error;
}
Example #7
0
void			parse(int fd, t_map *map)
{
    char		buffer[BUFFER_SIZE + 1];
    int			char_count;

    char_count = read_input(fd, buffer);
    check_input_length(char_count);
    prepare_entry_for_split(buffer);
    parse_entry(buffer, map);
}
Example #8
0
static GNode *
xmms_magic_add_node (GNode *tree, const gchar *s, GNode *prev_node)
{
	xmms_magic_entry_t *entry;
	gpointer *data = tree->data;
	guint indent = 0, prev_indent;

	g_assert (s);

	XMMS_DBG ("adding magic spec to tree '%s'", (gchar *) data[0]);

	/* indent level is number of leading '>' characters */
	while (*s == '>') {
		indent++;
		s++;
	}

	entry = parse_entry (s);
	if (!entry) {
		XMMS_DBG ("cannot parse magic entry");
		return NULL;
	}

	if (!indent) {
		return g_node_append_data (tree, entry);
	}

	if (!prev_node) {
		XMMS_DBG ("invalid indent level");
		xmms_magic_entry_free (entry);
		return NULL;
	}

	prev_indent = g_node_depth (prev_node) - 2;

	if (indent > prev_indent) {
		/* larger jumps are invalid */
		if (indent != prev_indent + 1) {
			XMMS_DBG ("invalid indent level");
			xmms_magic_entry_free (entry);
			return NULL;
		}

		return g_node_append_data (prev_node, entry);
	} else {
		while (indent < prev_indent) {
			prev_indent--;
			prev_node = prev_node->parent;
		}

		return g_node_insert_after (prev_node->parent, prev_node,
		                            g_node_new (entry));
	}
}
Example #9
0
/*
 * Parses a file (in the format used by TAGDB and NOTEDB).
 *
 * fn		File to parse
 *
 * spec		The specification of the format for the database. This
 *		consists of a series of identifier,type,offset tuples, ending
 *		with a NULL identifier.
 *
 * store	The database store, with offsets specified in spec.
 *		Specify as NULL for the first file, and the current database
 *		pointer for subsequent files.
 *
 * nitems	The number of items in the database so far.
 *
 * store_size	The size of each structure in store.
 *
 * default	A default structure for the store, or NULL if none.
 *
 * Returns a new copy of the database ('store'), or NULL for failure.
 */
void *parse_file(char *fn, pf_spec *spec, void *store, int *nitems,
		 int store_size, void *default_store) {
    int eof = 0;
    int count = *nitems;
    char *storep;
    FILE *fp;

    infile = fn;
    lineno = 0;
    fp = fopen(fn, "rb");

    if (!fp) {
	parse_error("Could not open");
	return NULL;
    }

    while (!eof) {
	switch (next_word(fp)) {
	case TOK_END:
	    eof = 1;
	    break;

	case TOK_NL:
	    break;

	case TOK_ID:
	    if (!(storep = find_store(store, store_size, count, word))) {
		count++;
		store = xrealloc(store, count * store_size);
		storep = (char *)store + (count-1) * store_size;
		if (default_store)
		    memcpy(storep, default_store, store_size);
		else
		    memset(storep, 0, store_size);
		*((char **)storep) = strdup(word);
	    }
	    eof = parse_entry(fp, spec, storep);
	    break;

	default:
	    parse_error("Syntax error - stopped parsing");
	    fclose(fp);
	    return NULL;
	}
    }

    fclose(fp);
    
    *nitems = count;
    return store;
}
Example #10
0
void 
process_desktop_file(const char * filename)
{
	FILE * f = fopen(filename, "r");

	if (!f)
		die("could not open file \"%s\"\n", filename);

	if (!parse_entry(f))
		die("file %s was invalid\n", filename);

	fclose(f);

	if (shell)
	{
		char * args[] =
		{
			SHELL,
			"-c",
			progpath,
			NULL
		};
			
		if (execvp(args[0], args) == -1)
			die("autorun: exec: %s (%d)\n", strerror(errno), errno);
	}

	char ** args = (char**)malloc(sizeof(char**));
	int argc = 0;

	char * next = NULL;
	int i = 0, j;

	while(sscanf(progpath+i, "%ms%n", &next, &j)>0) 
	{
		args = (char **)realloc((void*)args, sizeof(char**)*(argc+1));
		args[argc] = next;
		args[argc+1] = NULL;

		argc++;
		i+=j;
	}

	if (argc==0) 
		die("invalid Exec field value %s\n", progpath);

	if (execvp(args[0], args) == -1)
		die("could not exec program: %s (%d)\n", strerror(errno), errno);
}
SdfNode* parse_document(ParserData* data) {
	SdfNode* root = new_valued_node(data->filename, strlen(data->filename));

	// Parse children
	while (!data->eof) {
		SdfNode* child = parse_entry(data);
		if (child != NULL) {
			add_child(root, child);
		} else {
			// Syntax error in contents
			sdf_free_tree(root);
			return NULL;
		}
	}
	return root;
}
Example #12
0
File: auth_acl.c Project: PADL/krb5
/* Parse the contents of an ACL line. */
static struct acl_entry *
parse_line(krb5_context context, const char *line, const char *fname)
{
    struct acl_entry *entry = NULL;
    char *copy;
    char *client, *client_end, *ops, *ops_end, *target, *target_end, *rs, *end;
    const char *ws = "\t\n\f\v\r ,";

    /*
     * Format:
     *  entry ::= [<whitespace>] <principal> <whitespace> <opstring>
     *            [<whitespace> <target> [<whitespace> <restrictions>
     *                                    [<whitespace>]]]
     */

    /* Make a copy and remove any trailing whitespace. */
    copy = strdup(line);
    if (copy == NULL)
        return NULL;
    end = copy + strlen(copy);
    while (end > copy && isspace(end[-1]))
        *--end = '\0';

    /* Find the beginning and end of each field.  The end of restrictions is
     * the end of copy. */
    client = copy + strspn(copy, ws);
    client_end = client + strcspn(client, ws);
    ops = client_end + strspn(client_end, ws);
    ops_end = ops + strcspn(ops, ws);
    target = ops_end + strspn(ops_end, ws);
    target_end = target + strcspn(target, ws);
    rs = target_end + strspn(target_end, ws);

    /* Terminate the first three fields. */
    *client_end = *ops_end = *target_end = '\0';

    /* The last two fields are optional; represent them as NULL if not present.
     * The first two fields are required. */
    if (*target == '\0')
        target = NULL;
    if (*rs == '\0')
        rs = NULL;
    if (*client != '\0' && *ops != '\0')
        entry = parse_entry(context, client, ops, target, rs, line, fname);
    free(copy);
    return entry;
}
Example #13
0
void atom_parser::parse_feed(feed& f, xmlNode * rootNode) {
	if (!rootNode)
		throw exception(_("XML root node is NULL"));

	switch (f.rss_version) {
	case ATOM_0_3:
		ns = ATOM_0_3_URI;
		break;
	case ATOM_1_0:
		ns = ATOM_1_0_URI;
		break;
	case ATOM_0_3_NONS:
		ns = nullptr;
		break;
	default:
		ns = nullptr;
		break;
	}

	f.language = get_prop(rootNode, "lang");
	globalbase = get_prop(rootNode, "base", XML_URI);

	for (xmlNode * node = rootNode->children; node != nullptr; node = node->next) {
		if (node_is(node, "title", ns)) {
			f.title = get_content(node);
			f.title_type = get_prop(node, "type");
			if (f.title_type == "")
				f.title_type = "text";
		} else if (node_is(node, "subtitle", ns)) {
			f.description = get_content(node);
		} else if (node_is(node, "link", ns)) {
			std::string rel = get_prop(node, "rel");
			if (rel == "alternate") {
				f.link = newsbeuter::utils::absolute_url(globalbase, get_prop(node, "href"));
			}
		} else if (node_is(node, "updated", ns)) {
			f.pubDate = w3cdtf_to_rfc822(get_content(node));
		} else if (node_is(node, "entry", ns)) {
			f.items.push_back(parse_entry(node));
		}
	}

}
Example #14
0
int
parse_map(char *filename)
{
	FILE	*fp;
	char	*line;
	size_t	 len;
	size_t	 lineno = 0;
	char	 delim[] = { '\\', 0, 0 };

	if (strcmp(filename, "-") == 0)
		fp = fdopen(0, "r");
	else
		fp = fopen(filename, "r");
	if (fp == NULL) {
		warn("%s", filename);
		return 0;
	}

	if (!isatty(fileno(fp)) && flock(fileno(fp), LOCK_SH|LOCK_NB) == -1) {
		if (errno == EWOULDBLOCK)
			warnx("%s is locked", filename);
		else
			warn("%s: flock", filename);
		fclose(fp);
		return 0;
	}

	while ((line = fparseln(fp, &len, &lineno, delim, 0)) != NULL) {
		if (! parse_entry(line, len, lineno)) {
			free(line);
			fclose(fp);
			return 0;
		}
		free(line);
	}

	fclose(fp);
	return 1;
}
Example #15
0
tsol_zcent_t *
tsol_sgetzcent(const char *instr, int *errp, char **errstrp)
{
	int err;
	m_label_t *slp;
	char *errstr;
	tsol_zcent_t *zc;
	const char *nextf;
	char *cp;
	char fieldbuf[1024];

	/*
	 * The user can specify NULL pointers for these.  Make sure that we
	 * don't have to deal with checking for NULL everywhere by just
	 * pointing to our own variables if the user gives NULL.
	 */
	if (errp == NULL)
		errp = &err;
	if (errstrp == NULL)
		errstrp = &errstr;

	/* The default, unless we find a more specific error locus. */
	*errstrp = (char *)instr;

	if ((zc = calloc(1, sizeof (*zc))) == NULL) {
		*errp = LTSNET_SYSERR;
		return (NULL);
	}

	/* First, parse off the zone name. */
	instr = parse_entry(zc->zc_name, sizeof (zc->zc_name), instr, "#;:\n");
	if (zc->zc_name[0] == '\0') {
		*errstrp = (char *)instr;
		if (*instr == '\0' || *instr == '#' || *instr == '\n')
			*errp = LTSNET_EMPTY;
		else if (*instr == ':')
			*errp = LTSNET_NO_NAME;
		else
			*errp = LTSNET_ILL_NAME;
		goto err_ret;
	}
	if (*instr != ':') {
		*errstrp = (char *)instr;
		if (*instr == '=' || *instr == ';')
			*errp = LTSNET_ILL_NAME;
		else
			*errp = LTSNET_ILL_ENTRY;
		goto err_ret;
	}
	instr++;

	/* Field two: parse off the label. */
	nextf = parse_entry(fieldbuf, sizeof (fieldbuf), instr, "#;:\n");
	if (*nextf != ':') {
		*errstrp = (char *)nextf;
		*errp = LTSNET_ILL_ENTRY;
		goto err_ret;
	}
	if (fieldbuf[0] == '\0') {
		*errstrp = (char *)instr;
		*errp = LTSNET_NO_LABEL;
		goto err_ret;
	}

	slp = &zc->zc_label;
	if (str_to_label(fieldbuf, &slp, MAC_LABEL, L_NO_CORRECTION, NULL)
	    != 0) {
		*errstrp = (char *)instr;
		*errp = LTSNET_ILL_LABEL;
		goto err_ret;
	}
	instr = nextf + 1;

	/* The kernel will apply the system doi to the zone label later */
	zc->zc_doi = 0;

	/* Field three: get match flag */
	errno = 0;
	zc->zc_match = (uchar_t)strtol(instr, &cp, 0);
	if (errno != 0 || (*cp != ':' && *cp != '\0')) {
		*errp = LTSNET_ILL_FLAG;
		*errstrp = (char *)instr;
		goto err_ret;
	}
	if (*cp != ':') {
		*errp = LTSNET_ILL_VALDELIM;
		*errstrp = cp;
		goto err_ret;
	}
	instr = cp + 1;

	/* Field four: get zone-specific MLP list. */
	nextf = parse_entry(fieldbuf, sizeof (fieldbuf), instr, "#:\n");
	if (*nextf != ':') {
		*errstrp = (char *)nextf;
		*errp = LTSNET_ILL_ENTRY;
		goto err_ret;
	}
	if (!parse_mlp_list(&zc->zc_private_mlp, fieldbuf, errp, errstrp)) {
		*errstrp = (char *)instr + (*errstrp - fieldbuf);
		goto err_ret;
	}
	instr = nextf + 1;

	/* Field five: get global MLP list. */
	nextf = parse_entry(fieldbuf, sizeof (fieldbuf), instr, "#:\n");
	if (*nextf != '\0' && *nextf != '#' && !isspace(*nextf)) {
		*errstrp = (char *)nextf;
		*errp = LTSNET_ILL_ENTRY;
		goto err_ret;
	}
	if (!parse_mlp_list(&zc->zc_shared_mlp, fieldbuf, errp, errstrp)) {
		*errstrp = (char *)instr + (*errstrp - fieldbuf);
		goto err_ret;
	}

	return (zc);

err_ret:
	err = errno;
	tsol_freezcent(zc);
	errno = err;
	return (NULL);
}
SdfNode* parse_entry(ParserData* data) {

	// First try to parse a label.
	char* label;
	int length = consume_label(data, &label);
	if (length == 0) {
		// We did not find a label!
		return error(data, EXPECTED_LABEL);
	}

	// Create the node for this element
	SdfNode* element = new_valued_node(label, length);

	// Now try to get a { or :
	if (consume(data, '{')) {
		// This entry is a struct-valued entry

		// End the current line
		if (!next_line(data)) {
			sdf_free_tree(element);
			return error(data, EXPECTED_END_OF_LINE);
		}

		// Parse children until the closing bracket is found.
		while (!consume(data, '}')) {
			SdfNode* child = parse_entry(data);
			if (child != NULL) {
				add_child(element, child);
			} else {
				// Syntax error in contents
				sdf_free_tree(element);
				return NULL;
			}
		}
	} else if (consume(data, ':')) {
		// This entry is a single-valued entry

		// Consume leading white space
		consume_whitespace(data);

		// Try to get a simple or quoted string
		SdfNode* value;
		if (data->line[data->column] == '"') {
			// Quoted string
			value = consume_quoted_string(data);
		} else {
			// Simple string
			char* string;
			length = consume_label(data, &string);
			value = new_valued_node(string, length);
		}
		add_child(element, value);
	} else {
		// Failed to get a { or :
		sdf_free_tree(element);
		return error(data, EXPECTED_ENTRY);
	}

	// And we need a final newline, except when we are at the end of the file.
	if (!next_line(data) && !data->eof) {
		// Encountered something else than a newline or EOF
		sdf_free_tree(element);
		return error(data, EXPECTED_END_OF_LINE);
	}

	return element;
}
Example #17
0
/*
 * Get a service entry. Steps:
 *
 *      1. Parse entry attributes
 *      2. Determine service id
 *      3. Insert entry in table
 */
static void get_service_entry( int fd,
                               pset_h sconfs,
                               const char *name,
                               struct service_config *defaults )
{
    struct service_config   *scp ;
    const char              *func = "get_service_entry" ;

    scp = sc_alloc( name ) ;
    if ( scp == NULL )
    {
        skip_entry( fd ) ;
        return ;
    }

    /* Now fill in default attributes if given. */
    if ( SC_SPECIFIED( defaults, A_LOG_ON_SUCCESS ) &&
            ! SC_IS_PRESENT( scp, A_LOG_ON_SUCCESS) )
        fill_attribute( A_LOG_ON_SUCCESS, scp, defaults ) ;
    if ( SC_SPECIFIED( defaults, A_LOG_ON_FAILURE ) &&
            ! SC_IS_PRESENT( scp, A_LOG_ON_FAILURE ) )
        fill_attribute( A_LOG_ON_FAILURE, scp, defaults ) ;
    if ( SC_SPECIFIED( defaults, A_ONLY_FROM ) &&
            ! SC_IS_PRESENT( scp, A_ONLY_FROM ) )
        fill_attribute( A_ONLY_FROM, scp, defaults ) ;
    if ( SC_SPECIFIED( defaults, A_NO_ACCESS ) &&
            ! SC_IS_PRESENT( scp, A_NO_ACCESS ) )
        fill_attribute( A_NO_ACCESS, scp, defaults ) ;
    if ( SC_SPECIFIED( defaults, A_PASSENV ) &&
            ! SC_IS_PRESENT( scp, A_PASSENV ) )
        fill_attribute( A_PASSENV, scp, defaults ) ;
    if ( SC_SPECIFIED( defaults, A_ACCESS_TIMES ) &&
            ! SC_IS_PRESENT( scp, A_ACCESS_TIMES ) )
        fill_attribute( A_ACCESS_TIMES, scp, defaults ) ;
    if ( SC_SPECIFIED( defaults, A_BANNER ) &&
            ! SC_IS_PRESENT( scp, A_BANNER ) )
        fill_attribute( A_BANNER, scp, defaults ) ;
    if ( SC_SPECIFIED( defaults, A_BANNER_SUCCESS ) &&
            ! SC_IS_PRESENT( scp, A_BANNER_SUCCESS ) )
        fill_attribute( A_BANNER_SUCCESS, scp, defaults ) ;
    if ( SC_SPECIFIED( defaults, A_BANNER_FAIL ) &&
            ! SC_IS_PRESENT( scp, A_BANNER_FAIL ) )
        fill_attribute( A_BANNER_FAIL, scp, defaults ) ;

    if ( parse_entry( SERVICE_ENTRY, fd, scp ) == FAILED )
    {
        sc_free( scp ) ;
        skip_entry( fd ) ;
        return ;
    }

    /*
     * If no service id was specified, set it equal to the service name
     */
    if ( ! SC_SPECIFIED( scp, A_ID ) ) {
        if ( (SC_ID(scp) = new_string( SC_NAME(scp) )) )
            SC_PRESENT( scp, A_ID ) ;
        else
        {
            out_of_memory( func ) ;
            sc_free( scp ) ;
            return ;
        }
    }

    if ( ! (pset_add( sconfs, scp )) )
    {
        out_of_memory( func ) ;
        sc_free( scp ) ;
        return ;
    }

}
Example #18
0
/*
 * Read the configuration file (descriptor fd) and place all
 * services found there in the configuration.
 */
void parse_conf_file( int fd, struct configuration *confp, const char *filename)
{
    pset_h                   sconfs       = CNF_SERVICE_CONFS( confp ) ;
    struct service_config   *default_config   = CNF_DEFAULTS( confp ) ;
    boolean_e                found_defaults   = NO ;
    struct service_config    default_default_config ;
    const char              *func      = "parse_conf_file" ;
    int                      incfd;

    line_count = 0 ;
    current_file = filename;
    CLEAR( default_default_config ) ;

    for ( ;; )
    {
        entry_e   entry_type ;
        char      *service_name  = NULL;

        /*
         * if find_next_entry is successful, service_name
         * will point to malloc'ed memory
         */
        entry_type = find_next_entry( fd, &service_name ) ;
        switch ( entry_type )
        {
        case INCLUDE_ENTRY:
        {
            int saved_line_count = line_count;
            incfd = open(service_name, O_RDONLY);
            if( incfd < 0 ) {
                parsemsg( LOG_ERR, func,
                          "Unable to open included configuration file: %s",
                          service_name);
                break;
            }
            parsemsg( LOG_DEBUG,func,
                      "Reading included configuration file: %s",service_name);
            parse_conf_file(incfd, confp, service_name);
            /*
             * parse_conf_file eventually calls Srdline, try Sclosing it
             * to unmmap memory.
             */
            Sclose(incfd);
            /* Restore since we've returned from included file */
            current_file = filename;
            line_count = saved_line_count;
        }
        break;
        case INCLUDEDIR_ENTRY:
        {
            int saved_line_count = line_count;
            handle_includedir(service_name, confp);
            current_file = filename;
            line_count = saved_line_count;
        }
        break;
        case SERVICE_ENTRY:
            get_service_entry( fd, sconfs, service_name, default_config ) ;
            break ;
        case DEFAULTS_ENTRY:
            if ( found_defaults == YES )
            {
                parsemsg( LOG_ERR, func,
                          "only 1 defaults entry is allowed. This entry will be ignored" ) ;
                skip_entry( fd ) ;
            }
            else if ( parse_entry( DEFAULTS_ENTRY, fd,
                                   default_config ) == OK ) {
                found_defaults = YES ;
                /*
                 * We must check bind_address to see if it was deferred.
                 */
                if (SC_SPECIFIED( default_config, A_BIND) &&
                        SC_BIND_ADDR(default_config) == NULL)
                    M_CLEAR( default_config->sc_specified_attributes, A_BIND ) ;
            }
            break ;

        case BAD_ENTRY:
            skip_entry( fd ) ;
            break ;

        case NO_ENTRY:
            return ;
        }
        if (service_name)
            free(service_name);
    }
}
Example #19
0
static void edit_index(int natoms, t_atoms *atoms, rvec *x, t_blocka *block, char ***gn, gmx_bool bVerbose)
{
    static char   **atnames, *ostring;
    static gmx_bool bFirst = TRUE;
    char            inp_string[STRLEN], *string;
    char            gname[STRLEN], gname1[STRLEN], gname2[STRLEN];
    int             i, i0, i1, sel_nr, sel_nr2, newgroup;
    atom_id         nr, nr1, nr2, *index, *index1, *index2;
    gmx_bool        bAnd, bOr, bPrintOnce;

    if (bFirst)
    {
        bFirst = FALSE;
        snew(atnames, MAXNAMES);
        for (i = 0; i < MAXNAMES; i++)
        {
            snew(atnames[i], NAME_LEN+1);
        }
    }

    string = NULL;

    snew(index, natoms);
    snew(index1, natoms);
    snew(index2, natoms);

    newgroup   = NOTSET;
    bPrintOnce = TRUE;
    do
    {
        gname1[0] = '\0';
        if (bVerbose || bPrintOnce || newgroup != NOTSET)
        {
            printf("\n");
            if (bVerbose || bPrintOnce || newgroup == NOTSET)
            {
                i0 = 0;
                i1 = block->nr;
            }
            else
            {
                i0 = newgroup;
                i1 = newgroup+1;
            }
            for (i = i0; i < i1; i++)
            {
                printf("%3d %-20s: %5d atoms\n", i, (*gn)[i],
                       block->index[i+1]-block->index[i]);
            }
            newgroup = NOTSET;
        }
        if (bVerbose || bPrintOnce)
        {
            printf("\n");
            printf(" nr : group       !   'name' nr name   'splitch' nr    Enter: list groups\n");
            printf(" 'a': atom        &   'del' nr         'splitres' nr   'l': list residues\n");
            printf(" 't': atom type   |   'keep' nr        'splitat' nr    'h': help\n");
            printf(" 'r': residue         'res' nr         'chain' char\n");
            printf(" \"name\": group        'case': case %s         'q': save and quit\n",
                   bCase ? "insensitive" : "sensitive  ");
            printf(" 'ri': residue index\n");
            bPrintOnce = FALSE;
        }
        printf("\n");
        printf("> ");
        if (NULL == fgets(inp_string, STRLEN, stdin))
        {
            gmx_fatal(FARGS, "Error reading user input");
        }
        inp_string[strlen(inp_string)-1] = 0;
        printf("\n");
        string = inp_string;
        while (string[0] == ' ')
        {
            string++;
        }

        ostring = string;
        nr      = 0;
        if (string[0] == 'h')
        {
            printf(" nr                : selects an index group by number or quoted string.\n");
            printf("                     The string is first matched against the whole group name,\n");
            printf("                     then against the beginning and finally against an\n");
            printf("                     arbitrary substring. A multiple match is an error.\n");

            printf(" 'a' nr1 [nr2 ...] : selects atoms, atom numbering starts at 1.\n");
            printf(" 'a' nr1 - nr2     : selects atoms in the range from nr1 to nr2.\n");
            printf(" 'a' name1[*] [name2[*] ...] : selects atoms by name(s), '?' matches any char,\n");
            printf("                               wildcard '*' allowed at the end of a name.\n");
            printf(" 't' type1[*] [type2[*] ...] : as 'a', but for type, run input file required.\n");
            printf(" 'r' nr1[ic1] [nr2[ic2] ...] : selects residues by number and insertion code.\n");
            printf(" 'r' nr1 - nr2               : selects residues in the range from nr1 to nr2.\n");
            printf(" 'r' name1[*] [name2[*] ...] : as 'a', but for residue names.\n");
            printf(" 'ri' nr1 - nr2              : selects residue indices, 1-indexed, (as opposed to numbers) in the range from nr1 to nr2.\n");
            printf(" 'chain' ch1 [ch2 ...]       : selects atoms by chain identifier(s),\n");
            printf("                               not available with a .gro file as input.\n");
            printf(" !                 : takes the complement of a group with respect to all\n");
            printf("                     the atoms in the input file.\n");
            printf(" & |               : AND and OR, can be placed between any of the options\n");
            printf("                     above, the input is processed from left to right.\n");
            printf(" 'name' nr name    : rename group nr to name.\n");
            printf(" 'del' nr1 [- nr2] : deletes one group or groups in the range from nr1 to nr2.\n");
            printf(" 'keep' nr         : deletes all groups except nr.\n");
            printf(" 'case'            : make all name compares case (in)sensitive.\n");
            printf(" 'splitch' nr      : split group into chains using CA distances.\n");
            printf(" 'splitres' nr     : split group into residues.\n");
            printf(" 'splitat' nr      : split group into atoms.\n");
            printf(" 'res' nr          : interpret numbers in group as residue numbers\n");
            printf(" Enter             : list the currently defined groups and commands\n");
            printf(" 'l'               : list the residues.\n");
            printf(" 'h'               : show this help.\n");
            printf(" 'q'               : save and quit.\n");
            printf("\n");
            printf(" Examples:\n");
            printf(" > 2 | 4 & r 3-5\n");
            printf(" selects all atoms from group 2 and 4 that have residue numbers 3, 4 or 5\n");
            printf(" > a C* & !a C CA\n");
            printf(" selects all atoms starting with 'C' but not the atoms 'C' and 'CA'\n");
            printf(" > \"protein\" & ! \"backb\"\n");
            printf(" selects all atoms that are in group 'protein' and not in group 'backbone'\n");
            if (bVerbose)
            {
                printf("\npress Enter ");
                getchar();
            }
        }
        else if (strncmp(string, "del", 3) == 0)
        {
            string += 3;
            if (parse_int(&string, &sel_nr))
            {
                while (string[0] == ' ')
                {
                    string++;
                }
                if (string[0] == '-')
                {
                    string++;
                    parse_int(&string, &sel_nr2);
                }
                else
                {
                    sel_nr2 = NOTSET;
                }
                while (string[0] == ' ')
                {
                    string++;
                }
                if (string[0] == '\0')
                {
                    remove_group(sel_nr, sel_nr2, block, gn);
                }
                else
                {
                    printf("\nSyntax error: \"%s\"\n", string);
                }
            }
        }
        else if (strncmp(string, "keep", 4) == 0)
        {
            string += 4;
            if (parse_int(&string, &sel_nr))
            {
                remove_group(sel_nr+1, block->nr-1, block, gn);
                remove_group(0, sel_nr-1, block, gn);
            }
        }
        else if (strncmp(string, "name", 4) == 0)
        {
            string += 4;
            if (parse_int(&string, &sel_nr))
            {
                if ((sel_nr >= 0) && (sel_nr < block->nr))
                {
                    sscanf(string, "%s", gname);
                    sfree((*gn)[sel_nr]);
                    (*gn)[sel_nr] = strdup(gname);
                }
            }
        }
        else if (strncmp(string, "case", 4) == 0)
        {
            bCase = !bCase;
            printf("Switched to case %s\n", bCase ? "sensitive" : "insensitive");
        }
        else if (string[0] == 'v')
        {
            bVerbose = !bVerbose;
            printf("Turned verbose %s\n", bVerbose ? "on" : "off");
        }
        else if (string[0] == 'l')
        {
            if (check_have_atoms(atoms, ostring) )
            {
                list_residues(atoms);
            }
        }
        else if (strncmp(string, "splitch", 7) == 0)
        {
            string += 7;
            if (check_have_atoms(atoms, ostring) &&
                parse_int(&string, &sel_nr) &&
                (sel_nr >= 0) && (sel_nr < block->nr))
            {
                split_chain(atoms, x, sel_nr, block, gn);
            }
        }
        else if (strncmp(string, "splitres", 8) == 0)
        {
            string += 8;
            if (check_have_atoms(atoms, ostring) &&
                parse_int(&string, &sel_nr) &&
                (sel_nr >= 0) && (sel_nr < block->nr))
            {
                split_group(atoms, sel_nr, block, gn, FALSE);
            }
        }
        else if (strncmp(string, "splitat", 7) == 0)
        {
            string += 7;
            if (check_have_atoms(atoms, ostring) &&
                parse_int(&string, &sel_nr) &&
                (sel_nr >= 0) && (sel_nr < block->nr))
            {
                split_group(atoms, sel_nr, block, gn, TRUE);
            }
        }
        else if (string[0] == '\0')
        {
            bPrintOnce = TRUE;
        }
        else if (string[0] != 'q')
        {
            nr1 = -1;
            nr2 = -1;
            if (parse_entry(&string, natoms, atoms, block, gn, &nr, index, gname))
            {
                do
                {
                    while (string[0] == ' ')
                    {
                        string++;
                    }

                    bAnd = FALSE;
                    bOr  = FALSE;
                    if (string[0] == '&')
                    {
                        bAnd = TRUE;
                    }
                    else if (string[0] == '|')
                    {
                        bOr = TRUE;
                    }

                    if (bAnd || bOr)
                    {
                        string++;
                        nr1 = nr;
                        for (i = 0; i < nr; i++)
                        {
                            index1[i] = index[i];
                        }
                        strcpy(gname1, gname);
                        if (parse_entry(&string, natoms, atoms, block, gn, &nr2, index2, gname2))
                        {
                            if (bOr)
                            {
                                or_groups(nr1, index1, nr2, index2, &nr, index);
                                sprintf(gname, "%s_%s", gname1, gname2);
                            }
                            else
                            {
                                and_groups(nr1, index1, nr2, index2, &nr, index);
                                sprintf(gname, "%s_&_%s", gname1, gname2);
                            }
                        }
                    }
                }
                while (bAnd || bOr);
            }
            while (string[0] == ' ')
            {
                string++;
            }
            if (string[0])
            {
                printf("\nSyntax error: \"%s\"\n", string);
            }
            else if (nr > 0)
            {
                copy2block(nr, index, block);
                srenew(*gn, block->nr);
                newgroup        = block->nr-1;
                (*gn)[newgroup] = strdup(gname);
            }
            else
            {
                printf("Group is empty\n");
            }
        }
    }
    while (string[0] != 'q');

    sfree(index);
    sfree(index1);
    sfree(index2);
}
Example #20
0
int
do_lookup1(
	char *mapname,
	char *key,
	char *subdir,
	char *mapopts,
	char *path,
	uint_t isdirect,
	uid_t uid,
	autofs_action_t *action,
	struct linka *linkp)
{
	struct mapline ml;
	struct mapent *mapents = NULL;
	int err;
	struct autofs_rddir_cache *rdcp;
	int found = 0;
	bool_t iswildcard = FALSE;
	bool_t isrestricted = hasrestrictopt(mapopts);
	char *stack[STACKSIZ];
	char **stkptr = stack;

	/*
	 * Default action is for no work to be done by kernel AUTOFS.
	 */
	*action = AUTOFS_NONE;

	/*
	 * Is there a cache for this map?
	 */
	rw_rdlock(&autofs_rddir_cache_lock);
	err = autofs_rddir_cache_lookup(mapname, &rdcp);
	if (!err && rdcp->full) {
		rw_unlock(&autofs_rddir_cache_lock);
		/*
		 * Try to lock readdir cache entry for reading, if
		 * the entry can not be locked, then avoid blocking
		 * and go to the name service. I'm assuming it is
		 * faster to go to the name service than to wait for
		 * the cache to be populated.
		 */
		if (rw_tryrdlock(&rdcp->rwlock) == 0) {
			found = (rddir_entry_lookup(key, rdcp->entp) != NULL);
			rw_unlock(&rdcp->rwlock);
		}
	} else
		rw_unlock(&autofs_rddir_cache_lock);

	if (!err) {
		/*
		 * release reference on cache entry
		 */
		mutex_lock(&rdcp->lock);
		rdcp->in_use--;
		assert(rdcp->in_use >= 0);
		mutex_unlock(&rdcp->lock);
	}

	if (found)
		return (0);

	/*
	 * entry not found in cache, try the name service now
	 */
	err = 0;

	/* initialize the stack of open files for this thread */
	stack_op(INIT, NULL, stack, &stkptr);

	err = getmapent(key, mapname, &ml, stack, &stkptr, &iswildcard,
		isrestricted);
	if (err == 0) /* call parser w default mount_access = TRUE */
		mapents = parse_entry(key, mapname, mapopts, &ml,
				    subdir, isdirect, TRUE);

	/*
	 * Now we indulge in a bit of hanky-panky.
	 * If the entry isn't found in the map and the
	 * name begins with an "=" then we assume that
	 * the name is an undocumented control message
	 * for the daemon.  This is accessible only
	 * to superusers.
	 */
	if (mapents == NULL && *action == AUTOFS_NONE) {
		if (*key == '=' && uid == 0) {
			if (isdigit(*(key+1))) {
				/*
				 * If next character is a digit
				 * then set the trace level.
				 */
				trace = atoi(key+1);
				trace_prt(1, "Automountd: trace level = %d\n",
					trace);
			} else if (*(key+1) == 'v') {
				/*
				 * If it's a "v" then
				 * toggle verbose mode.
				 */
				verbose = !verbose;
				trace_prt(1, "Automountd: verbose %s\n",
						verbose ? "on" : "off");
			}
		}

		err = ENOENT;
		goto done;
	}

	/*
	 * Each mapent in the list describes a mount to be done.
	 * Since I'm only doing a lookup, I only care whether a mapentry
	 * was found or not. The mount will be done on a later RPC to
	 * do_mount1.
	 */
	if (mapents == NULL && *action == AUTOFS_NONE)
		err = ENOENT;

done:	if (mapents)
		free_mapent(mapents);

	if (*action == AUTOFS_NONE && (iswildcard == TRUE)) {
		*action = AUTOFS_MOUNT_RQ;
	}
	if (trace > 1) {
		trace_prt(1, "  do_lookup1: action=%d wildcard=%s error=%d\n",
			*action, iswildcard ? "TRUE" : "FALSE", err);
	}
	return (err);
}
Example #21
0
int
save_old_pass (pam_handle_t *pamh, const char *user, uid_t uid,
	       const char *oldpass, int howmany, int debug UNUSED)
{
  char opasswd_tmp[] = TMP_PASSWORDS_FILE;
  struct stat opasswd_stat;
  FILE *oldpf, *newpf;
  int newpf_fd;
  int do_create = 0;
  int retval = PAM_SUCCESS;
  char *buf = NULL;
  size_t buflen = 0;
  int found = 0;

  if (howmany <= 0)
    return PAM_SUCCESS;

  if (oldpass == NULL || *oldpass == '\0')
    return PAM_SUCCESS;

  if ((oldpf = fopen (OLD_PASSWORDS_FILE, "r")) == NULL)
    {
      if (errno == ENOENT)
	{
	  pam_syslog (pamh, LOG_NOTICE, "Creating %s",
		      OLD_PASSWORDS_FILE);
	  do_create = 1;
	}
      else
	{
	  pam_syslog (pamh, LOG_ERR, "Cannot open %s: %m",
		      OLD_PASSWORDS_FILE);
	  return PAM_AUTHTOK_ERR;
	}
    }
  else if (fstat (fileno (oldpf), &opasswd_stat) < 0)
    {
      pam_syslog (pamh, LOG_ERR, "Cannot stat %s: %m", OLD_PASSWORDS_FILE);
      fclose (oldpf);
      return PAM_AUTHTOK_ERR;
    }

  /* Open a temp passwd file */
  newpf_fd = mkstemp (opasswd_tmp);
  if (newpf_fd == -1)
    {
      pam_syslog (pamh, LOG_ERR, "Cannot create %s temp file: %m",
		  OLD_PASSWORDS_FILE);
      if (oldpf)
	fclose (oldpf);
      return PAM_AUTHTOK_ERR;
    }
  if (do_create)
    {
      if (fchmod (newpf_fd, S_IRUSR|S_IWUSR) != 0)
	pam_syslog (pamh, LOG_ERR,
		    "Cannot set permissions of %s temp file: %m",
		    OLD_PASSWORDS_FILE);
      if (fchown (newpf_fd, 0, 0) != 0)
	pam_syslog (pamh, LOG_ERR,
		    "Cannot set owner/group of %s temp file: %m",
		    OLD_PASSWORDS_FILE);
    }
  else
    {
      if (fchmod (newpf_fd, opasswd_stat.st_mode) != 0)
	pam_syslog (pamh, LOG_ERR,
		    "Cannot set permissions of %s temp file: %m",
		    OLD_PASSWORDS_FILE);
      if (fchown (newpf_fd, opasswd_stat.st_uid, opasswd_stat.st_gid) != 0)
	pam_syslog (pamh, LOG_ERR,
		    "Cannot set owner/group of %s temp file: %m",
		    OLD_PASSWORDS_FILE);
    }
  newpf = fdopen (newpf_fd, "w+");
  if (newpf == NULL)
    {
      pam_syslog (pamh, LOG_ERR, "Cannot fdopen %s: %m", opasswd_tmp);
      if (oldpf)
	fclose (oldpf);
      close (newpf_fd);
      retval = PAM_AUTHTOK_ERR;
      goto error_opasswd;
    }

  if (!do_create)
    while (!feof (oldpf))
      {
	char *cp, *tmp, *save;
#if defined(HAVE_GETLINE)
	ssize_t n = getline (&buf, &buflen, oldpf);
#elif defined (HAVE_GETDELIM)
	ssize_t n = getdelim (&buf, &buflen, '\n', oldpf);
#else
	ssize_t n;

	if (buf == NULL)
	  {
	    buflen = DEFAULT_BUFLEN;
	    buf = malloc (buflen);
	    if (buf == NULL)
              {
		fclose (oldpf);
		fclose (newpf);
		retval = PAM_BUF_ERR;
		goto error_opasswd;
              }
	  }
	buf[0] = '\0';
	fgets (buf, buflen - 1, oldpf);
	n = strlen (buf);
#endif /* HAVE_GETLINE / HAVE_GETDELIM */

	cp = buf;
	save = strdup (buf); /* Copy to write the original data back.  */
	if (save == NULL)
          {
	    fclose (oldpf);
	    fclose (newpf);
	    retval = PAM_BUF_ERR;
	    goto error_opasswd;
          }

	if (n < 1)
	  break;

	tmp = strchr (cp, '#');  /* remove comments */
	if (tmp)
	  *tmp = '\0';
	while (isspace ((int)*cp))    /* remove spaces and tabs */
	  ++cp;
	if (*cp == '\0')        /* ignore empty lines */
	  goto write_old_data;

	if (cp[strlen (cp) - 1] == '\n')
	  cp[strlen (cp) - 1] = '\0';

	if (strncmp (cp, user, strlen (user)) == 0 &&
	    cp[strlen (user)] == ':')
	  {
	    /* We found the line we needed */
	    opwd entry;

	    if (parse_entry (cp, &entry) == 0)
	      {
		char *out = NULL;

		found = 1;

		/* Don't save the current password twice */
		if (entry.old_passwords && entry.old_passwords[0] != '\0')
		  {
		    char *last = entry.old_passwords;

		    cp = entry.old_passwords;
		    entry.count = 1;  /* Don't believe the count */
		    while ((cp = strchr (cp, ',')) != NULL)
		      {
			entry.count++;
			last = ++cp;
		      }

		    /* compare the last password */
		    if (strcmp (last, oldpass) == 0)
		      goto write_old_data;
		  }
		else
		  entry.count = 0;

		/* increase count.  */
		entry.count++;

		/* check that we don't remember to many passwords.  */
		while (entry.count > howmany && entry.count > 1)
		  {
		    char *p = strpbrk (entry.old_passwords, ",");
		    if (p != NULL)
		      entry.old_passwords = ++p;
		    entry.count--;
		  }

		if (entry.count == 1)
		  {
		    if (asprintf (&out, "%s:%s:%d:%s\n",
				  entry.user, entry.uid, entry.count,
				  oldpass) < 0)
		      {
		        free (save);
			retval = PAM_AUTHTOK_ERR;
			fclose (oldpf);
			fclose (newpf);
			goto error_opasswd;
		      }
		  }
		else
		  {
		    if (asprintf (&out, "%s:%s:%d:%s,%s\n",
				  entry.user, entry.uid, entry.count,
				  entry.old_passwords, oldpass) < 0)
		      {
		        free (save);
			retval = PAM_AUTHTOK_ERR;
			fclose (oldpf);
			fclose (newpf);
			goto error_opasswd;
		      }
		  }

		if (fputs (out, newpf) < 0)
		  {
		    free (out);
		    free (save);
		    retval = PAM_AUTHTOK_ERR;
		    fclose (oldpf);
		    fclose (newpf);
		    goto error_opasswd;
		  }
		free (out);
	      }
	  }
	else
	  {
	  write_old_data:
	    if (fputs (save, newpf) < 0)
	      {
		free (save);
		retval = PAM_AUTHTOK_ERR;
		fclose (oldpf);
		fclose (newpf);
		goto error_opasswd;
	      }
	  }
	free (save);
      }

  if (!found)
    {
      char *out;

      if (asprintf (&out, "%s:%d:1:%s\n", user, uid, oldpass) < 0)
	{
	  retval = PAM_AUTHTOK_ERR;
	  if (oldpf)
	    fclose (oldpf);
	  fclose (newpf);
	  goto error_opasswd;
	}
      if (fputs (out, newpf) < 0)
	{
	  free (out);
	  retval = PAM_AUTHTOK_ERR;
	  if (oldpf)
	    fclose (oldpf);
	  fclose (newpf);
	  goto error_opasswd;
	}
      free (out);
    }

  if (oldpf)
    if (fclose (oldpf) != 0)
      {
	pam_syslog (pamh, LOG_ERR, "Error while closing old opasswd file: %m");
	retval = PAM_AUTHTOK_ERR;
	fclose (newpf);
	goto error_opasswd;
      }

  if (fflush (newpf) != 0 || fsync (fileno (newpf)) != 0)
    {
      pam_syslog (pamh, LOG_ERR,
		  "Error while syncing temporary opasswd file: %m");
      retval = PAM_AUTHTOK_ERR;
      fclose (newpf);
      goto error_opasswd;
    }

  if (fclose (newpf) != 0)
    {
      pam_syslog (pamh, LOG_ERR,
		  "Error while closing temporary opasswd file: %m");
      retval = PAM_AUTHTOK_ERR;
      goto error_opasswd;
    }

  unlink (OLD_PASSWORDS_FILE".old");
  if (link (OLD_PASSWORDS_FILE, OLD_PASSWORDS_FILE".old") != 0 &&
      errno != ENOENT)
    pam_syslog (pamh, LOG_ERR, "Cannot create backup file of %s: %m",
		OLD_PASSWORDS_FILE);
  rename (opasswd_tmp, OLD_PASSWORDS_FILE);
 error_opasswd:
  unlink (opasswd_tmp);
  free (buf);

  return retval;
}
Example #22
0
/* Check, if the new password is already in the opasswd file.  */
int
check_old_pass (pam_handle_t *pamh, const char *user,
		const char *newpass, int debug)
{
  int retval = PAM_SUCCESS;
  FILE *oldpf;
  char *buf = NULL;
  size_t buflen = 0;
  opwd entry;
  int found = 0;

  if ((oldpf = fopen (OLD_PASSWORDS_FILE, "r")) == NULL)
    {
      if (errno != ENOENT)
	pam_syslog (pamh, LOG_ERR, "Cannot open %s: %m", OLD_PASSWORDS_FILE);
      return PAM_SUCCESS;
    }

  while (!feof (oldpf))
    {
      char *cp, *tmp;
#if defined(HAVE_GETLINE)
      ssize_t n = getline (&buf, &buflen, oldpf);
#elif defined (HAVE_GETDELIM)
      ssize_t n = getdelim (&buf, &buflen, '\n', oldpf);
#else
      ssize_t n;

      if (buf == NULL)
        {
          buflen = DEFAULT_BUFLEN;
          buf = malloc (buflen);
	  if (buf == NULL)
	    return PAM_BUF_ERR;
        }
      buf[0] = '\0';
      fgets (buf, buflen - 1, oldpf);
      n = strlen (buf);
#endif /* HAVE_GETLINE / HAVE_GETDELIM */
      cp = buf;

      if (n < 1)
        break;

      tmp = strchr (cp, '#');  /* remove comments */
      if (tmp)
        *tmp = '\0';
      while (isspace ((int)*cp))    /* remove spaces and tabs */
        ++cp;
      if (*cp == '\0')        /* ignore empty lines */
        continue;

      if (cp[strlen (cp) - 1] == '\n')
        cp[strlen (cp) - 1] = '\0';

      if (strncmp (cp, user, strlen (user)) == 0 &&
          cp[strlen (user)] == ':')
        {
          /* We found the line we needed */
	  if (parse_entry (cp, &entry) == 0)
	    {
	      found = 1;
	      break;
	    }
	}
    }

  fclose (oldpf);

  if (found && entry.old_passwords)
    {
      const char delimiters[] = ",";
      char *running;
      char *oldpass;

      running = entry.old_passwords;

      do {
	oldpass = strsep (&running, delimiters);
	if (oldpass && strlen (oldpass) > 0 &&
	    compare_password(newpass, oldpass) )
	  {
	    if (debug)
	      pam_syslog (pamh, LOG_DEBUG, "New password already used");
	    retval = PAM_AUTHTOK_ERR;
	    break;
	  }
      } while (oldpass != NULL);
    }

  if (buf)
    free (buf);

  return retval;
}
Example #23
0
static unsigned long get_cached_size(void)
{
	char entry[] = "Cached: %lu";
	return parse_entry(meminfo_fname, entry);
}
Example #24
0
/*
 * Import authlist from the userspace
 */
static int write_authlist(struct authlist *authlist, void __user *buffer,
			  size_t *lenp, loff_t *ppos)
{
	struct authlist_entry *entries = NULL, *old_entries;
	char *memblk = NULL;
	int error = 0;
	int nentries;
	int ne;
	int terminal = -1;
	const char *p;

	/* ensure atomic transfer */
	if (*ppos != 0)
		return -EINVAL;

	if (*lenp > AUTHLIST_LENGTH_LIMIT)
		return -EINVAL;

	memblk = kmalloc(*lenp + 1, GFP_KERNEL);
	if (memblk == NULL)
		return -ENOMEM;

	if (copy_from_user(memblk, buffer, *lenp))
		error_out(-EFAULT);

	memblk[*lenp] = '\0';

	nentries = count_entries(memblk);
	if (nentries == 0)
		error_out(-EINVAL);

	entries = kmalloc(sizeof(struct authlist_entry) * nentries, GFP_KERNEL);
	if (entries == NULL)
		error_out(-ENOMEM);

	for (p = memblk, ne = 0;; ne++) {
		/* skip leading whitespace */
		while (is_ws(*p))
			p++;

		/* reached the end of the string? */
		if (*p == '\0')
			break;

		error = parse_entry(&p, entries + ne);
		if (error)
			goto out;

		switch (entries[ne].kind) {
		case AUTHLIST_KIND_EVERYBODY:
		case AUTHLIST_KIND_NOBODY:
			if (terminal != -1)
				error_out(-EINVAL);
			terminal = ne;
			break;

		default:
			break;
		}
	}

	/*
	 * Last entry must be everybody/nobody.
	 * Intermediate entry cannot be everybody/nobody.
	 */
	if (terminal != nentries - 1)
		error_out(-EINVAL);

	down_write(&authlist->rws);
	old_entries = authlist->entries;
	authlist->nentries = nentries;
	authlist->entries = entries;
	up_write(&authlist->rws);

	kfree(old_entries);
	entries = NULL;

	*ppos += *lenp;

out:

	kfree(memblk);
	kfree(entries);

	return error;
}
Example #25
0
File: rdup-up.c Project: miekg/rdup
/* update the directory with the archive */
static gboolean update(char *path)
{
	struct rdup *rdup_entry;
	size_t line, i, pathsize;
	size_t pathlen;
	char *buf, *pathbuf, *n, *p;
	char delim;
	gboolean ok;
	GHashTable *uidhash;	/* holds username -> uid */
	GHashTable *gidhash;	/* holds groupname -> gid */

        p = NULL;
	buf = g_malloc(BUFSIZE + 1);
	pathbuf = g_malloc(BUFSIZE + 1);
	i = BUFSIZE;
	delim = '\n';
	line = 0;
	ok = TRUE;
	uidhash = g_hash_table_new(g_str_hash, g_str_equal);
	gidhash = g_hash_table_new(g_str_hash, g_str_equal);
	if (path)
		pathlen = strlen(path);
	else
		pathlen = 0;

	while ((rdup_getdelim(&buf, &i, delim, stdin)) != -1) {
		line++;
		n = strrchr(buf, '\n');
		if (n)
			*n = '\0';

		if (!(rdup_entry = parse_entry(buf, line))) {
			/* msgs from entry.c */
			exit(EXIT_FAILURE);
		}

		/* we have a valid entry, read the filename */
		pathsize =
		    fread(pathbuf, sizeof(char), rdup_entry->f_name_size,
			  stdin);

		if (pathsize != rdup_entry->f_name_size) {
			msg(_
			    ("Reported name size (%zd) does not match actual name size (%zd)"),
			    rdup_entry->f_name_size, pathsize);
			exit(EXIT_FAILURE);
		}
		pathbuf[pathsize] = '\0';
		if (pathbuf[0] != '/') {
			msg(_("Pathname does not start with /: `%s\'"),
			    pathbuf);
			exit(EXIT_FAILURE);
		}

		rdup_entry->f_name = pathbuf;

		/* extract target from rdup_entry */
		if (S_ISLNK(rdup_entry->f_mode) || rdup_entry->f_lnk) {
			// filesize is spot where to cut
			rdup_entry->f_name[rdup_entry->f_size] = '\0';
			rdup_entry->f_target = rdup_entry->f_name +
			    rdup_entry->f_size + 4;
		} else {
			rdup_entry->f_target = NULL;
		}

		/* strippath must be inserted here */
		if (opt_strip)
			strippath(rdup_entry);

		if (opt_path_strip)
			strippathname(rdup_entry);

		if (!rdup_entry->f_name)
			p = NULL;
		else {
			/* avoid // at the beginning */
			if ((pathlen == 1 && path[0] == '/') || pathlen == 0) {
				p = g_strdup(rdup_entry->f_name);
			} else {
                                g_free(p);
				p = g_strdup_printf("%s%s", path,
						    rdup_entry->f_name);
				rdup_entry->f_name_size += pathlen;
				if (S_ISLNK(rdup_entry->f_mode)
				    || rdup_entry->f_lnk)
					rdup_entry->f_size += pathlen;
			}
		}
		rdup_entry->f_name = p;
		if (mk_obj(stdin, path, rdup_entry, uidhash, gidhash) == FALSE)
			ok = FALSE;
		g_free(rdup_entry->f_user);
		g_free(rdup_entry->f_group);
		g_free(rdup_entry);
	}

	/* post-process hardlinks */
	if (mk_hlink(hlink_list) == FALSE)
		ok = FALSE;

	g_free(buf);
	g_free(pathbuf);
	return ok;
}
Example #26
0
void
read_v23_status()
{
  FILE *fp;
  char buffer[MAX_CHARS_PER_LINE];
  struct status_dot_dat_entry ent;
  int i, host_stamp, service_stamp, eof;

#ifdef _DEBUG_
debug("read_v23_status()...");
debug("status file is %s",STATUS_DAT_FILE);
#endif

  /*--------------------------------------------------------*/
  mvaddstr(LINES-1-pad,pad,"reading status.dat...");
  refresh();

  /*--------------------------------------------------------*/
  if ((fp = fopen(STATUS_DAT_FILE, "r")) == NULL) {
    endwin();
    fprintf(stderr,"fatal error: fopen %s ",STATUS_DAT_FILE);
    perror("failed");
    exit(1);
  }
  line = 0;

  /*--------------------------------------------------------*/
  /* read last update */

  fgets(buffer,sizeof(buffer),fp); line++;
  while ( !feof(fp) && strcmp(buffer,"info {\n") != 0 ) {
    fgets(buffer,sizeof(buffer),fp); line++;
  }
  if ( strcmp(buffer,"info {\n") != 0 ) {
    endwin();
    printf("fatal error: %s: could not find \"info\" stanza\n", STATUS_DAT_FILE);
    exit(1);
  }
  fgets(buffer,sizeof(buffer),fp); line++;
  parse_entry(&ent,buffer);
  while ( !feof(fp) && strcmp(ent.lhs,"created") != 0 ) {
    fgets(buffer,sizeof(buffer),fp); line++;
    parse_entry(&ent,buffer);
  }
  if ( !strcmp(ent.lhs,"created") ) {
    last_update_int = atoi(ent.rhs);
    strncpy(last_update,ctime((time_t *)&last_update_int),19);
    last_update[20] = '\0';
  } else {
    endwin();
    printf("fatal error: %s: could not find \"created\" entry\n", STATUS_DAT_FILE);
    exit(1);
  }
#ifdef _DEBUG_
debug("last update is %s (%d)",last_update,last_update_int);
#endif


  /*--------------------------------------------------------*/
  num_okay = num_warn = num_crit = 0;
  host_list_size = service_list_size = 0;
  num_up = num_down = 0;

  while ( fgets(buffer,sizeof(buffer),fp) != NULL ) { 
    line++;
    parse_entry(&ent,buffer);
    if ( !strcmp(ent.lhs,"fail") ) { continue; }

    /*--------------------------------------------------------*/
    /* HOST object... */
    if ( (!strcmp("host",ent.lhs)) || (!strcmp("hoststatus",ent.lhs)) ) {

      /*--------------------*/
      /* HOST_NAME... */
      fgets(buffer,sizeof(buffer),fp); line++;
      parse_entry(&ent,buffer);
      while ( !feof(fp) && strcmp(ent.lhs,"host_name") != 0 ) {
        fgets(buffer,sizeof(buffer),fp); line++;
        parse_entry(&ent,buffer);
        if ( !strcmp(ent.lhs,"fail") ) { 
          endwin();
          printf("fatal error: %s: could not find \"host_name\" for host stanza preceeding line %d\n", 
            STATUS_DAT_FILE, line);
          exit(1);
        }
      }
      if ( strcmp(ent.lhs,"host_name") ) {
        endwin();
        printf("fatal error: %s: could not find \"host_name\" for host stanza preceeding line %d\n", 
          STATUS_DAT_FILE, line);
        exit(1);
      }
      host_list[host_list_size][HOST_NAME] = malloc(strlen(ent.rhs)+1);
      strncpy(host_list[host_list_size][HOST_NAME],ent.rhs,strlen(ent.rhs)+1);
#ifdef _DEBUG_
debug("HOST NUMBER %d...", host_list_size);
debug("  host_name is \"%s\"",host_list[host_list_size][HOST_NAME]);
#endif

      /*--------------------*/
      /* STATUS... */
      fgets(buffer,sizeof(buffer),fp); line++;
      parse_entry(&ent,buffer);
      while ( !feof(fp) && strcmp(ent.lhs,"current_state") != 0 ) {
        fgets(buffer,sizeof(buffer),fp); line++;
        parse_entry(&ent,buffer);
        if ( !strcmp(ent.lhs,"fail") ) { 
          endwin();
          printf("fatal error: %s: could not find \"current_state\" for host stanza preceeding line %d\n", 
            STATUS_DAT_FILE, line);
          exit(1);
        }
      }
      if ( strcmp(ent.lhs,"current_state") ) {
        endwin();
        printf("fatal error: %s: could not find \"current_state\" for host stanza preceeding line %d\n", 
          STATUS_DAT_FILE, line);
        exit(1);
      }
      switch(ent.rhs[0]) {
        case NAGIOS_HOST_UP:
          host_list[host_list_size][STATUS] = malloc(3); 
          strncpy(host_list[host_list_size][STATUS],"UP",3);
        break;
        case NAGIOS_HOST_DOWN:
          host_list[host_list_size][STATUS] = malloc(5);
          strncpy(host_list[host_list_size][STATUS],"DOWN",5);
        break;
      }
#ifdef _DEBUG_
debug("  current_state is %s", host_list[host_list_size][STATUS]);
#endif

      /*--------------------*/
      /* PLUGIN_OUTPUT... */
      fgets(buffer,sizeof(buffer),fp); line++;
      parse_entry(&ent,buffer);
      while ( !feof(fp) && strcmp(ent.lhs,"plugin_output") != 0 ) {
        fgets(buffer,sizeof(buffer),fp); line++;
        parse_entry(&ent,buffer);
        if ( !strcmp(ent.lhs,"fail") ) { 
          endwin();
          printf("fatal error: %s: could not find \"plugin_output\" for host stanza preceeding line %d\n", 
            STATUS_DAT_FILE, line);
          exit(1);
        }
      }
      if ( strcmp(ent.lhs,"plugin_output") ) {
        endwin();
        printf("fatal error: %s: could not find \"plugin_output\" for host stanza preceeding line %d\n", 
          STATUS_DAT_FILE, line);
        exit(1);
      }
      host_list[host_list_size][PLUGIN_OUTPUT] = malloc(strlen(ent.rhs)+1);
      strncpy(host_list[host_list_size][PLUGIN_OUTPUT],ent.rhs,strlen(ent.rhs)+1);
      perl_hook(HOST_PLUGIN_HOOK,host_list[host_list_size][PLUGIN_OUTPUT]);
#ifdef _DEBUG_
debug("  raw plugin_output is \"%s\"",ent.rhs);
debug("  munged plugin_output is \"%s\"",host_list[host_list_size][PLUGIN_OUTPUT]);
#endif

      /*--------------------*/
      /* LAST_STATE_CHANGE... */
      fgets(buffer,sizeof(buffer),fp); line++;
      parse_entry(&ent,buffer);
      while ( !feof(fp) && strcmp(ent.lhs,"last_state_change") != 0 ) {
        fgets(buffer,sizeof(buffer),fp); line++;
        parse_entry(&ent,buffer);
        if ( !strcmp(ent.lhs,"fail") ) { 
          endwin();
          printf("fatal error: %s: could not find \"last_state_change\" for host stanza preceeding line %d\n", 
            STATUS_DAT_FILE, line);
          exit(1);
        }
      }
      if ( strcmp(ent.lhs,"last_state_change") ) {
        endwin();
        printf("fatal error: %s: could not find \"last_state_change\" for host stanza preceeding line %d\n", 
          STATUS_DAT_FILE, line);
        exit(1);
      }
      sscanf(ent.rhs,"%d",&host_stamp);
      if ( (host_stamp == 0) && (host_list[host_list_size][PLUGIN_OUTPUT][0] == '\0') ) {
#ifdef _DEBUG_
debug("  current_state is PENDING, inferred from empty plugin output on Jan 1 1970");
#endif
        /* PENDING... is really UP with NULL plugin output on Jan 1 1970... */
        free(host_list[host_list_size][STATUS]);
        host_list[host_list_size][STATUS] = malloc(8);
        strncpy(host_list[host_list_size][STATUS],"PENDING",8);
        free(host_list[host_list_size][PLUGIN_OUTPUT]);
        host_list[host_list_size][PLUGIN_OUTPUT] = malloc(25);
        strncpy(host_list[host_list_size][PLUGIN_OUTPUT],"(Host assumed to be up)",25);
        perl_hook(HOST_PLUGIN_HOOK,host_list[host_list_size][PLUGIN_OUTPUT]);
        host_stamp = last_update_int;
        host_list[host_list_size][LAST_STATE_CHANGE_INT] = (char *)(last_update_int);
        host_list[host_list_size][LAST_STATE_CHANGE] = malloc(17); 
        strncpy(host_list[host_list_size][LAST_STATE_CHANGE]," not applicable ",16);
      } else { 
        host_list[host_list_size][LAST_STATE_CHANGE_INT] = (char *)host_stamp;
        host_list[host_list_size][LAST_STATE_CHANGE] = malloc(17); /* "DOW Mon DD HH:MM\0" */
        strncpy(host_list[host_list_size][LAST_STATE_CHANGE],ctime((time_t *)&host_stamp),16);
      }
      host_list[host_list_size][LAST_STATE_CHANGE][16] = '\0';
#ifdef _DEBUG_
debug("  last_state_change is \"%s\" (%d)",
  host_list[host_list_size][LAST_STATE_CHANGE],
  (int)host_list[host_list_size][LAST_STATE_CHANGE_INT]);
#endif

      /*--------------------*/
      /* DURATION... */
      host_list[host_list_size][DURATION] = (char *)calc_duration(host_stamp);
#ifdef _DEBUG_
debug("  duration is \"%s\"",host_list[host_list_size][DURATION]);
#endif
 
      /*--------------------*/
      /* Other stuff... */
      host_idx_to_level[host_list_size] = convert_level(host_list[host_list_size][STATUS]);
      switch(host_idx_to_level[host_list_size]) {
        case UP: num_up++;     break;
        case DOWN: num_down++; break;
      }
#if 0
      debug("HOST idx=%d: NAME=%s STATUS=%s LAST_CHANGE=%s",
        host_list_size,
        host_list[host_list_size][HOST_NAME],
        host_list[host_list_size][STATUS],
        host_list[host_list_size][LAST_STATE_CHANGE]
      );
#endif
      host_list_size++;
      if ( host_list_size > MAX_ITEMS ) {
        endwin();
        printf("fatal error: too many hosts!\n");  
        printf("increase MAX_ITEMS in cnagios.h\n");
        exit(1);
      }
      continue;

    }

    /*--------------------------------------------------------*/
    /* SERVICE object... */
    if ( (!strcmp("service",ent.lhs)) || (!strcmp("servicestatus",ent.lhs)) ) {

      /*--------------------*/
      /* HOST_NAME... */
      fgets(buffer,sizeof(buffer),fp); line++;
      parse_entry(&ent,buffer);
      while ( !feof(fp) && strcmp(ent.lhs,"host_name") != 0 ) {
        fgets(buffer,sizeof(buffer),fp); line++;
        parse_entry(&ent,buffer);
        if ( !strcmp(ent.lhs,"fail") ) {
          endwin();
          printf("fatal error: %s: could not find \"host_name\" for service stanza preceeding line %d\n",
            STATUS_DAT_FILE, line);
          exit(1);
        }
      }
      if ( strcmp(ent.lhs,"host_name") ) {
        endwin();
        printf("fatal error: %s: could not find \"host_name\" for service stanza preceeding line %d\n",
          STATUS_DAT_FILE, line);
        exit(1);
      }
      service_list[service_list_size][HOST_NAME] = malloc(strlen(ent.rhs)+1);
      strncpy(service_list[service_list_size][HOST_NAME],ent.rhs,strlen(ent.rhs)+1);
#ifdef _DEBUG_
debug("SERVICE NUMBER %d...",service_list_size);
debug("  host_name is \"%s\"",service_list[service_list_size][HOST_NAME]);
#endif

      /*--------------------*/
      /* SERVICE_NAME... */
      fgets(buffer,sizeof(buffer),fp); line++;
      parse_entry(&ent,buffer);
      while ( !feof(fp) && strcmp(ent.lhs,"service_description") != 0 ) {
        fgets(buffer,sizeof(buffer),fp); line++;
        parse_entry(&ent,buffer);
        if ( !strcmp(ent.lhs,"fail") ) {
          endwin();
          printf("fatal error: %s: could not find \"service_description\" for service stanza preceeding line %d\n",
            STATUS_DAT_FILE, line);
          exit(1);
        }
      }
      if ( strcmp(ent.lhs,"service_description") ) {
        endwin();
        printf("fatal error: %s: could not find \"service_description\" for service stanza preceeding line %d\n",
          STATUS_DAT_FILE, line);
        exit(1);
      }
      service_list[service_list_size][SERVICE_NAME] =
        malloc(strlen(ent.rhs)+1+strlen(service_list[service_list_size][HOST_NAME])+1);
      snprintf(service_list[service_list_size][SERVICE_NAME],(strlen(ent.rhs)+1+strlen(service_list[service_list_size][HOST_NAME])+1),"%s %s ",
        service_list[service_list_size][HOST_NAME],ent.rhs);
      perl_hook(SERVICE_PLUGIN_HOOK,service_list[service_list_size][SERVICE_NAME]);
#ifdef _DEBUG_
debug("  raw service_description is \"%s\"",ent.rhs);
debug("  munged service_description is \"%s\"",service_list[service_list_size][SERVICE_NAME]);
#endif

      /*--------------------*/
      /* STATUS... */
      fgets(buffer,sizeof(buffer),fp); line++;
      parse_entry(&ent,buffer);
      while ( !feof(fp) && strcmp(ent.lhs,"current_state") != 0 ) {
        fgets(buffer,sizeof(buffer),fp); line++;
        parse_entry(&ent,buffer);
        if ( !strcmp(ent.lhs,"fail") ) {
          endwin();
          printf("fatal error: %s: could not find \"current_state\" for service stanza preceeding line %d\n",
            STATUS_DAT_FILE, line);
          exit(1);
        }
      }
      if ( strcmp(ent.lhs,"current_state") ) {
        endwin();
        printf("fatal error: %s: could not find \"current_state\" for service stanza preceeding line %d\n",
          STATUS_DAT_FILE, line);
        exit(1);
      }
      switch(ent.rhs[0]) {
        case NAGIOS_STATE_OK:
          service_list[service_list_size][STATUS] = malloc(5);
          strncpy(service_list[service_list_size][STATUS],"OKAY",5);
        break;
        case NAGIOS_STATE_WARNING:
          service_list[service_list_size][STATUS] = malloc(8);
          strncpy(service_list[service_list_size][STATUS],"WARNING",8);
        break;
        case NAGIOS_STATE_CRITICAL:
          service_list[service_list_size][STATUS] = malloc(9);
          strncpy(service_list[service_list_size][STATUS],"CRITICAL",9);
        break;
        case NAGIOS_STATE_UNKNOWN:
          service_list[service_list_size][STATUS] = malloc(8);
          strncpy(service_list[service_list_size][STATUS],"UNKNOWN",8);
        break;
      }
#ifdef _DEBUG_
debug("  current_state is %s",service_list[service_list_size][STATUS]);
#endif

      /*--------------------*/
      /* LAST_STATE_CHANGE... */
      fgets(buffer,sizeof(buffer),fp); line++;
      parse_entry(&ent,buffer);
      while ( !feof(fp) && strcmp(ent.lhs,"last_state_change") != 0 ) {
        fgets(buffer,sizeof(buffer),fp); line++;
        parse_entry(&ent,buffer);
        if ( !strcmp(ent.lhs,"fail") ) {
          endwin();
          printf("fatal error: %s: could not find \"last_state_change\" for service stanza preceeding line %d\n",
            STATUS_DAT_FILE, line);
          exit(1);
        }
      }
      if ( strcmp(ent.lhs,"last_state_change") ) {
        endwin();
        printf("fatal error: %s: could not find \"last_state_change\" for service stanza preceeding line %d\n",
          STATUS_DAT_FILE, line);
        exit(1);
      }

      sscanf(ent.rhs,"%d",&service_stamp);
      service_list[service_list_size][LAST_STATE_CHANGE_INT] = (char *)service_stamp;
      service_list[service_list_size][LAST_STATE_CHANGE] = malloc(17); /* "DOW Mon DD HH:MM\0" */
      strncpy(service_list[service_list_size][LAST_STATE_CHANGE],ctime((time_t *)&service_stamp),16);
      service_list[service_list_size][LAST_STATE_CHANGE][16] = '\0';
#ifdef _DEBUG_
debug("  last_state_change is \"%s\" (%d)",
  service_list[service_list_size][LAST_STATE_CHANGE],
  (int)service_list[service_list_size][LAST_STATE_CHANGE_INT]);
#endif

      /*--------------------*/
      /* DURATION... */
      service_list[service_list_size][DURATION] = (char *)calc_duration(service_stamp);
#ifdef _DEBUG_
debug("  duration is \"%s\"",service_list[service_list_size][DURATION]);
#endif

      /*--------------------*/
      /* PLUGIN_OUTPUT... */
      fgets(buffer,sizeof(buffer),fp); line++;
      parse_entry(&ent,buffer);
      while ( !feof(fp) && strcmp(ent.lhs,"plugin_output") != 0 ) {
        fgets(buffer,sizeof(buffer),fp); line++;
        parse_entry(&ent,buffer);
        if ( !strcmp(ent.lhs,"fail") ) {
          endwin();
          printf("fatal error: %s: could not find \"plugin_output\" for service stanza preceeding line %d\n",
            STATUS_DAT_FILE, line);
          exit(1);
        }
      }
      if ( strcmp(ent.lhs,"plugin_output") ) {
        endwin();
        printf("fatal error: %s: could not find \"plugin_output\" for service stanza preceeding line %d\n",
          STATUS_DAT_FILE, line);
        exit(1);
      }
      service_list[service_list_size][PLUGIN_OUTPUT] = malloc(strlen(ent.rhs)+1);
      strncpy(service_list[service_list_size][PLUGIN_OUTPUT],ent.rhs,strlen(ent.rhs)+1);
      perl_hook(SERVICE_PLUGIN_HOOK,service_list[service_list_size][PLUGIN_OUTPUT]);
#ifdef _DEBUG_
debug("  raw plugin_output is \"%s\"",ent.rhs);
debug("  munged plugin_output is \"%s\"",service_list[service_list_size][PLUGIN_OUTPUT]);
#endif
      /* PENDING is really OKAY w/ "(Service assumed to be ok)" on Jan 1 1970... */
      if ( (service_stamp == 0) && (!strcmp("(Service assumed to be ok)",ent.rhs)) ) {
#ifdef _DEBUG_
debug("  current_state is PENDING, inferred from \"(Service assumed to be ok)\" on Jan 1 1970");
#endif
        free(service_list[service_list_size][STATUS]);
        service_list[service_list_size][STATUS] = malloc(8);
        strncpy(service_list[service_list_size][STATUS],"PENDING",8);
        service_stamp = last_update_int;
        service_list[service_list_size][LAST_STATE_CHANGE_INT] = (char *)service_stamp;
        service_list[service_list_size][LAST_STATE_CHANGE] = malloc(17); /* "DOW Mon DD HH:MM\0" */
        strncpy(service_list[service_list_size][LAST_STATE_CHANGE]," not applicable ",17);
        service_list[service_list_size][DURATION] = (char *)calc_duration(service_stamp);
      }

      /*--------------------*/
      /* Other stuff... */
      service_idx_to_level[service_list_size] = 
         convert_level(service_list[service_list_size][STATUS]);
      switch(service_idx_to_level[service_list_size]) {
        case 0: num_okay++;  break;
        case 1: num_warn++;  break;
        case 2: num_crit++;  break;
      }
#if 0
      debug("SERVICE idx=%d: NAME=%s SERVICE=%s STATUS=%s LAST_CHANGE=%s",
        service_list_size,
        service_list[service_list_size][HOST_NAME],
        service_list[service_list_size][SERVICE_NAME],
        service_list[service_list_size][STATUS],
        service_list[service_list_size][LAST_STATE_CHANGE]
      );
#endif
      service_list_size++;
      if ( service_list_size > MAX_ITEMS ) { 
        endwin();
        printf("fatal error: too many services!\n");
        printf("increase MAX_ITEMS in cnagios.h\n");
        exit(1);
      }
      continue;

    }

  }

  /*--------------------------------------------------------*/

  fclose(fp);

#if _DEBUG_
  debug("done with read_v23_status()");
#endif

}
Example #27
0
File: text.c Project: Axure/librime
Dict* dict_text_new(const char* filename) {
  TextDict* text_dictionary;

  text_dictionary = (TextDict*)malloc(sizeof(TextDict));
  text_dictionary->entry_count = INITIAL_DICTIONARY_SIZE;
  text_dictionary->max_length = 0;
  text_dictionary->lexicon = (TextEntry*)malloc(
    sizeof(TextEntry) * text_dictionary->entry_count);
  text_dictionary->word_buff = NULL;

  static char buff[ENTRY_BUFF_SIZE];

  FILE* fp = fopen(filename, "r");

  if (fp == NULL) {
    dict_text_delete((Dict*)text_dictionary);
    return (Dict*)-1;
  }
  skip_utf8_bom(fp);

  size_t i = 0;

  while (fgets(buff, ENTRY_BUFF_SIZE, fp)) {
    if (i >= text_dictionary->entry_count) {
      text_dictionary->entry_count += text_dictionary->entry_count;
      text_dictionary->lexicon = (TextEntry*)realloc(
        text_dictionary->lexicon,
        sizeof(TextEntry) * text_dictionary->entry_count
        );
    }

    if (parse_entry(buff, text_dictionary->lexicon + i) == -1) {
      text_dictionary->entry_count = i;
      dict_text_delete((Dict*)text_dictionary);
      return (Dict*)-1;
    }

    size_t length = ucs4len(text_dictionary->lexicon[i].key);

    if (length > text_dictionary->max_length) {
      text_dictionary->max_length = length;
    }

    i++;
  }

  fclose(fp);

  text_dictionary->entry_count = i;
  text_dictionary->lexicon = (TextEntry*)realloc(
    text_dictionary->lexicon,
    sizeof(TextEntry) * text_dictionary->entry_count
    );
  text_dictionary->word_buff = (ucs4_t*)
                               malloc(sizeof(ucs4_t) *
                                      (text_dictionary->max_length + 1));

  qsort(text_dictionary->lexicon,
        text_dictionary->entry_count,
        sizeof(text_dictionary->lexicon[0]),
        qsort_entry_cmp
        );

  return (Dict*)text_dictionary;
}