Exemplo n.º 1
0
// Pick a bonus up
void PLAYER::pick_bonus(BONUS *b) {
#ifndef EDITOR
	b->alive = false;
	b->effect();

	if(wisp.bonus == b)
		wisp.bonus = NULL;

	// Handle the bonuses
	bonus_counter[b->type]++;
	if(bonus_counter[b->type] >= powers_from_bonuses) {
		// Add a comment
		switch(next_bonus[b->type]) {
			default:
			case RED_POWER_TRAP:
				add_comment(COL_RED, "You have received a Trap."); break;
			case RED_POWER_WILDFIRE:
				add_comment(COL_RED, "You have received a Wild Fire."); break;
			case RED_POWER_NAPALM:
				add_comment(COL_RED, "You have received a Napalm Strike."); break;
			case GREEN_POWER_WISP:
				add_comment(COL_GREEN, "You have received a Will O' The Wisp."); break;
			case GREEN_POWER_POTATOMAN:
				add_comment(COL_GREEN, "You have received a Potato Man."); break;
			case GREEN_POWER_FLOWERPOWER:
				add_comment(COL_GREEN, "You have received a Flower Power."); break;
			case BLUE_POWER_TELEPORT:
				add_comment(COL_BLUE, "You have received a Teleport."); break;
			case BLUE_POWER_TURN:
				add_comment(COL_BLUE, "You have received a Turn."); break;
			case BLUE_POWER_LIGHTNING:
				add_comment(COL_BLUE, "You have received a Lightning Bolt."); break;
		}

		// Handle the special power
		icon_menu.count[next_bonus[b->type]]++;
		next_bonus[b->type]++;
		switch(b->type) {
			default:
			case BONUS_RED:
				if(next_bonus[BONUS_RED] > RED_POWER_NAPALM)
					next_bonus[BONUS_RED] = RED_POWER_TRAP;
				break;
			case BONUS_GREEN:
				if(next_bonus[BONUS_GREEN] > GREEN_POWER_FLOWERPOWER)
					next_bonus[BONUS_GREEN] = GREEN_POWER_WISP;
				break;
			case BONUS_BLUE:
				if(next_bonus[BONUS_BLUE] > BLUE_POWER_LIGHTNING)
					next_bonus[BONUS_BLUE] = BLUE_POWER_TELEPORT;
				break;
		}

		bonus_counter[b->type] = 0;
	}

#endif
}
Exemplo n.º 2
0
int main(int argc, char ** argv)
{
    std::string comment = "this is a really long comment, I hope that it exceeds the line";
    add_comment(argv[1],comment.c_str());


}
Exemplo n.º 3
0
void	add_command(int test, t_function **file, char *line)
{
	t_function	*tmp;

	if (test == 100)
		add_c_name(file, line);
	else if (test == 101)
		add_comment(file, line);
	else if (test == 102)
		cut_parsing_1(file, line);
	else if (test == 106)
		cut_parsing_2(file, line);
	else if (test == 103 || test == 105)
		;
	else if (test == 0)
		;
	else
	{
		if (g_begin != 2)
			exit_prgm_nbr(NULL, NULL);
		if (last_fun_h(file) == 1)
		{
			tmp = new_function(NULL);
			ft_lstaddend_funct(file, tmp);
		}
		cut_parsing_3(file, line, test);
	}
}
Exemplo n.º 4
0
// The player dies
void PLAYER::die() {
	if(jumping)
		return;

	if(dying)
		return;		// Hey, don't you die twice, man! ;)

	dying = true;
	die_anim = 1.0f;
	death_counter = 80;			// Just over one second

	// Play the sound
	static int last_sound = -1;
	int sound = last_sound;
	while(sound == last_sound)
		sound = RAND(SND_DIE1, SND_DIE6);
	play_sound(sound, false);
	last_sound = sound;

	// Reduce the special powers
	for(int f=0; f<NUM_ICONS; f++) {
		//icon_menu.count[f] = 0;
		if(icon_menu.count[f])
			icon_menu.count[f]--;
	}


	// Add a comment
	add_comment(COL_DEFAULT, "Respawning soon...");
}
Exemplo n.º 5
0
/* adds a host comment to the list in memory */
int add_host_comment(int entry_type, char *host_name, time_t entry_time, char *author, char *comment_data, unsigned long comment_id, int persistent, int expires, time_t expire_time, int source) {
	int result = OK;

	result = add_comment(HOST_COMMENT, entry_type, host_name, NULL, entry_time, author, comment_data, comment_id, persistent, expires, expire_time, source);

	return result;
	}
Exemplo n.º 6
0
/* adds a service comment to the list in memory */
int add_service_comment(int entry_type, char *host_name, char *svc_description, time_t entry_time, char *author, char *comment_data, unsigned long comment_id, int persistent, int expires, time_t expire_time, int source) {
	int result = OK;

	result = add_comment(SERVICE_COMMENT, entry_type, host_name, svc_description, entry_time, author, comment_data, comment_id, persistent, expires, expire_time, source);

	return result;
	}
Exemplo n.º 7
0
void local_addcomment(vorbis_comment *cms, const char *name, const string data)
{
	char    *cm;
	size_t   sz;
	int      vlen;

	sz = (str_size(data) * 4);

	cm = (char*) malloc(strlen(name) + sz + 2);

	strcpy(cm, name);
	strcat(cm, "=");
	
	WideCharToMultiByte(CP_UTF8, 0, data, -1, cm + (int)strlen(name) + 1, (int)sz, 0, 0);

	vlen = (int)strlen(cm) /* would this work for UTF-8 ? */;

	add_comment(cm, cms, vlen);
}
Exemplo n.º 8
0
int parse_codec_cfg(const char *cfgfile)
{
    codecs_t *codec = NULL; // current codec
    codecs_t **codecsp = NULL;// points to audio_codecs or to video_codecs
    char *endptr;   // strtoul()...
    int *nr_codecsp;
    int codec_type;     /* TYPE_VIDEO/TYPE_AUDIO */
    int tmp, i;

    // in case we call it a second time
    codecs_uninit_free();

    nr_vcodecs = 0;
    nr_acodecs = 0;

    if(cfgfile==NULL) {
#ifdef CODECS2HTML
        return 0;
#else
        video_codecs = builtin_video_codecs;
        audio_codecs = builtin_audio_codecs;
        nr_vcodecs = sizeof(builtin_video_codecs)/sizeof(codecs_t);
        nr_acodecs = sizeof(builtin_audio_codecs)/sizeof(codecs_t);
        return 1;
#endif
    }

    mp_msg(MSGT_CODECCFG, MSGL_V, "Reading optional codecs config file %s: ", cfgfile);

    if ((fp = fopen(cfgfile, "r")) == NULL) {
        mp_msg(MSGT_CODECCFG, MSGL_V, "%s\n", strerror(errno));
        return 0;
    }

    if ((line = malloc(MAX_LINE_LEN + 1)) == NULL) {
        mp_msg(MSGT_CODECCFG,MSGL_FATAL,MSGTR_CantGetMemoryForLine, strerror(errno));
        return 0;
    }
    read_nextline = 1;

    /*
     * this only catches release lines at the start of
     * codecs.conf, before audiocodecs and videocodecs.
     */
    while ((tmp = get_token(1, 1)) == RET_EOL)
        /* NOTHING */;
    if (tmp == RET_EOF)
        goto out;
    if (!strcmp(token[0], "release")) {
        if (get_token(1, 2) < 0)
            goto err_out_parse_error;
        tmp = atoi(token[0]);
        if (tmp < CODEC_CFG_MIN)
            goto err_out_release_num;
        codecs_conf_release = tmp;
        while ((tmp = get_token(1, 1)) == RET_EOL)
            /* NOTHING */;
        if (tmp == RET_EOF)
            goto out;
    } else
        goto err_out_release_num;

    /*
     * check if the next block starts with 'audiocodec' or
     * with 'videocodec'
     */
    if (!strcmp(token[0], "audiocodec") || !strcmp(token[0], "videocodec"))
        goto loop_enter;
    goto err_out_parse_error;

    while ((tmp = get_token(1, 1)) != RET_EOF) {
        if (tmp == RET_EOL)
            continue;
        if (!strcmp(token[0], "audiocodec") ||
            !strcmp(token[0], "videocodec")) {
            if (!validate_codec(codec, codec_type))
                goto err_out_not_valid;
        loop_enter:
            if (*token[0] == 'v') {
                codec_type = TYPE_VIDEO;
                nr_codecsp = &nr_vcodecs;
                codecsp = &video_codecs;
            } else if (*token[0] == 'a') {
                codec_type = TYPE_AUDIO;
                nr_codecsp = &nr_acodecs;
                codecsp = &audio_codecs;
#ifdef DEBUG
            } else {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,"picsba\n");
                goto err_out;
#endif
            }
            if (!(*codecsp = realloc(*codecsp,
                                     sizeof(codecs_t) * (*nr_codecsp + 2)))) {
                mp_msg(MSGT_CODECCFG,MSGL_FATAL,MSGTR_CantReallocCodecsp, strerror(errno));
                goto err_out;
            }
            codec=*codecsp + *nr_codecsp;
            ++*nr_codecsp;
            memset(codec,0,sizeof(codecs_t));
            memset(codec->fourcc, 0xff, sizeof(codec->fourcc));
            memset(codec->outfmt, 0xff, sizeof(codec->outfmt));
            memset(codec->infmt, 0xff, sizeof(codec->infmt));

            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            for (i = 0; i < *nr_codecsp - 1; i++) {
                if(( (*codecsp)[i].name!=NULL) &&
                   (!strcmp(token[0], (*codecsp)[i].name)) ) {
                    mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CodecNameNotUnique, token[0]);
                    goto err_out_print_linenum;
                }
            }
            if (!(codec->name = strdup(token[0]))) {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupName, strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "info")) {
            if (codec->info || get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->info = strdup(token[0]))) {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupInfo, strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "comment")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            add_comment(token[0], &codec->comment);
        } else if (!strcmp(token[0], "fourcc")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_fourcc(token[0], token[1],
                               codec->fourcc,
                               codec->fourccmap))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "format")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_format(token[0], token[1],
                               codec->fourcc,codec->fourccmap))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "driver")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->drv = strdup(token[0]))) {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupDriver, strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "dll")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->dll = strdup(token[0]))) {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupDLL, strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "guid")) {
            if (get_token(11, 11) < 0)
                goto err_out_parse_error;
            codec->guid.f1=strtoul(token[0],&endptr,0);
            if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                *endptr != '\0')
                goto err_out_parse_error;
            codec->guid.f2=strtoul(token[1],&endptr,0);
            if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                *endptr != '\0')
                goto err_out_parse_error;
            codec->guid.f3=strtoul(token[2],&endptr,0);
            if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                *endptr != '\0')
                goto err_out_parse_error;
            for (i = 0; i < 8; i++) {
                codec->guid.f4[i]=strtoul(token[i + 3],&endptr,0);
                if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                    *endptr != '\0')
                    goto err_out_parse_error;
            }
        } else if (!strcmp(token[0], "out")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_inout(token[0], token[1], codec->outfmt,
                              codec->outflags))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "in")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_inout(token[0], token[1], codec->infmt,
                              codec->inflags))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "flags")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!strcmp(token[0], "seekable"))
                codec->flags |= CODECS_FLAG_SEEKABLE;
            else
            if (!strcmp(token[0], "align16"))
                codec->flags |= CODECS_FLAG_ALIGN16;
            else
            if (!strcmp(token[0], "dummy"))
                codec->flags |= CODECS_FLAG_DUMMY;
            else
                goto err_out_parse_error;
        } else if (!strcmp(token[0], "status")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!strcasecmp(token[0], "working"))
                codec->status = CODECS_STATUS_WORKING;
            else if (!strcasecmp(token[0], "crashing"))
                codec->status = CODECS_STATUS_NOT_WORKING;
            else if (!strcasecmp(token[0], "untested"))
                codec->status = CODECS_STATUS_UNTESTED;
            else if (!strcasecmp(token[0], "buggy"))
                codec->status = CODECS_STATUS_PROBLEMS;
            else
                goto err_out_parse_error;
        } else if (!strcmp(token[0], "cpuflags")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->cpuflags = get_cpuflags(token[0])))
                goto err_out_parse_error;
        } else
            goto err_out_parse_error;
    }
    if (!validate_codec(codec, codec_type))
        goto err_out_not_valid;
    mp_msg(MSGT_CODECCFG,MSGL_INFO,MSGTR_AudioVideoCodecTotals, nr_acodecs, nr_vcodecs);
    if(video_codecs) video_codecs[nr_vcodecs].name = NULL;
    if(audio_codecs) audio_codecs[nr_acodecs].name = NULL;
out:
    free(line);
    line=NULL;
    fclose(fp);
    return 1;

err_out_parse_error:
    mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_ParseError);
err_out_print_linenum:
    PRINT_LINENUM;
err_out:
    codecs_uninit_free();

    free(line);
    line=NULL;
    line_num = 0;
    fclose(fp);
    return 0;
err_out_not_valid:
    mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CodecDefinitionIncorrect);
    goto err_out_print_linenum;
err_out_release_num:
    mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_OutdatedCodecsConf);
    goto err_out_print_linenum;
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
	vcedit_state *state;
	vorbis_comment *vc;
	param_t	*param;
	int i;

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);

	/* initialize the cmdline interface */
	param = new_param();
	parse_options(argc, argv, param);

	/* take care of opening the requested files */
	/* relevent file pointers are returned in the param struct */
	open_files(param);

	/* which mode are we in? */

	if (param->mode == MODE_LIST) {
		
		state = vcedit_new_state();

		if(vcedit_open(state, param->in) < 0)
		{
			fprintf(stderr, _("Failed to open file as vorbis: %s\n"), 
					vcedit_error(state));
            close_files(param);
            free_param(param);
            vcedit_clear(state);
			return 1;
		}

		/* extract and display the comments */
		vc = vcedit_comments(state);
		print_comments(param->com, vc, param->raw);

		/* done */
		vcedit_clear(state);

		close_files(param);
        free_param(param);
		return 0;		
	}

	if (param->mode == MODE_WRITE || param->mode == MODE_APPEND) {

		state = vcedit_new_state();

		if(vcedit_open(state, param->in) < 0)
		{
			fprintf(stderr, _("Failed to open file as vorbis: %s\n"), 
					vcedit_error(state));
            close_files(param);
            free_param(param);
            vcedit_clear(state);
			return 1;
		}

		/* grab and clear the exisiting comments */
		vc = vcedit_comments(state);
		if(param->mode != MODE_APPEND) 
		{
			vorbis_comment_clear(vc);
			vorbis_comment_init(vc);
		}

		for(i=0; i < param->commentcount; i++)
		{
			if(add_comment(param->comments[i], vc, param->raw) < 0)
				fprintf(stderr, _("Bad comment: \"%s\"\n"), param->comments[i]);
		}

		/* build the replacement structure */
		if(param->commentcount==0)
		{
			/* FIXME should use a resizeable buffer! */
			char *buf = (char *)malloc(sizeof(char)*1024);

			while (fgets(buf, 1024, param->com))
				if (add_comment(buf, vc, param->raw) < 0) {
					fprintf(stderr,
						_("bad comment: \"%s\"\n"),
						buf);
				}
			
			free(buf);
		}

		/* write out the modified stream */
		if(vcedit_write(state, param->out) < 0)
		{
			fprintf(stderr, _("Failed to write comments to output file: %s\n"), 
					vcedit_error(state));
            close_files(param);
            free_param(param);
            vcedit_clear(state);
			return 1;
		}

		/* done */
		vcedit_clear(state);
		
		close_files(param);
        free_param(param);
		return 0;
	}

	/* should never reach this point */
	fprintf(stderr, _("no action specified\n"));
    free_param(param);
	return 1;
}
Exemplo n.º 10
0
struct header *
pc_wav_to_feasd(char	*prefix,
		int	num_read,
		FILE	*file)
{
    pc_wav_hd	    *wav_hd;
    double	    start_time;
    double	    sf;
    struct header   *ohd;

    wav_hd = get_hd(prefix, num_read, file);

    if (wav_hd == NULL)
    {
	error_msg("pc_wav_to_feasd", "read header failed.");
	return NULL;
    }

    switch (wav_hd->FormatTag)
    {
    case WAVE_FORMAT_PCM:
	if (wav_hd->spec.pcm.BitsPerSample != 16)
	{
	    error_msg("pc_wav_to_feasd", "only 16-bit audio supported.");
	    return NULL;
	}
	break;
    default:
	error_msg("pc_wav_to_feasd", "only WAVE_FORMAT_PCM supported.");
	return NULL;
    }

    ohd = new_header(FT_FEA);

    if (ohd == NULL)
    {
	error_msg("pc_wav_to_feasd", "couldn't create FEA header.");
	return NULL;
    }

    strcpy(ohd->common.prog, "pc_wav_to_feasd");
    add_comment(ohd, "Converted from PC WAVE header\n");
    ohd->common.tag = NO;
    ohd->common.edr = NO;
    start_time = 0.0;
    sf = (double) wav_hd->SamplesPerSec;
    init_feasd_hd(ohd, SHORT, (int) wav_hd->Channels, &start_time, NO, sf);
    *add_genhd_l("FormatTag", (long *) NULL, 1, ohd) =
	(long) wav_hd->FormatTag;
    *add_genhd_l("Channels", (long *) NULL, 1, ohd) =
	(long) wav_hd->Channels;
    *add_genhd_l("SamplesPerSec", (long *) NULL, 1, ohd) =
	(long) wav_hd->SamplesPerSec;
    *add_genhd_l("AvgBytesPerSec", (long *) NULL, 1, ohd) =
	(long) wav_hd->AvgBytesPerSec;
    *add_genhd_l("BlockAlign", (long *) NULL, 1, ohd) =
	(long) wav_hd->BlockAlign;
    *add_genhd_l("BitsPerSample", (long *) NULL, 1, ohd) =
	(long) wav_hd->spec.pcm.BitsPerSample;

    *add_genhd_l("pc_wav_hd_ptr", (long *) NULL, 1, ohd) =
	(long) wav_hd;

    return ohd;
}
Exemplo n.º 11
0
int main(int ac, char **av)
{
	struct database *db;
	struct group *group = NULL;
	char *line = NULL;
	size_t linesz = 0;
	if (!av[1]) {
		printf("%s database\n", av[0]);
		exit(1);
	}
	printf("dbtest\n");
	db = open_db(av[1], 1);
	while (printf("> "),
		fflush(stdout),
		getline(&line, &linesz, stdin) > 0) {
		char *p = line + strlen(line) - 1;
		while (p >= line && isspace(*p))
			*p-- = 0;
		switch (line[0]) {
		case 's':
			C(sync_db(db));
			break;
		case 'q':
			C(close_db(db));
			exit(0);
		case 'g':
			group = find_group(db, line + 1);
			if (group)
				printf("found\n");
			break;
		case 'G':
			NEEDGROUP;
			C(delete_group(db, group));
			group = NULL;
			break;
		case 'a': {
			int existed = 0;
			group = add_group(db, line + 1, &existed);
			if (existed)
				printf("existed\n");
			break;
		}
		case 'v':
			NEEDGROUP;
			printf("%s\n", entry_val(group, line + 1));
			break;
		case 'c': {
			p = line + 1;
			char *entry = strsep(&p, ",");
			NEEDGROUP;
			change_entry(db, group, entry, strsep(&p, ""));
			break;
		}
		case 'L':
			NEEDGROUP;
			clone_group(db, group, line + 1);
			break;
		case 'f': {
			struct group *g;
			p = line + 1;
			char *entry = strsep(&p, ",");
			char *val = strsep(&p, "");
			g = NULL;
			int nr = 0;
			while ((g = find_entry(db, g, entry, val)) != NULL) {
				if (nr == 0)
					group = g;
				nr++;
				dump_group(group, stdout);
			}
			if (nr == 0)
				printf("not found\n");
			break;
		}
		case 'C':
			NEEDGROUP;
			add_comment(db, group, line + 1);
			break;
		case 'd':
			NEEDGROUP;
			dump_group(group, stdout);
			break;
		case 'D':
			dump_database(db, stdout);
			break;
		default:
			usage();
			break;
		}
	}
	return 0;
}
Exemplo n.º 12
0
main(int   argc,
     char  **argv)
{
    extern int	    optind;	/* for use of getopt() */
    extern char	    *optarg;	/* for use of getopt() */
    int		    ch;		/* command-line option letter */

    static char	    *ProgName = "esig2fea";	/* name of this program */
    static char	    *Version = SCCS_VERSION;	/* program SCCS version */
    static char	    *Date = SCCS_DATE;		/* program SCCS date */

    char	    **field_names = NULL;
    int		    num_fields = 0;
    int		    alloc_fields = 0;

    int		    rflag = NO;	/* -r option specified? */
    char	    *rrange;	/* arguments of -r option */
    long	    start_rec;	/* starting record number */
    long	    end_rec;	/* ending record number */
    long	    num_recs;	/* number of records to read
				   (0 means all up to end of file) */
    long	    num_read;	/* number of records actually read */

    char	    *iname;	/* input file name */
    FILE	    *ifile;	/* input stream */
    FieldList	    list;	/* input field list */
    int		    inord;	/* input: field order or type order? */
    FieldSpec	    **ifields;	/* input fields in field or type order */

    char	    *subtype = NULL;		/* FEA subtype name */
    int		    subtype_code = NONE;	/* numeric subtype code */
    FieldSpec	    *fld;	/* spec of various special fields */

    char	    *oname;	/* output file name */
    FILE	    *ofile;	/* output stream */
    struct header   *ohd;	/* output file header */
    struct fea_data *orec;	/* output record */
    int		    outord = TYPE_ORDER;

    char	    *version;	/* version from input preamble */
    int		    arch;	/* architecture from input preamble */
    long	    pre_size;	/* preamble size */
    long	    hdr_size;	/* header size (bytes) from preamble */
    long	    rec_size;	/* record size from preamble */

    double	    rec_freq;
    double	    start_time_offset;
    double	    *data;
    long	    len, i;


    struct header   *source;	/* embedded source-file header */


    while ((ch = getopt(argc, argv, "f:r:x:FT:")) != EOF)
	switch (ch)
	{
	case 'f':
	    if (num_fields >= alloc_fields)
	    {
		size_t	size;

		alloc_fields = num_fields + 1 + num_fields/2;
		size = (alloc_fields + 1) * sizeof(char *);
		field_names = (char **)
		    ((field_names == NULL)
		     ? malloc(size)
		     : realloc(field_names, size));
	    }
	    field_names[num_fields++] = optarg;
	    field_names[num_fields] = NULL;
	    break;
	case 'r':
	    rflag = YES;
	    rrange = optarg;
	    break;
	case 'x':
	    debug_level = atoi(optarg);
	    break;
	case 'F':
	    outord = FIELD_ORDER;
	    break;
	case 'T':
	    subtype = optarg;
	    break;
	default:
	    SYNTAX;
	    break;
	}

    if (argc - optind > 2)
    {
	fprintf(stderr,
		"%s: too many file names specified.\n", ProgName);
	SYNTAX;
    }
    if (argc - optind < 2)
    {
	fprintf(stderr,
		"%s: too few file names specified.\n", ProgName);
	SYNTAX;
    }


    DebugMsgLevel = debug_level;
    DebugMsgFunc = DebugPrint;

    iname = argv[optind++];
    list = OpenIn(iname, &version,
		  &arch, &pre_size, &hdr_size, &rec_size, &ifile);
    REQUIRE(list != NULL, "read header failed");
    if (ifile == stdin)
	iname = "<stdin>";

    oname = argv[optind++];

    start_rec = 0;
    end_rec = LONG_MAX;
    num_recs = 0;	/* 0 means continue to end of file */

    if (rflag)
    {
	lrange_switch(rrange, &start_rec, &end_rec, 0);
	if (end_rec != LONG_MAX)
	    num_recs = end_rec - start_rec + 1;
    }

    REQUIRE(start_rec >= 0, "can't start before beginning of file");
    REQUIRE(end_rec >= start_rec, "empty range of records specified");

    if (debug_level)
	fprintf(stderr,
		"start_rec: %ld.  end_rec: %ld.  num_recs: %ld.\n",
		start_rec, end_rec, num_recs);

    REQUIRE(GetFieldOrdering(list, &inord),
	    "cant get field ordering of input");

    switch (inord)
    {
    case TYPE_ORDER:
	if (debug_level)
	    fprintf(stderr, "making type-ordered field array.\n");
	ifields = TypeOrder(list);
	break;
    case FIELD_ORDER:
	if (debug_level)
	    fprintf(stderr, "making field-ordered field array.\n");
	ifields = FieldOrder(list);
	break;
    default:
	REQUIRE(0, "input order neither TYPE_ORDER nor FIELD_ORDER");
	break;
    }

    ohd = FieldList_to_fea(list, &orec, field_names, FALSE);

    REQUIRE(ohd != NULL,
	    "failure converting input field list to header & record struct");

    if (subtype != NULL)
    {
	subtype_code = lin_search(fea_file_type, subtype);

	if (subtype_code == -1)
	    fprintf(stderr, "%s: unknown FEA file subtype \"%s\" ignored.\n",
		    ProgName, subtype);
	else
	    ohd->hd.fea->fea_type = subtype_code;
    }

    if (outord == FIELD_ORDER)
	ohd->hd.fea->field_order = YES;

    fld = FindField(list, "recordFreq");

    if (fld != NULL && fld->occurrence == GLOBAL && fld->data != NULL)
    {
	(void) type_convert(1L, (char *) fld->data, ElibTypeToEsps(fld->type),
			    (char *) &rec_freq, FDOUBLE, (void (*)()) NULL);

	*add_genhd_d("record_freq", NULL, 1, ohd) = rec_freq;
    }
    else
	rec_freq = 1.0;

    fld = FindField(list, "startTime");

    if (fld != NULL
	&& fld->occurrence == GLOBAL && fld->data != NULL && rec_freq != 0)
    {
	start_time_offset = start_rec / rec_freq;

	len = FieldLength(fld);
	data = (double *) type_convert(len, (char *) fld->data,
				       ElibTypeToEsps(fld->type),
				       (char *) NULL, FDOUBLE,
				       (void (*)()) NULL);

	if (start_time_offset != 0)
	{
	    for (i = 0; i < len; i++)
		data[i] += start_time_offset;
	}

	(void) add_genhd_d("start_time", data, len, ohd);
    }

    (void) strcpy(ohd->common.prog, ProgName);
    (void) strcpy(ohd->common.vers, Version);
    (void) strcpy(ohd->common.progdate, Date);

    source = FieldList_to_fea(list, NULL, NULL, TRUE);
    add_source_file(ohd, savestring(iname), source);

    add_comment(ohd, get_cmd_line(argc, argv));

    oname = eopen(ProgName,
		  oname, "w", NONE, NONE, NULL, &ofile);
    write_header(ohd, ofile);

    num_read = SkipRecs(ifile, start_rec,
			RecordSize(list, arch), ifields, arch);

    if (num_read != start_rec)
    {
	fprintf(stderr,
		"%s: couldn't reach starting record; only %ld skipped.\n",
		ProgName, num_read);
	exit(0);
    }

    for ( ;
	 num_read <= end_rec && ReadRecord(ifields, arch, ifile);
	 num_read++)
    {
	put_fea_rec(orec, ohd, ofile);
    }

    if (num_read <= end_rec && num_recs != 0)
	fprintf(stderr, "esig2fea: only %ld records read.\n",
		num_read - start_rec);

    exit(0);
    /*NOTREACHED*/
}
Exemplo n.º 13
0
/******************************************************************************
Given a file pointer, get ready to read PLY data from the file.

Entry:
  fp - the given file pointer

Exit:
  nelems     - number of elements in object
  elem_names - list of element names
  returns a pointer to a PlyFile, used to refer to this file, or NULL if error
******************************************************************************/
PlyFile *ply_read(FILE *fp, int *nelems, char ***elem_names)
{
    int i,j;
    PlyFile *plyfile;
    int nwords;
    char **words;
    //int found_format = 0;
    char **elist;
    PlyElement *elem;
    char *orig_line;

    // check for NULL file pointer
    assert(fp != NULL);

    // create record for this object

    plyfile = (PlyFile *) myalloc (sizeof (PlyFile));
    plyfile->nelems = 0;
    plyfile->comments = NULL;
    plyfile->num_comments = 0;
    plyfile->obj_info = NULL;
    plyfile->num_obj_info = 0;
    plyfile->fp = fp;
    //plyfile->other_elems = NULL;

    // read and parse the file's header
    words = get_words(plyfile->fp, &nwords, &orig_line);
    assert(words && (strncmp(words[0], "ply", sizeof("ply ")) == 0));

    while (words) {
        // parse words

        if (strncmp(words[0], "format", sizeof("format")) == 0) {
            if (nwords != 3) {
                return (NULL);
            }
            if (strncmp(words[1], "ascii", sizeof("ascii")) == 0) {
                plyfile->file_type = PLY_ASCII;
            } else {
                return (NULL);
            }
            plyfile->version = atof (words[2]);
            //found_format = 1;
        } else if (strncmp(words[0], "element", sizeof("element")) == 0) {
            add_element (plyfile, words, nwords);
        } else if (strncmp(words[0], "property", sizeof("property")) == 0) {
            add_property (plyfile, words, nwords);
        } else if (strncmp(words[0], "comment", sizeof("comment")) == 0) {
            add_comment (plyfile, orig_line);
        } else if (strncmp(words[0], "obj_info", sizeof("obj_info")) == 0) {
            add_obj_info (plyfile, orig_line);
        } else if (strncmp(words[0], "end_header", sizeof("end_header")) == 0) {
            break;
        }

        // free up words space
        free (words);

        words = get_words (plyfile->fp, &nwords, &orig_line);
    }

    // create tags for each property of each element, to be used
    // later to say whether or not to store each property for the user

    for (i = 0; i < plyfile->nelems; i++) {
        elem = plyfile->elems[i];
        elem->store_prop = (char *) myalloc (sizeof (char) * elem->nprops);
        for (j = 0; j < elem->nprops; j++) {
            elem->store_prop[j] = DONT_STORE_PROP;
        }
        elem->other_offset = NO_OTHER_PROPS; // no "other" props by default
    }

    // set return values about the elements

    elist = (char **) myalloc (sizeof (char *) * plyfile->nelems);
    for (i = 0; i < plyfile->nelems; i++) {
        elist[i] = strdup (plyfile->elems[i]->name);
    }

    *elem_names = elist;
    *nelems = plyfile->nelems;

    // return a pointer to the file's information

    return (plyfile);
}
Exemplo n.º 14
0
int main() {
    while (FCGI_Accept() >= 0) {
        char type[80] = "html";
        char entry[10] = "0";
        char comments[6] = "false";
        char *req_method;
        char gets[1000];

        req_method = getenv("REQUEST_METHOD");

        if (strcmp(req_method, "PUT") == 0) {
            char id[10];

            strcpy(gets, getenv("QUERY_STRING"));

            if (getenv("QUERY_STRING") == NULL) {
                printf("Status: 400 Bad Request\r\n\r\n");
            } else {
                get_param(gets, "id", id, 10);

                int entry_id = strtol(id, NULL, 10);

                // grab the post data
                int len = strtol(getenv("CONTENT_LENGTH"), NULL, 10);
                char *content = (char *)malloc(sizeof(char) * len);
                fread(content, sizeof(char), len, stdin);

                LIBXML_TEST_VERSION

                char *t;
                char *c;
                const int TS = 256;
                int code;

                t = (char *)malloc(sizeof(char) * TS);
                c = (char *)malloc(sizeof(char) * len);

                if (parse_post(content, t, TS, c, len) == 0) {

                    code = update_entry(entry_id, t, c);
                    if (code == 0) {
                        printf("Status: 200 OK\r\n");
                        printf("Content-type: text/xml; charset=UTF-8\r\n"
                            "\r\n");

                        generate_entries(1, entry_id, "atom_single.ct");

                    } else {
                        printf("Status: 500 Internal Server Error\r\n\r\nDB Error Code: %d - %d \n\n", code, entry_id);
                    }

                } else {
                    printf("Status: 400 Bad Request\r\n\r\n");
                }

                free(t);
                free(c);
                free(content);
            }
        } else 
        if (strcmp(req_method, "DELETE") == 0) {
            char id[10];

            strcpy(gets, getenv("QUERY_STRING"));

            if (getenv("QUERY_STRING") == NULL) {
                printf("Status: 400 Bad Request\r\n\r\n");
            } else {
                get_param(gets, "id", id, 10);

                if (remove_entry(strtol(id, NULL, 10)) == 0) {
                    printf("Status: 204 No Content\r\n\r\n");
                } else {
                    printf("Status: 400 Bad Request\r\n\r\n");
                }
            }

        } else
        if (strcmp(req_method, "POST") == 0) {
            if (getenv("QUERY_STRING") == NULL) {
                printf("Status: 400 Bad Request\r\n\r\n");
            }

            // parse the post function
            char function[20];
            strcpy(gets, getenv("QUERY_STRING"));
            get_param(gets, "function", function, 20);
            get_param(gets, "format", type, 20);

            // grab the post data
            int len = strtol(getenv("CONTENT_LENGTH"), NULL, 10);
            char *content = (char *)malloc(sizeof(char) * len);
            fread(content, sizeof(char), len, stdin);

            //atom post!
            if (strcmp(type, "atom") == 0) {
                LIBXML_TEST_VERSION

                char *t;
                char *c;
                const int TS = 256;
                int id;

                t = (char *)malloc(sizeof(char) * TS);
                c = (char *)malloc(sizeof(char) * len);

                if (parse_post(content, t, TS, c, len) == 0) {
                    id = add_entry(t, c);

                    if (id > 0) {
                        printf("Status: 201 Created\r\n\r\n");
                        printf("Content-type: text/xml; charset=UTF-8\r\n"
                            "\r\n");
                        generate_entries(1, id, "atom_single.ct");
                    } else {
                        printf("Status: 500 Internal Server Error\r\n\r\nDB Error Code: %d", id);
                    }
                } else {
                    printf("Status: 400 Bad Request\r\n\r\n");
                }

                free(t);
                free(c);
                free(content);
            } else 
            if (strcmp(function, "comment") == 0) {
                char entry_id[10];
                char comment[len];
                int ac;

                get_param(content, "entry_id", entry_id, 10);
                get_param(content, "content", comment, len);

                ac = add_comment(strtol(entry_id, NULL, 10), comment);

                fprintf(stderr, "Does it get here?");

                if (ac > 0) {
                    printf("Content-type: application/json; charset=UTF-8\r\n");
                    printf("\r\n");
                    printf("{'success': true}");
                } else {
                    printf("Status: 500 Internal Server Error\r\n\r\n");
                    printf("{'success': false, 'error_code': %d}", ac);
                }
            } else {
                printf("Status: 400 Bad Request\r\n\r\n");
            }

            free(content);

            /*
            int len = strtol(getenv("CONTENT_LENGTH"), NULL, 10);
            char *content = (char *)malloc(sizeof(char) * len);
            fread(content, sizeof(char), len, stdin);


            */
        } else // end if( type == "POST")

        if (strcmp(req_method, "GET") == 0) {

            if (getenv("QUERY_STRING") != NULL) {
                char gets[1000];

                strcpy(gets, getenv("QUERY_STRING"));
                get_param(gets, "entry", entry, 10);

                strcpy(gets, getenv("QUERY_STRING"));
                get_param(gets, "format", type, 20);

                strcpy(gets, getenv("QUERY_STRING"));
                get_param(gets, "get_comments", comments, 6);
            }


            if (strcmp(type, "html") == 0) {
                // application/xhtml+xml doesn't work with IE -_-;;
                //printf("Content-type: application/xhtml+xml; charset=UTF-8\r\n"
                // have to serve xhtml as html... IE sucks
                printf("Content-type: text/html; charset=UTF-8\r\n"
                        "\r\n");
            } else
            if (strcmp(type, "json") == 0) {
                printf("Content-type: application/json; charset=UTF-8\r\n"
                        "\r\n");
            } else
            if (strcmp(type, "rss") == 0) {
                printf("Content-type: application/rss+xml; charset=UTF-8\r\n"
                        "\r\n");
            } else 
            if (strcmp(type, "atom") == 0) {
                printf("Content-type: application/atom+xml; charset=UTF-8\r\n"
                        "\r\n");
            } else {
                printf("Status: 400 Bad Request\r\n\r\n");
                break;
            }

            if (strcmp(comments, "true") == 0) {
                strcat(type, "_comments.ct");
                generate_comments(strtol(entry, NULL, 10), type);
            } else {
                /* defaults to creating the main blog */
                strcat(type, ".ct");
                if(strcmp(entry,"0") == 0) {
                    generate_entries(10, 1, type);
                } else { 
                    generate_entries(1, strtol(entry, NULL, 10), type);
                }
            }

        } // end if( type == "GET")
    }
    return 0;
}
Exemplo n.º 15
0
int parse_codec_cfg(const char *cfgfile)
{
    codecs_t *codec = NULL; // current codec
    codecs_t **codecsp = NULL;// points to audio_codecs or to video_codecs
    char *endptr;   // strtoul()...
    int *nr_codecsp;
    int codec_type;     /* TYPE_VIDEO/TYPE_AUDIO */
    int tmp, i;
    int codec_cfg_min;

    for (struct bstr s = builtin_codecs_conf; ; bstr_getline(s, &s)) {
        if (!s.len)
            abort();
        if (bstr_eatstart0(&s, "release ")) {
            codec_cfg_min = atoi(s.start);
            break;
        }
    }

    // in case we call it a second time
    codecs_uninit_free();

    nr_vcodecs = 0;
    nr_acodecs = 0;

    if (cfgfile) {
        // Avoid printing errors from open_stream when trying optional files
        if (!mp_path_exists(cfgfile)) {
            mp_tmsg(MSGT_CODECCFG, MSGL_V,
                    "No optional codecs config file: %s\n", cfgfile);
            return 0;
        }
        mp_msg(MSGT_CODECCFG, MSGL_V, "Reading codec config file: %s\n",
                cfgfile);
        struct stream *s = open_stream(cfgfile, NULL, NULL);
        if (!s)
            return 0;
        filetext = stream_read_complete(s, NULL, 10000000, 1);
        free_stream(s);
        if (!filetext.start)
            return 0;
    } else
        // Parsing modifies the data
        filetext = bstrdup(NULL, builtin_codecs_conf);
    void *tmpmem = filetext.start;

    read_nextline = 1;

    /*
     * this only catches release lines at the start of
     * codecs.conf, before audiocodecs and videocodecs.
     */
    while ((tmp = get_token(1, 1)) == RET_EOL)
        /* NOTHING */;
    if (tmp == RET_EOF)
        goto out;
    if (!strcmp(token[0], "release")) {
        if (get_token(1, 2) < 0)
            goto err_out_parse_error;
        tmp = atoi(token[0]);
        if (tmp < codec_cfg_min)
            goto err_out_release_num;
        codecs_conf_release = tmp;
        while ((tmp = get_token(1, 1)) == RET_EOL)
            /* NOTHING */;
        if (tmp == RET_EOF)
            goto out;
    } else
        goto err_out_release_num;

    /*
     * check if the next block starts with 'audiocodec' or
     * with 'videocodec'
     */
    if (!strcmp(token[0], "audiocodec") || !strcmp(token[0], "videocodec"))
        goto loop_enter;
    goto err_out_parse_error;

    while ((tmp = get_token(1, 1)) != RET_EOF) {
        if (tmp == RET_EOL)
            continue;
        if (!strcmp(token[0], "audiocodec") ||
            !strcmp(token[0], "videocodec")) {
            if (!validate_codec(codec, codec_type))
                goto err_out_not_valid;
        loop_enter:
            if (*token[0] == 'v') {
                codec_type = TYPE_VIDEO;
                nr_codecsp = &nr_vcodecs;
                codecsp = &video_codecs;
            } else {
                assert(*token[0] == 'a');
                codec_type = TYPE_AUDIO;
                nr_codecsp = &nr_acodecs;
                codecsp = &audio_codecs;
            }
            if (!(*codecsp = realloc(*codecsp,
                                     sizeof(codecs_t) * (*nr_codecsp + 2)))) {
                mp_tmsg(MSGT_CODECCFG,MSGL_FATAL,"Can't realloc '*codecsp': %s\n", strerror(errno));
                goto err_out;
            }
            codec=*codecsp + *nr_codecsp;
            ++*nr_codecsp;
            memset(codec,0,sizeof(codecs_t));
            memset(codec->fourcc, 0xff, sizeof(codec->fourcc));
            memset(codec->outfmt, 0xff, sizeof(codec->outfmt));
            memset(codec->infmt, 0xff, sizeof(codec->infmt));

            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            for (i = 0; i < *nr_codecsp - 1; i++) {
                if(( (*codecsp)[i].name!=NULL) &&
                   (!strcmp(token[0], (*codecsp)[i].name)) ) {
                    mp_tmsg(MSGT_CODECCFG,MSGL_ERR,"Codec name '%s' isn't unique.", token[0]);
                    goto err_out_print_linenum;
                }
            }
            if (!(codec->name = strdup(token[0]))) {
                mp_tmsg(MSGT_CODECCFG,MSGL_ERR,"Can't strdup -> 'name': %s\n", strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "info")) {
            if (codec->info || get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->info = strdup(token[0]))) {
                mp_tmsg(MSGT_CODECCFG,MSGL_ERR,"Can't strdup -> 'info': %s\n", strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "comment")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            add_comment(token[0], &codec->comment);
        } else if (!strcmp(token[0], "fourcc")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_fourcc(token[0], token[1],
                               codec->fourcc,
                               codec->fourccmap))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "format")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_format(token[0], token[1],
                               codec->fourcc,codec->fourccmap))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "driver")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->drv = strdup(token[0]))) {
                mp_tmsg(MSGT_CODECCFG,MSGL_ERR,"Can't strdup -> 'driver': %s\n", strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "dll")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->dll = strdup(token[0]))) {
                mp_tmsg(MSGT_CODECCFG,MSGL_ERR,"Can't strdup -> 'dll': %s", strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "guid")) {
            if (get_token(11, 11) < 0)
                goto err_out_parse_error;
            codec->guid.f1=strtoul(token[0],&endptr,0);
            if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                *endptr != '\0')
                goto err_out_parse_error;
            codec->guid.f2=strtoul(token[1],&endptr,0);
            if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                *endptr != '\0')
                goto err_out_parse_error;
            codec->guid.f3=strtoul(token[2],&endptr,0);
            if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                *endptr != '\0')
                goto err_out_parse_error;
            for (i = 0; i < 8; i++) {
                codec->guid.f4[i]=strtoul(token[i + 3],&endptr,0);
                if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                    *endptr != '\0')
                    goto err_out_parse_error;
            }
        } else if (!strcmp(token[0], "out")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_inout(token[0], token[1], codec->outfmt,
                              codec->outflags))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "in")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_inout(token[0], token[1], codec->infmt,
                              codec->inflags))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "flags")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!strcmp(token[0], "seekable"))
                codec->flags |= CODECS_FLAG_SEEKABLE;
            else if (!strcmp(token[0], "align16"))
                codec->flags |= CODECS_FLAG_ALIGN16;
            else
                goto err_out_parse_error;
        } else if (!strcmp(token[0], "status")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!strcasecmp(token[0], "working"))
                codec->status = CODECS_STATUS_WORKING;
            else if (!strcasecmp(token[0], "crashing"))
                codec->status = CODECS_STATUS_NOT_WORKING;
            else if (!strcasecmp(token[0], "untested"))
                codec->status = CODECS_STATUS_UNTESTED;
            else if (!strcasecmp(token[0], "buggy"))
                codec->status = CODECS_STATUS_PROBLEMS;
            else
                goto err_out_parse_error;
        } else if (!strcmp(token[0], "anyinput")) {
            codec->anyinput = true;
        } else
            goto err_out_parse_error;
    }
    if (!validate_codec(codec, codec_type))
        goto err_out_not_valid;
    mp_tmsg(MSGT_CODECCFG, MSGL_V, "%d audio & %d video codecs\n", nr_acodecs,
            nr_vcodecs);
    if(video_codecs) video_codecs[nr_vcodecs].name = NULL;
    if(audio_codecs) audio_codecs[nr_acodecs].name = NULL;
out:
    talloc_free(tmpmem);
    line=NULL;
    return 1;

err_out_parse_error:
    mp_tmsg(MSGT_CODECCFG,MSGL_ERR,"parse error");
err_out_print_linenum:
    PRINT_LINENUM;
err_out:
    codecs_uninit_free();

    talloc_free(tmpmem);
    line=NULL;
    line_num = 0;
    return 0;
err_out_not_valid:
    mp_tmsg(MSGT_CODECCFG,MSGL_ERR,"Codec is not defined correctly.");
    goto err_out_print_linenum;
err_out_release_num:
    mp_tmsg(MSGT_CODECCFG,MSGL_ERR,"This codecs.conf is too old and incompatible with this MPlayer release!");
    goto err_out_print_linenum;
}
Exemplo n.º 16
0
int main (int argc, char ** argv)
{
    HTSQL *	sql = NULL;
    char *	sqlserver = DEFAULT_SQL_SERVER;
    char *	sqldb = DEFAULT_SQL_DB;
    char *	sqluser = DEFAULT_SQL_USER;
    char *	sqlpw = DEFAULT_SQL_PW;
    char *	cvsuser = DEFAULT_CVS_USER;
    time_t	cvsdate = -1;
    FILE * fin = stdin;
    char *	input_buffer[BUFSIZE];
    HTChunk *	loginfo = HTChunk_new(BUFSIZE);
    int		arg = 0;
    BOOL	create_db = YES;

    /* Initiate libwww */
    HTLibInit(APP_NAME, APP_VERSION);

    /* Scan command line for parameters */
    for (arg=1; arg<argc; arg++) {
        if (*argv[arg] == '-') {

            if (!strcmp(argv[arg], "-h") || !strcmp(argv[arg], "-?")) {
                VersionInfo();
                Cleanup(0, sql, loginfo);

            } else if (!strcmp(argv[arg], "-v")) {
                HTSetTraceMessageMask("q");

            } else if (!strcmp(argv[arg], "-nocreate")) {
                create_db = NO;

            } else if (!strncmp(argv[arg], "-sqldb", 5)) {
                sqldb = (arg+1 < argc && *argv[arg+1] != '-') ?
                        argv[++arg] : DEFAULT_SQL_DB;

            } else if (!strncmp(argv[arg], "-sqlpassword", 5)) {
                sqlpw = (arg+1 < argc && *argv[arg+1] != '-') ?
                        argv[++arg] : DEFAULT_SQL_PW;

            } else if (!strncmp(argv[arg], "-sqlserver", 5)) {
                sqlserver = (arg+1 < argc && *argv[arg+1] != '-') ?
                            argv[++arg] : DEFAULT_SQL_SERVER;

            } else if (!strncmp(argv[arg], "-sqluser", 5)) {
                sqluser = (arg+1 < argc && *argv[arg+1] != '-') ?
                          argv[++arg] : DEFAULT_SQL_USER;

            } else if (!strncmp(argv[arg], "-cvsuser", 5)) {
                cvsuser = (arg+1 < argc && *argv[arg+1] != '-') ?
                          argv[++arg] : DEFAULT_CVS_USER;

            } else if (!strncmp(argv[arg], "-cvsdate", 5)) {
                cvsdate = (arg+1 < argc && *argv[arg+1] != '-') ?
                          HTParseTime(argv[++arg], NULL, NO) : -1;

            } else {
                fprintf(stderr, "Bad Argument (%s)\n", argv[arg]);
            }
        } else {
            fprintf(stderr, "Bad Argument (%s)\n", argv[arg]);
        }
    }

    /* Get an SQL object */
    if ((sql = HTSQL_new(sqlserver, sqluser, sqlpw, 0)) == NULL)
        Cleanup(-1, sql, loginfo);

    /* Connect to the SQL server */
    if (HTSQL_connect(sql) != YES) Cleanup(-1, sql, loginfo);

    /* Select our database */
    if (HTSQL_selectDB(sql, sqldb) != YES) Cleanup(-1, sql, loginfo);

    /* Create our tables */
    if (create_db) createTables(sql, 0);

    /* Read the arguments from stdin */
    for (;;) {
        int status = fread(input_buffer, 1, BUFSIZE, fin);
        if (status < 0) Cleanup(-1, sql, loginfo);
        if (status == 0) break;
        HTChunk_putb(loginfo, (const char *) input_buffer, status);
    }

    /* Parse the input chunk */
    {
        char * ptr = HTChunk_data(loginfo);
        char * noop1 = HTNextField(&ptr);
        char * noop2 = HTNextField(&ptr);
        char * root = HTNextField(&ptr);
        char * operation = NULL;
        char * files = NULL;
        char * comment = NULL;
        int comment_id = -1;
        int user_id = -1;
        char * p, * q;
#ifdef HT_REENTRANT
        char *lasts;					     /* For strtok_r */
#endif

        /* Find shared log message and get id */
        if ((q = HTStrCaseStr(ptr, "\nLog Message:")) != NULL) {
            comment = q+14;
            *q = '\0';
        }
        if ((comment_id = add_comment(sql, comment)) < 0)
            Cleanup(-1, sql, loginfo);

        /* Add/find user and get id */
        if ((user_id = add_user(sql, cvsuser)) < 0)
            Cleanup(-1, sql, loginfo);

        /* For each operation, find the files involved */
        while ((q = HTStrCaseStr(ptr, " Files:")) != NULL) {

            /* Find the operation */
            files = q+9;
            for (p=q; p>HTChunk_data(loginfo) && *p && *p!='\n'; p--);
            p++;
            operation = HTNextField(&p);

            /* Find the next line */
            if ((q = strchr(files, '\n')) != NULL) {
                *q++ = '\0';
                ptr = q;
            }

            /* Create the query */
            if (operation && files && comment) {
                char * file;
                int location_id = -1;

#ifdef HT_REENTRANT
                if ((file = strtok_r(files, DELIMITERS, &lasts)) != NULL) {
#else
                if ((file = strtok(files, DELIMITERS)) != NULL) {
#endif /* HT_REENTRANT */
                    do {
                        char * path = NULL;
                        StrAllocMCopy(&path, root, "/", file, NULL);

                        /* Add/find location and get id */
                        if ((location_id = add_location(sql, path)) < 0) {
                            Cleanup(-1, sql, loginfo);
                            break;
                        }

#if 0
                        fprintf(stderr, "location: `%s\', user: `%s\', operation: `%s\', comment: `%s\'\n",
                                path, cvsuser, operation, comment);
#endif

                        /* Add log entry */
                        {
                            char buf[16384];
                            char * query = HTSQL_printf(buf, 16384, "insert into %s values (%u,%u,%T,%S,%u)",
                                                        DEFAULT_SQL_LOG_TABLE,
                                                        location_id,
                                                        user_id,
                                                        cvsdate,
                                                        operation,
                                                        comment_id);
                            if (HTSQL_query(sql, query) != YES) {
                                Cleanup(-1, sql, loginfo);
                                break;
                            }
                        }

                        HT_FREE(path);
#ifdef HT_REENTRANT
                    } while ((file = (char *) strtok_r(NULL, DELIMITERS, &lasts)) != NULL);
#else
                    }
                    while ((file = strtok(NULL, DELIMITERS)) != NULL);
#endif /* HT_REENTRANT */
                }
            }
        }
    }

    return 0;
}
Exemplo n.º 17
0
/* read all program, host, and service status information */
int xsddefault_read_status_data(char *config_file, int options) {
#ifdef NO_MMAP
	char input[MAX_PLUGIN_OUTPUT_LENGTH] = "";
	FILE *fp = NULL;
#else
	char *input = NULL;
	mmapfile *thefile = NULL;
#endif
	int data_type = XSDDEFAULT_NO_DATA;
	hoststatus *temp_hoststatus = NULL;
	servicestatus *temp_servicestatus = NULL;
	char *var = NULL;
	char *val = NULL;
	char *ptr = NULL;
	int result = 0;
	/* comment and downtime vars */
	unsigned long comment_id = 0;
	int persistent = FALSE;
	int expires = FALSE;
	time_t expire_time = 0L;
	int entry_type = USER_COMMENT;
	int source = COMMENTSOURCE_INTERNAL;
	time_t entry_time = 0L;
	char *host_name = NULL;
	char *service_description = NULL;
	char *author = NULL;
	char *comment_data = NULL;
	unsigned long downtime_id = 0;
	time_t start_time = 0L;
	time_t flex_downtime_start = 0L;
	time_t end_time = 0L;
	int fixed = FALSE;
	unsigned long triggered_by = 0;
	unsigned long duration = 0L;
	int x = 0;
	int is_in_effect = FALSE;


	/* initialize some vars */
	for(x = 0; x < MAX_CHECK_STATS_TYPES; x++) {
		program_stats[x][0] = 0;
		program_stats[x][1] = 0;
		program_stats[x][2] = 0;
		}

	/* grab configuration data */
	result = xsddefault_grab_config_info(config_file);
	if(result == ERROR)
		return ERROR;

	/* open the status file for reading */
#ifdef NO_MMAP
	if((fp = fopen(xsddefault_status_log, "r")) == NULL)
		return ERROR;
#else
	if((thefile = mmap_fopen(xsddefault_status_log)) == NULL)
		return ERROR;
#endif

	/* Big speedup when reading status.dat in bulk */
	defer_downtime_sorting = 1;
	defer_comment_sorting = 1;

	/* read all lines in the status file */
	while(1) {

#ifdef NO_MMAP
		strcpy(input, "");
		if(fgets(input, sizeof(input), fp) == NULL)
			break;
#else
		/* free memory */
		my_free(input);

		/* read the next line */
		if((input = mmap_fgets(thefile)) == NULL)
			break;
#endif

		strip(input);

		/* skip blank lines and comments */
		if(input[0] == '#' || input[0] == '\x0')
			continue;

		else if(!strcmp(input, "info {"))
			data_type = XSDDEFAULT_INFO_DATA;
		else if(!strcmp(input, "programstatus {"))
			data_type = XSDDEFAULT_PROGRAMSTATUS_DATA;
		else if(!strcmp(input, "hoststatus {")) {
			data_type = XSDDEFAULT_HOSTSTATUS_DATA;
			temp_hoststatus = (hoststatus *)calloc(1, sizeof(hoststatus));
			}
		else if(!strcmp(input, "servicestatus {")) {
			data_type = XSDDEFAULT_SERVICESTATUS_DATA;
			temp_servicestatus = (servicestatus *)calloc(1, sizeof(servicestatus));
			}
		else if(!strcmp(input, "contactstatus {")) {
			data_type = XSDDEFAULT_CONTACTSTATUS_DATA;
			/* unimplemented */
			}
		else if(!strcmp(input, "hostcomment {"))
			data_type = XSDDEFAULT_HOSTCOMMENT_DATA;
		else if(!strcmp(input, "servicecomment {"))
			data_type = XSDDEFAULT_SERVICECOMMENT_DATA;
		else if(!strcmp(input, "hostdowntime {"))
			data_type = XSDDEFAULT_HOSTDOWNTIME_DATA;
		else if(!strcmp(input, "servicedowntime {"))
			data_type = XSDDEFAULT_SERVICEDOWNTIME_DATA;

		else if(!strcmp(input, "}")) {

			switch(data_type) {

				case XSDDEFAULT_INFO_DATA:
					break;

				case XSDDEFAULT_PROGRAMSTATUS_DATA:
					break;

				case XSDDEFAULT_HOSTSTATUS_DATA:
					add_host_status(temp_hoststatus);
					temp_hoststatus = NULL;
					break;

				case XSDDEFAULT_SERVICESTATUS_DATA:
					add_service_status(temp_servicestatus);
					temp_servicestatus = NULL;
					break;

				case XSDDEFAULT_CONTACTSTATUS_DATA:
					/* unimplemented */
					break;

				case XSDDEFAULT_HOSTCOMMENT_DATA:
				case XSDDEFAULT_SERVICECOMMENT_DATA:

					/* add the comment */
					add_comment((data_type == XSDDEFAULT_HOSTCOMMENT_DATA) ? HOST_COMMENT : SERVICE_COMMENT, entry_type, host_name, service_description, entry_time, author, comment_data, comment_id, persistent, expires, expire_time, source);

					/* free temp memory */
					my_free(host_name);
					my_free(service_description);
					my_free(author);
					my_free(comment_data);

					/* reset defaults */
					entry_type = USER_COMMENT;
					comment_id = 0;
					source = COMMENTSOURCE_INTERNAL;
					persistent = FALSE;
					entry_time = 0L;
					expires = FALSE;
					expire_time = 0L;

					break;

				case XSDDEFAULT_HOSTDOWNTIME_DATA:
				case XSDDEFAULT_SERVICEDOWNTIME_DATA:

					/* add the downtime */
					if(data_type == XSDDEFAULT_HOSTDOWNTIME_DATA)
						add_host_downtime(host_name, entry_time, author, comment_data, start_time, flex_downtime_start, end_time, fixed, triggered_by, duration, downtime_id, is_in_effect);
					else
						add_service_downtime(host_name, service_description, entry_time, author, comment_data, start_time, flex_downtime_start, end_time, fixed, triggered_by, duration, downtime_id, is_in_effect);

					/* free temp memory */
					my_free(host_name);
					my_free(service_description);
					my_free(author);
					my_free(comment_data);

					/* reset defaults */
					downtime_id = 0;
					entry_time = 0L;
					start_time = 0L;
					end_time = 0L;
					fixed = FALSE;
					triggered_by = 0;
					duration = 0L;
					is_in_effect = FALSE;

					break;

				default:
					break;
				}

			data_type = XSDDEFAULT_NO_DATA;
			}

		else if(data_type != XSDDEFAULT_NO_DATA) {

			var = strtok(input, "=");
			val = strtok(NULL, "\n");
			if(val == NULL)
				continue;

			switch(data_type) {

				case XSDDEFAULT_INFO_DATA:
					break;

				case XSDDEFAULT_PROGRAMSTATUS_DATA:
					/* NOTE: some vars are not read, as they are not used by the CGIs (modified attributes, event handler commands, etc.) */
					if(!strcmp(var, "nagios_pid"))
						nagios_pid = atoi(val);
					else if(!strcmp(var, "daemon_mode"))
						daemon_mode = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "program_start"))
						program_start = strtoul(val, NULL, 10);
					else if(!strcmp(var, "last_log_rotation"))
						last_log_rotation = strtoul(val, NULL, 10);
					else if(!strcmp(var, "enable_notifications"))
						enable_notifications = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "active_service_checks_enabled"))
						execute_service_checks = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "passive_service_checks_enabled"))
						accept_passive_service_checks = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "active_host_checks_enabled"))
						execute_host_checks = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "passive_host_checks_enabled"))
						accept_passive_host_checks = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "enable_event_handlers"))
						enable_event_handlers = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "obsess_over_services"))
						obsess_over_services = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "obsess_over_hosts"))
						obsess_over_hosts = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "check_service_freshness"))
						check_service_freshness = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "check_host_freshness"))
						check_host_freshness = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "enable_flap_detection"))
						enable_flap_detection = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "process_performance_data"))
						process_performance_data = (atoi(val) > 0) ? TRUE : FALSE;

					else if(strstr(var, "_stats")) {

						x = -1;
						if(!strcmp(var, "active_scheduled_host_check_stats"))
							x = ACTIVE_SCHEDULED_HOST_CHECK_STATS;
						if(!strcmp(var, "active_ondemand_host_check_stats"))
							x = ACTIVE_ONDEMAND_HOST_CHECK_STATS;
						if(!strcmp(var, "passive_host_check_stats"))
							x = PASSIVE_HOST_CHECK_STATS;
						if(!strcmp(var, "active_scheduled_service_check_stats"))
							x = ACTIVE_SCHEDULED_SERVICE_CHECK_STATS;
						if(!strcmp(var, "active_ondemand_service_check_stats"))
							x = ACTIVE_ONDEMAND_SERVICE_CHECK_STATS;
						if(!strcmp(var, "passive_service_check_stats"))
							x = PASSIVE_SERVICE_CHECK_STATS;
						if(!strcmp(var, "cached_host_check_stats"))
							x = ACTIVE_CACHED_HOST_CHECK_STATS;
						if(!strcmp(var, "cached_service_check_stats"))
							x = ACTIVE_CACHED_SERVICE_CHECK_STATS;
						if(!strcmp(var, "external_command_stats"))
							x = EXTERNAL_COMMAND_STATS;
						if(!strcmp(var, "parallel_host_check_stats"))
							x = PARALLEL_HOST_CHECK_STATS;
						if(!strcmp(var, "serial_host_check_stats"))
							x = SERIAL_HOST_CHECK_STATS;

						if(x >= 0) {
							if((ptr = strtok(val, ","))) {
								program_stats[x][0] = atoi(ptr);
								if((ptr = strtok(NULL, ","))) {
									program_stats[x][1] = atoi(ptr);
									if((ptr = strtok(NULL, "\n")))
										program_stats[x][2] = atoi(ptr);
									}
								}
							}
						}
					break;

				case XSDDEFAULT_HOSTSTATUS_DATA:
					/* NOTE: some vars are not read, as they are not used by the CGIs (modified attributes, event handler commands, etc.) */
					if(temp_hoststatus != NULL) {
						if(!strcmp(var, "host_name"))
							temp_hoststatus->host_name = (char *)strdup(val);
						else if(!strcmp(var, "has_been_checked"))
							temp_hoststatus->has_been_checked = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "should_be_scheduled"))
							temp_hoststatus->should_be_scheduled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "check_execution_time"))
							temp_hoststatus->execution_time = strtod(val, NULL);
						else if(!strcmp(var, "check_latency"))
							temp_hoststatus->latency = strtod(val, NULL);
						else if(!strcmp(var, "check_type"))
							temp_hoststatus->check_type = atoi(val);
						else if(!strcmp(var, "current_state"))
							temp_hoststatus->status = atoi(val);
						else if(!strcmp(var, "last_hard_state"))
							temp_hoststatus->last_hard_state = atoi(val);
						else if(!strcmp(var, "plugin_output")) {
							temp_hoststatus->plugin_output = (char *)strdup(val);
							unescape_newlines(temp_hoststatus->plugin_output);
							}
						else if(!strcmp(var, "long_plugin_output")) {
							temp_hoststatus->long_plugin_output = (char *)strdup(val);
							unescape_newlines(temp_hoststatus->long_plugin_output);
							}
						else if(!strcmp(var, "performance_data"))
							temp_hoststatus->perf_data = (char *)strdup(val);
						else if(!strcmp(var, "current_attempt"))
							temp_hoststatus->current_attempt = atoi(val);
						else if(!strcmp(var, "max_attempts"))
							temp_hoststatus->max_attempts = atoi(val);
						else if(!strcmp(var, "last_check"))
							temp_hoststatus->last_check = strtoul(val, NULL, 10);
						else if(!strcmp(var, "next_check"))
							temp_hoststatus->next_check = strtoul(val, NULL, 10);
						else if(!strcmp(var, "check_options"))
							temp_hoststatus->check_options = atoi(val);
						else if(!strcmp(var, "current_attempt"))
							temp_hoststatus->current_attempt = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "state_type"))
							temp_hoststatus->state_type = atoi(val);
						else if(!strcmp(var, "last_state_change"))
							temp_hoststatus->last_state_change = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_hard_state_change"))
							temp_hoststatus->last_hard_state_change = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_up"))
							temp_hoststatus->last_time_up = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_down"))
							temp_hoststatus->last_time_down = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_unreachable"))
							temp_hoststatus->last_time_unreachable = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_notification"))
							temp_hoststatus->last_notification = strtoul(val, NULL, 10);
						else if(!strcmp(var, "next_notification"))
							temp_hoststatus->next_notification = strtoul(val, NULL, 10);
						else if(!strcmp(var, "no_more_notifications"))
							temp_hoststatus->no_more_notifications = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "current_notification_number"))
							temp_hoststatus->current_notification_number = atoi(val);
						else if(!strcmp(var, "notifications_enabled"))
							temp_hoststatus->notifications_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "problem_has_been_acknowledged"))
							temp_hoststatus->problem_has_been_acknowledged = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "acknowledgement_type"))
							temp_hoststatus->acknowledgement_type = atoi(val);
						else if(!strcmp(var, "active_checks_enabled"))
							temp_hoststatus->checks_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "passive_checks_enabled"))
							temp_hoststatus->accept_passive_checks = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "event_handler_enabled"))
							temp_hoststatus->event_handler_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "flap_detection_enabled"))
							temp_hoststatus->flap_detection_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "process_performance_data"))
							temp_hoststatus->process_performance_data = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "obsess_over_host") || !strcmp(var, "obsess"))
							temp_hoststatus->obsess = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "last_update"))
							temp_hoststatus->last_update = strtoul(val, NULL, 10);
						else if(!strcmp(var, "is_flapping"))
							temp_hoststatus->is_flapping = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "percent_state_change"))
							temp_hoststatus->percent_state_change = strtod(val, NULL);
						else if(!strcmp(var, "scheduled_downtime_depth"))
							temp_hoststatus->scheduled_downtime_depth = atoi(val);
						}
					break;

				case XSDDEFAULT_SERVICESTATUS_DATA:
					/* NOTE: some vars are not read, as they are not used by the CGIs (modified attributes, event handler commands, etc.) */
					if(temp_servicestatus != NULL) {
						if(!strcmp(var, "host_name"))
							temp_servicestatus->host_name = (char *)strdup(val);
						else if(!strcmp(var, "service_description"))
							temp_servicestatus->description = (char *)strdup(val);
						else if(!strcmp(var, "has_been_checked"))
							temp_servicestatus->has_been_checked = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "should_be_scheduled"))
							temp_servicestatus->should_be_scheduled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "check_execution_time"))
							temp_servicestatus->execution_time = strtod(val, NULL);
						else if(!strcmp(var, "check_latency"))
							temp_servicestatus->latency = strtod(val, NULL);
						else if(!strcmp(var, "check_type"))
							temp_servicestatus->check_type = atoi(val);
						else if(!strcmp(var, "current_state"))
							temp_servicestatus->status = atoi(val);
						else if(!strcmp(var, "last_hard_state"))
							temp_servicestatus->last_hard_state = atoi(val);
						else if(!strcmp(var, "current_attempt"))
							temp_servicestatus->current_attempt = atoi(val);
						else if(!strcmp(var, "max_attempts"))
							temp_servicestatus->max_attempts = atoi(val);
						else if(!strcmp(var, "state_type"))
							temp_servicestatus->state_type = atoi(val);
						else if(!strcmp(var, "last_state_change"))
							temp_servicestatus->last_state_change = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_hard_state_change"))
							temp_servicestatus->last_hard_state_change = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_ok"))
							temp_servicestatus->last_time_ok = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_warning"))
							temp_servicestatus->last_time_warning = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_unknown"))
							temp_servicestatus->last_time_unknown = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_critical"))
							temp_servicestatus->last_time_critical = strtoul(val, NULL, 10);
						else if(!strcmp(var, "plugin_output")) {
							temp_servicestatus->plugin_output = (char *)strdup(val);
							unescape_newlines(temp_servicestatus->plugin_output);
							}
						else if(!strcmp(var, "long_plugin_output")) {
							temp_servicestatus->long_plugin_output = (char *)strdup(val);
							unescape_newlines(temp_servicestatus->long_plugin_output);
							}
						else if(!strcmp(var, "performance_data"))
							temp_servicestatus->perf_data = (char *)strdup(val);
						else if(!strcmp(var, "last_check"))
							temp_servicestatus->last_check = strtoul(val, NULL, 10);
						else if(!strcmp(var, "next_check"))
							temp_servicestatus->next_check = strtoul(val, NULL, 10);
						else if(!strcmp(var, "check_options"))
							temp_servicestatus->check_options = atoi(val);
						else if(!strcmp(var, "current_notification_number"))
							temp_servicestatus->current_notification_number = atoi(val);
						else if(!strcmp(var, "last_notification"))
							temp_servicestatus->last_notification = strtoul(val, NULL, 10);
						else if(!strcmp(var, "next_notification"))
							temp_servicestatus->next_notification = strtoul(val, NULL, 10);
						else if(!strcmp(var, "no_more_notifications"))
							temp_servicestatus->no_more_notifications = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "notifications_enabled"))
							temp_servicestatus->notifications_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "active_checks_enabled"))
							temp_servicestatus->checks_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "passive_checks_enabled"))
							temp_servicestatus->accept_passive_checks = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "event_handler_enabled"))
							temp_servicestatus->event_handler_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "problem_has_been_acknowledged"))
							temp_servicestatus->problem_has_been_acknowledged = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "acknowledgement_type"))
							temp_servicestatus->acknowledgement_type = atoi(val);
						else if(!strcmp(var, "flap_detection_enabled"))
							temp_servicestatus->flap_detection_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "process_performance_data"))
							temp_servicestatus->process_performance_data = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "obsess_over_service") || !strcmp(var, "obsess"))
							temp_servicestatus->obsess = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "last_update"))
							temp_servicestatus->last_update = strtoul(val, NULL, 10);
						else if(!strcmp(var, "is_flapping"))
							temp_servicestatus->is_flapping = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "percent_state_change"))
							temp_servicestatus->percent_state_change = strtod(val, NULL);
						else if(!strcmp(var, "scheduled_downtime_depth"))
							temp_servicestatus->scheduled_downtime_depth = atoi(val);
						}
					break;

				case XSDDEFAULT_CONTACTSTATUS_DATA:
					/* unimplemented */
					break;

				case XSDDEFAULT_HOSTCOMMENT_DATA:
				case XSDDEFAULT_SERVICECOMMENT_DATA:
					if(!strcmp(var, "host_name"))
						host_name = (char *)strdup(val);
					else if(!strcmp(var, "service_description"))
						service_description = (char *)strdup(val);
					else if(!strcmp(var, "entry_type"))
						entry_type = atoi(val);
					else if(!strcmp(var, "comment_id"))
						comment_id = strtoul(val, NULL, 10);
					else if(!strcmp(var, "source"))
						source = atoi(val);
					else if(!strcmp(var, "persistent"))
						persistent = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "entry_time"))
						entry_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "expires"))
						expires = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "expire_time"))
						expire_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "author"))
						author = (char *)strdup(val);
					else if(!strcmp(var, "comment_data"))
						comment_data = (char *)strdup(val);
					break;

				case XSDDEFAULT_HOSTDOWNTIME_DATA:
				case XSDDEFAULT_SERVICEDOWNTIME_DATA:
					if(!strcmp(var, "host_name"))
						host_name = (char *)strdup(val);
					else if(!strcmp(var, "service_description"))
						service_description = (char *)strdup(val);
					else if(!strcmp(var, "downtime_id"))
						downtime_id = strtoul(val, NULL, 10);
					else if(!strcmp(var, "comment_id"))
						comment_id = strtoul(val, NULL, 10);
					else if(!strcmp(var, "entry_time"))
						entry_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "start_time"))
						start_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "flex_downtime_start"))
						flex_downtime_start = strtoul(val, NULL, 10);
					else if(!strcmp(var, "end_time"))
						end_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "fixed"))
						fixed = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "triggered_by"))
						triggered_by = strtoul(val, NULL, 10);
					else if(!strcmp(var, "duration"))
						duration = strtoul(val, NULL, 10);
					else if(!strcmp(var, "is_in_effect"))
						is_in_effect = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "author"))
						author = (char *)strdup(val);
					else if(!strcmp(var, "comment"))
						comment_data = (char *)strdup(val);
					break;

				default:
					break;
				}

			}
		}

	/* free memory and close the file */
#ifdef NO_MMAP
	fclose(fp);
#else
	my_free(input);
	mmap_fclose(thefile);
#endif

	/* free memory */
	my_free(xsddefault_status_log);
	my_free(xsddefault_temp_file);

	if(sort_downtime() != OK)
		return ERROR;
	if(sort_comments() != OK)
		return ERROR;

	return OK;
	}
Exemplo n.º 18
0
/* 
 * Read and process poll commands
 * Return:  -1 for quit command
 *          0 otherwise
 */
int process_args(int cmd_argc, char **cmd_argv, Poll **poll_list_ptr) {

    // some commands need the poll_list head and others
    // require the address of that head
    Poll *poll_list = *poll_list_ptr; 

    if (cmd_argc <= 0) {
        return 0;
    } else if (strcmp(cmd_argv[0], "quit") == 0 && cmd_argc == 1) {
        return -1;
        
    } else if (strcmp(cmd_argv[0], "add_poll") == 0 && cmd_argc == 3) {
        if (insert_new_poll(cmd_argv[1], strtol(cmd_argv[2], NULL, 10), 
            poll_list_ptr) == 1) {
            error("Poll by this name already exists");
        }
        
    } else if (strcmp(cmd_argv[0], "list_polls") == 0 && cmd_argc == 1) {
        print_polls(poll_list);
        
    } else if (strcmp(cmd_argv[0], "configure_poll") == 0 && cmd_argc >= 3) {
        int label_count = cmd_argc - 2; 
        int result = configure_poll(cmd_argv[1], &cmd_argv[2], label_count, 
                     poll_list);
        if (result == 1) {
           error("Poll by this name does not exist");
        } else if (result == 2) {
           error("Wrong number of slot labels provided for this poll\n");
        }

    } else if (strcmp(cmd_argv[0], "add_participant") == 0 && cmd_argc == 4) {
        int return_code = add_participant(cmd_argv[1], cmd_argv[2], poll_list, 
                                          cmd_argv[3]);
        if (return_code == 1) {
           error("Poll by this name does not exist");
        } else if (return_code == 2) {
           error("This Poll already has a participant by this name");
        } else if (return_code == 3) {
           error("Availability string is wrong size for this poll");
        }
      
    } else if (strcmp(cmd_argv[0], "add_comment") == 0 && cmd_argc >= 4) {
        // first determine how long a string we need
        int space_needed = 0;
        int i;
        for (i=3; i<cmd_argc; i++) {
            space_needed += strlen(cmd_argv[i]) + 1;
        }
        // allocate the space
        char *comment = malloc(space_needed);
        if (comment == NULL) {
            perror("malloc");
            exit(1);
        }
        // copy in the bits to make a single string
        strcpy(comment, cmd_argv[3]);
        for (i=4; i<cmd_argc; i++) {
            strcat(comment, " ");
            strcat(comment, cmd_argv[i]);
        }
        
        int return_code = add_comment(cmd_argv[1], cmd_argv[2], comment, 
                                      poll_list);
        // comment was only used as parameter so we are finished with it now
        free(comment);

        if (return_code == 1) {
           error("There is no poll with this name");
        } else if (return_code == 2) {
           error("There is no participant by this name in this poll");
        }

    } else if (strcmp(cmd_argv[0], "update_availability") == 0 && cmd_argc == 4) {
        int return_code = update_availability(cmd_argv[1], cmd_argv[2], 
                                           cmd_argv[3], poll_list);
        if (return_code == 1) {
           error("There is no poll with this name");
        } else if (return_code == 2) {
           error("There is no participant by this name in this poll");
        } else if (return_code == 3) {
           error("The length of the provided availability does not match" 
                  "number of slots in this poll");
        }

    } else if (strcmp(cmd_argv[0], "delete_poll") == 0 && cmd_argc == 2) {
        if (delete_poll(cmd_argv[1], poll_list_ptr) == 1) {
            error("No poll by this name exists");
        }

    } else if (strcmp(cmd_argv[0], "print_poll_info") == 0 && cmd_argc == 2) {
        if (print_poll_info(cmd_argv[1], poll_list) == 1) {
            error("No poll by this name exists");
        }

    } else {
        error("Incorrect syntax");
    }
    return 0;
}