Пример #1
0
void Convert::convert_start(void)
{
    update_progress(0.0);

    if(!libvlc_loaded)
    {
        if(convert_init() == 0)
            libvlc_loaded = true;
        else
        {
            status(tr("Internal error !"));
            return;
        }
    }

    ui.convert_button->setEnabled(false);
    ui.input_choose->setEnabled(false);
    ui.output_choose->setEnabled(false);

    status(tr("in progress"));

    thread = new ConvertThread(
         ui.input_file->text().toUtf8().data(),
        ui.output_file->text().toUtf8().data());

    connect(thread, SIGNAL(finished()), this, SLOT(finished()));
    connect(thread, SIGNAL(progress_changed(float)),
            this, SLOT(update_progress(float)));

    thread->start();
}
Пример #2
0
/**
 * _pyjava.start function: dynamically load a JVM DLL and start it.
 */
static PyObject *pyjava_start(PyObject *self, PyObject *args)
{
    const char *path;
    PyObject *options;
    size_t size;
    const char **option_array;
    size_t i;

    if(!(PyArg_ParseTuple(args, "sO!", &path, &PyList_Type, &options)))
        return NULL;

    if(penv != NULL)
    {
        PyErr_SetString(
                Err_Base,
                "Attempt to start() the JVM a second time.");
        return NULL;
    }

    size = PyList_GET_SIZE(options);
    option_array = malloc(size * sizeof(char *));
    for(i = 0; i < size; ++i)
    {
        PyObject *option = PyList_GET_ITEM(options, i);
        if(!PyString_Check(option))
        {
            PyErr_SetString(
                    PyExc_TypeError,
                    "Options list contained non-string objects.");
            free(option_array);
            return NULL;
        }

        option_array[i] = PyString_AS_STRING(option);
    }

    penv = java_start_vm(path, option_array, size);
    free(option_array);

    if(penv != NULL)
    {
        /*
         * Initialize the modules dependent on the JVM (load classes and
         * methods, ...)
         */
        java_init();
        convert_init();

        Py_INCREF(Py_True);
        return Py_True;
    }
    else
    {
        Py_INCREF(Py_False);
        return Py_False;
    }
}
Пример #3
0
int do_init(int argc, char** argv)
{
	char_config_read( (argc > 1) ? argv[1] : CHAR_CONF_NAME);
	mapindex_init();
	sql_config_read( (argc > 2) ? argv[2] : SQL_CONF_NAME);
	inter_init_txt( (argc > 3) ? argv[3] : INTER_CONF_NAME);
	inter_init_sql( (argc > 3) ? argv[3] : INTER_CONF_NAME);
	convert_init();
	ShowStatus("Everything's been converted!\n");
	mapindex_final();
	return 0;
}
Пример #4
0
static void init_data(args_t *args)
{
    args->header = args->files->readers[0].header;

    int i, nsamples = 0, *samples = NULL;
    if ( args->sample_list && strcmp("-",args->sample_list) )
    {
        for (i=0; i<args->files->nreaders; i++)
        {
            int ret = bcf_hdr_set_samples(args->files->readers[i].header,args->sample_list,args->sample_is_file);
            if ( ret<0 ) error("Error parsing the sample list\n");
            else if ( ret>0 ) error("Sample name mismatch: sample #%d not found in the header\n", ret);
        }

        if ( args->sample_list[0]!='^' )
        {
            // the sample ordering may be different if not negated
            int n;
            char **smpls = hts_readlist(args->sample_list, args->sample_is_file, &n);
            if ( !smpls ) error("Could not parse %s\n", args->sample_list);
            if ( n!=bcf_hdr_nsamples(args->files->readers[0].header) )
                error("The number of samples does not match, perhaps some are present multiple times?\n");
            nsamples = bcf_hdr_nsamples(args->files->readers[0].header);
            samples = (int*) malloc(sizeof(int)*nsamples);
            for (i=0; i<n; i++)
            {
                samples[i] = bcf_hdr_id2int(args->files->readers[0].header, BCF_DT_SAMPLE,smpls[i]);
                free(smpls[i]);
            }
            free(smpls);
        }
    }
    args->convert = convert_init(args->header, samples, nsamples, args->format_str);
    if ( args->allow_undef_tags ) convert_set_option(args->convert, allow_undef_tags, 1);
    free(samples);

    int max_unpack = convert_max_unpack(args->convert);
    if ( args->filter_str )
    {
        args->filter = filter_init(args->header, args->filter_str);
        max_unpack |= filter_max_unpack(args->filter);
    }
    args->files->max_unpack = max_unpack;
}
Пример #5
0
static gint file_open(gint fmt, gint rate, gint nch)
{
    gchar *filename = NULL, *temp = NULL;
    gchar * directory;
    gint pos;
    gint rv;
    gint playlist;

    input.format = fmt;
    input.frequency = rate;
    input.channels = nch;

    playlist = aud_playlist_get_playing ();
    if (playlist < 0)
        return 0;

    pos = aud_playlist_get_position(playlist);
    tuple = aud_playlist_entry_get_tuple (playlist, pos, FALSE);
    if (tuple == NULL)
        return 0;

    if (filenamefromtags)
    {
        gchar * utf8 = aud_playlist_entry_get_title (playlist, pos, FALSE);
        string_replace_char (utf8, '/', ' ');

        gchar buf[3 * strlen (utf8) + 1];
        str_encode_percent (utf8, -1, buf);
        str_unref (utf8);

        filename = g_strdup (buf);
    }
    else
    {
        temp = aud_playlist_entry_get_filename (playlist, pos);
        gchar * original = strrchr (temp, '/');
        g_return_val_if_fail (original != NULL, 0);
        filename = g_strdup (original + 1);
        str_unref (temp);

        if (!use_suffix)
            if ((temp = strrchr(filename, '.')) != NULL)
                *temp = '\0';
    }

    if (prependnumber)
    {
        gint number = tuple_get_int(tuple, FIELD_TRACK_NUMBER, NULL);
        if (!tuple || !number)
            number = pos + 1;

        temp = g_strdup_printf ("%d%%20%s", number, filename);
        g_free(filename);
        filename = temp;
    }

    if (save_original)
    {
        temp = aud_playlist_entry_get_filename (playlist, pos);
        directory = g_strdup (temp);
        str_unref (temp);
        temp = strrchr (directory, '/');
        g_return_val_if_fail (temp != NULL, 0);
        temp[1] = 0;
    }
    else
    {
        g_return_val_if_fail (file_path[0], 0);
        if (file_path[strlen (file_path) - 1] == '/')
            directory = g_strdup (file_path);
        else
            directory = g_strdup_printf ("%s/", file_path);
    }

    temp = g_strdup_printf ("%s%s.%s", directory, filename, fileext_str[fileext]);
    g_free (directory);
    g_free (filename);
    filename = temp;

    output_file = safe_create (filename);
    g_free (filename);

    if (output_file == NULL)
        return 0;

    convert_init (fmt, plugin->format_required (fmt), nch);

    rv = (plugin->open)();

    samples_written = 0;

    return rv;
}
Пример #6
0
int main(int argc, char *argv[])
{
    char **url = NULL;
    int n_url = 0, cur_url = 0;
    int check_interval = 15 * 60;
    mrss_t **data_prev = NULL;
    mrss_t **data_cur = NULL;
    int data_size;
    char *proxy = NULL, *proxy_auth = NULL;
    int sw;
    int verbose = 0;
    int notify_friendly = 0;
    char show_timestamp = 0, show_link = 0, show_description = 0, show_pubdate = 0, show_author = 0, show_comments = 0;
    char strip_html = 0, no_error_exit = 0;
    char one_shot = 0;
    char no_heading = 0;
    int bytes_limit = 0;
    time_t last_changed = (time_t)0;
    char continue_on_error = 0/*, dummy*/;
    int show_n = -1;
    /*long int max_age = -1;*/
    char *heading = NULL;
    mrss_options_t mot;

    convert_context_t conv_context;
    convert_context_t* cc = &conv_context;
    char *conv_title = 0;
    char *rss_title = 0;
    char *conv_rss_title = 0;
    char *conv_author = 0;
    char *conv_description = 0;
    char *conv_comments = 0;

    tzset();
    setlocale(LC_ALL, "");

    memset(&mot, 0x00, sizeof(mot));

    while((sw = getopt(argc, argv, "Z:1b:PHztldpacmu:Ni:n:x:y:vVh")) != -1)
    {
        switch(sw)
        {
            case 'Z':
                heading = optarg;
                break;

            case 'N':
                no_heading = 1;
                break;

            case 'm':
                notify_friendly = 1;
                break;

            case '1':
                one_shot = 1;
                break;

            case 'b':
                bytes_limit = atoi(optarg);
                if (bytes_limit <= 0)
                {
                    fprintf(stderr, "-b requires a number > 0\n");
                    return 1;
                }
                break;

            case 'P':
                no_error_exit = 1;
                break;

            case 'H':
                strip_html = 1;
                break;

            case 'n':
                show_n = atoi(optarg);
                if (show_n < 0)
                {
                    fprintf(stderr, "-n requires an positive value\n");
                    return 1;
                }
                else if (show_n > 50)
                    fprintf(stderr, "Initially showing more then 50 items, must be one hell of an rss feed!\n");
                break;

#if 0
            case 'o':
                dummy = optarg[strlen(optarg) - 1];
                max_age = atoi(optarg);
                if (max_age < 0)
                {
                    printf("-o requires an positive value\n");
                    return 1;
                }
                if (dummy == 's')
                    max_age *= 1;
                else if (dummy == 'M')
                    max_age *= 60;
                else if (dummy == 'h')
                    max_age *= 3600;
                else if (dummy == 'd')
                    max_age *= 86400;
                else if (dummy == 'm')
                    max_age *= 86400 * 31;
                else if (dummy == 'y')
                    max_age *= 86400 * 365.25;
                else if (isalpha(dummy))
                {
                    printf("'%c' is a not recognized multiplier\n", dummy);
                    return 1;
                }
                break;
#endif

            case 'z':
                continue_on_error = 1;
                break;

            case 't':
                show_timestamp = 1;
                break;

            case 'l':
                show_link = 1;
                break;

            case 'd':
                show_description = 1;
                break;

            case 'p':
                show_pubdate = 1;
                break;

            case 'a':
                show_author = 1;
                break;

            case 'c':
                show_comments = 1;
                break;

            case 'u':
                url = (char **)realloc(url, sizeof(char *) * (n_url + 1));
                if (!url)
                {
                    fprintf(stderr, "Cannot allocate memory\n");
                    return 2;
                }
                url[n_url++] = optarg;
                break;

            case 'i':
                check_interval = atoi(optarg);
                break;

            case 'x':
                proxy = optarg;
                break;

            case 'y':
                proxy_auth = optarg;
                break;

            case 'v':
                verbose++;
                break;

            case 'V':
                version();
                return 1;

            case 'h':
            default:
                usage();
                return 1;
        }
    }

    mot.timeout = check_interval;
        mot.proxy = proxy;
    mot.proxy_authentication = proxy_auth;
    mot.user_agent = "rsstail " VERSION ", (C) 2006-2007 by [email protected]";

    if (n_url == 0)
    {
        fprintf(stderr, "Please give the URL of the RSS feed to check with the '-u' parameter.\n");
        return 1;
    }

    data_size = sizeof(mrss_t *) * n_url;
    data_prev = (mrss_t **)malloc(data_size);
    data_cur  = (mrss_t **)malloc(data_size);
    if (!data_prev || !data_cur)
    {
        fprintf(stderr, "Cannot allocate memory\n");
        return 2;
    }

    memset(data_prev, 0x00, data_size);
    memset(data_cur , 0x00, data_size);

    if (verbose)
    {
        int loop;
        fprintf(stderr, "Monitoring RSS feeds:\n");
        for(loop=0; loop<n_url; loop++)
            fprintf(stderr, "\t%s\n", url[loop]);
        fprintf(stderr, "Check interval: %d\n", check_interval);
    }

    for(;;)
    {
        mrss_error_t err_read;
        mrss_item_t *item_cur = NULL;
        time_t cur_last_changed;
        int n_shown = 0;

        if (verbose)
            fprintf(stderr, "Retrieving RSS feed '%s'...\n", url[cur_url]);

        if ((err_read = mrss_get_last_modified(url[cur_url], &cur_last_changed)) != MRSS_OK)
        {
            if (err_read == MRSS_ERR_POSIX)
            {
                if (errno == EINPROGRESS)
                {
                    fprintf(stderr, "Time-out while connecting to RSS feed, continuing\n");
                    goto goto_next_url;
                }
            }

            fprintf(stderr, "Error reading RSS feed: %s\n", mrss_strerror(err_read));

            if (no_error_exit)
                goto goto_next_url;
            else
                return 2;
        }

        if (cur_last_changed == last_changed && cur_last_changed != 0)
        {
            if (verbose)
                fprintf(stderr, "Feed did not change since last check.\n");
            goto goto_next_url;
        }
        last_changed = cur_last_changed;

        if ((err_read = mrss_parse_url_with_options(url[cur_url], &data_cur[cur_url], &mot)) != MRSS_OK)
        {
            if (err_read == MRSS_ERR_POSIX)
            {
                if (errno == EINPROGRESS)
                {
                    fprintf(stderr, "Time-out while connecting to RSS feed, continuing\n");
                    goto goto_next_url;
                }
            }
            else if (err_read == MRSS_ERR_PARSER && continue_on_error)
            {
                fprintf(stderr, "Error reading RSS feed: %s\n", mrss_strerror(err_read));
                goto goto_next_url;
            }

            fprintf(stderr, "Error reading RSS feed: %s\n", mrss_strerror(err_read));
            if (no_error_exit)
                goto goto_next_url;
            else
                return 2;
        }

        item_cur = data_cur[cur_url] -> item;
        rss_title = data_cur[cur_url] -> title;

        if( !convert_init(cc, data_cur[cur_url]->encoding, convert_system_enc()) )
        {
            fprintf(stderr, "\nERROR: iconv initialization error.\n" );
        }

        while(item_cur)
        {
            if ((data_prev[cur_url] && is_new_record(data_prev[cur_url] -> item, item_cur) != -1) ||
                (!data_prev[cur_url]))
            {
#if 0
                if (/* pubdate */ < max_age && max_age != -1)
                    continue;
#endif

                if ((!data_prev[cur_url]) && n_shown >= show_n && show_n != -1)
                {
                    item_cur = item_cur -> next;
                    continue;
                }
                n_shown++;

                if ((show_link + show_description + show_pubdate + show_author + show_comments ) > 1 && !notify_friendly )
                    printf("\n");

                if (show_timestamp)
                {
                    time_t now = time(NULL);
                    struct tm *now_tm = localtime(&now);

                    printf("%04d/%02d/%02d %02d:%02d:%02d  ",
                            now_tm -> tm_year + 1900,
                            now_tm -> tm_mon + 1,
                            now_tm -> tm_mday,
                            now_tm -> tm_hour,
                            now_tm -> tm_min,
                            now_tm -> tm_sec);
                }

                if (show_pubdate && item_cur -> pubDate != NULL)
                {
                    if ( notify_friendly )
                    {
                        char* new_date_str = convert_pub_date(item_cur->pubDate);
                        printf("%s%s ", no_heading?" ":"Pub.date: ", new_date_str);
                        free(new_date_str);
                    }
                    else
                    {
                        printf("%s%s\n", no_heading?" ":"Pub.date: ", item_cur -> pubDate);
                    }
                }

                if (heading)
                {
                    printf(" %s", heading);
                }

                if ( notify_friendly )
                {
                    if ( rss_title )
                    {
                        conv_rss_title = convert(cc, rss_title);
                        printf("%s*%s* ", no_heading?" ":"RSS Title: ", conv_rss_title);
                        free(conv_rss_title);
                    }
                }

                if (item_cur -> title != NULL)
                {
                    conv_title = convert(cc, item_cur->title);
                    printf("%s%s%s", no_heading?" ":"Title: ", conv_title, (notify_friendly?" ":"\n"));
                    free(conv_title);
                }

                if (show_link && item_cur -> link != NULL)
                {
                    if ( notify_friendly )
                    {
                        printf("%s<a href=\"%s\">Link</a>\n", no_heading?" ":"Link: ", item_cur -> link );
                    }
                    else
                    {
                        printf("%s%s\n", no_heading?" ":"Link: ", item_cur -> link );
                    }
                }
                else
                {
                    if ( notify_friendly )
                    {
                        printf("\n"); //crlf without Link html tag
                    }
                }

                if (show_description && item_cur -> description != NULL)
                {
                    if (strip_html)
                    {
                        char *stripped = remove_html_tags(item_cur -> description);

                        if (bytes_limit != 0 && bytes_limit < strlen(stripped))
                            stripped[bytes_limit] = 0x00;

                        conv_description = convert(cc, stripped);
                        printf("%s%s\n", no_heading?" ":"Description: ", conv_description);
                        free(conv_description);

                        free(stripped);
                    }
                    else
                    {
                        if (bytes_limit != 0 && bytes_limit < strlen(item_cur -> description))
                            (item_cur -> description)[bytes_limit] = 0x00;

                        conv_description = convert(cc, item_cur->description);
                        printf("%s%s\n", no_heading?" ":"Description: ", conv_description);
                        free(conv_description);
                    }
                }

                if (show_author && item_cur -> author != NULL)
                {
                    conv_author = convert(cc, item_cur->author);
                    printf("%s%s\n", no_heading?" ":"Author: ", conv_author);
                    free(conv_author);
                }

                if (show_comments && item_cur -> comments != NULL)
                {
                    if (bytes_limit != 0 && bytes_limit < strlen(item_cur -> comments))
                        (item_cur -> comments)[bytes_limit] = 0x00;

                    conv_comments = convert(cc, item_cur->comments);
                    printf("%s%s\n", no_heading?" ":"Comments: ", conv_comments);
                    free(conv_comments);
                }
            }

            item_cur = item_cur -> next;
        }

        convert_close(cc);

        if (data_prev[cur_url])
        {
            mrss_error_t err_free = mrss_free(data_prev[cur_url]);

            if (err_free != MRSS_OK)
            {
                fprintf(stderr, "Error freeing up memory: %s\n", mrss_strerror(err_read));
                if (no_error_exit)
                    goto goto_next_url;
                else
                    return 2;
            }
        }

        data_prev[cur_url] = data_cur[cur_url];
        data_cur[cur_url] = NULL;

goto_next_url:
        cur_url++;
        if (cur_url == n_url)
            cur_url = 0;

        fflush(stdout);

        if (one_shot)
            break;

        if (verbose > 2)
            fprintf(stderr, "Sleeping...\n");
        sleep(check_interval / n_url);
    }

    return 0;
}
Пример #7
0
/**
 * \brief Input plugin initializtion function
 *
 * \param[in]  params XML with input parameters
 * \param[out] config  Sets source and destination IP, destination port.
 * \return 0 on success, nonzero else.
 */
int input_init(char *params, void **config)
{
	/* necessary structures */
	struct addrinfo *addrinfo = NULL, hints;
	struct plugin_conf *conf = NULL;
	char *port = NULL, *address = NULL;
	int ai_family = AF_INET6; /* IPv6 is default */
	char dst_addr[INET6_ADDRSTRLEN];
	int ret, ipv6_only = 0, retval = 0;

	/* 1 when using default port - don't free memory */
	int default_port = 0;

	/* parse params */
	xmlDoc *doc = NULL;
	xmlNode *root_element = NULL;
	xmlNode *cur_node = NULL;

	/* allocate plugin_conf structure */
	conf = calloc(1, sizeof(struct plugin_conf));
	if (conf == NULL) {
		MSG_ERROR(msg_module, "Cannot allocate memory for config structure: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* parse xml string */
	doc = xmlParseDoc(BAD_CAST params);
	if (doc == NULL) {
		printf("%s", params);
		MSG_ERROR(msg_module, "Cannot parse configuration");
		retval = 1;
		goto out;
	}

	/* get the root element node */
	root_element = xmlDocGetRootElement(doc);
	if (root_element == NULL) {
		MSG_ERROR(msg_module, "Cannot get document root element");
		retval = 1;
		goto out;
	}

	/* check that we have the right config xml, BAD_CAST is (xmlChar *) cast defined by libxml */
	if (!xmlStrEqual(root_element->name, BAD_CAST "udpCollector")) {
		MSG_ERROR(msg_module, "Expecting udpCollector root element, got %s", root_element->name);
		retval = 1;
		goto out;
	}

	/* go over all elements */
	for (cur_node = root_element->children; cur_node; cur_node = cur_node->next) {
		if (cur_node->type == XML_ELEMENT_NODE
				&& cur_node->children != NULL
				&& cur_node->children->content != NULL) {
			/* copy value to memory - don't forget the terminating zero */
			int tmp_val_len = strlen((char *) cur_node->children->content) + 1;
			char *tmp_val = malloc(sizeof(char) * tmp_val_len);
			if (tmp_val == NULL) {
				MSG_ERROR(msg_module, "Cannot allocate memory: %s", strerror(errno));
				retval = 1;
				goto out;
			}

			/* this is not a preferred cast, but we really want to use plain chars here */
			strncpy_safe(tmp_val, (char *) cur_node->children->content, tmp_val_len);

			if (xmlStrEqual(cur_node->name, BAD_CAST "localPort")) { /* set local port */
				if (port) {
					free(port);
				}
				port = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "localIPAddress")) { /* set local address */
				if (address) {
					free(address);
				}
				address = tmp_val;

			/* save following configuration to input_info */
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "templateLifeTime")) {
				if (conf->info.template_life_time) {
					free(conf->info.template_life_time);
				}
				conf->info.template_life_time = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "optionsTemplateLifeTime")) {
				if (conf->info.options_template_life_time) {
					free(conf->info.options_template_life_time);
				}
				conf->info.options_template_life_time = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "templateLifePacket")) {
				if (conf->info.template_life_packet) {
					free(conf->info.template_life_packet);
				}
				conf->info.template_life_packet = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "optionsTemplateLifePacket")) {
				if (conf->info.options_template_life_packet) {
					free(conf->info.options_template_life_packet);
				}
				conf->info.options_template_life_packet = tmp_val;
			} else { /* unknown parameter, ignore */
				free(tmp_val);
			}
		}
	}

	/* set default port if none given */
	if (port == NULL) {
		port = DEFAULT_PORT;
		default_port = 1;
	}

	/* specify parameters of the connection */
	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_socktype = SOCK_DGRAM; /* UDP */
	hints.ai_family = ai_family; /* both IPv4 and IPv6*/
	hints.ai_flags = AI_V4MAPPED; /* we want to accept mapped addresses */
	if (address == NULL) {
		hints.ai_flags |= AI_PASSIVE; /* no address given, listen on all local addresses */
	}

	/* get server address */
	if ((ret = getaddrinfo(address, port, &hints, &addrinfo)) != 0) {
		MSG_ERROR(msg_module, "getaddrinfo failed: %s", gai_strerror(ret));
		retval = 1;
		goto out;
	}

	/* create socket */
	conf->socket = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);

	/* Retry with IPv4 when the implementation does not support the specified address family */
	if (conf->socket == -1 && errno == EAFNOSUPPORT && addrinfo->ai_family == AF_INET6) {
		addrinfo->ai_family = AF_INET;
		conf->socket = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
	}
	if (conf->socket == -1) {
		MSG_ERROR(msg_module, "Cannot create socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* allow IPv4 connections on IPv6 */
	if ((addrinfo->ai_family == AF_INET6) &&
			(setsockopt(conf->socket, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_only, sizeof(ipv6_only)) == -1)) {
		MSG_WARNING(msg_module, "Cannot turn off socket option IPV6_V6ONLY; plugin may not accept IPv4 connections...");
	}

	/* bind socket to address */
	if (bind(conf->socket, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
		MSG_ERROR(msg_module, "Cannot bind socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* fill in general information */
	conf->info.type = SOURCE_TYPE_UDP;
	conf->info.dst_port = atoi(port);
	if (addrinfo->ai_family == AF_INET) { /* IPv4 */
		conf->info.l3_proto = 4;

		/* copy dst IPv4 address */
		conf->info.dst_addr.ipv4.s_addr =
			((struct sockaddr_in*) addrinfo->ai_addr)->sin_addr.s_addr;

		inet_ntop(AF_INET, &conf->info.dst_addr.ipv4, dst_addr, INET6_ADDRSTRLEN);
	} else { /* IPv6 */
		conf->info.l3_proto = 6;

		/* copy destination IPv6 address */
		int i;
		for (i = 0; i < 4; i++) {
			conf->info.dst_addr.ipv6.s6_addr32[i] =
				((struct sockaddr_in6*) addrinfo->ai_addr)->sin6_addr.s6_addr32[i];
		}

		inet_ntop(AF_INET6, &conf->info.dst_addr.ipv6, dst_addr, INET6_ADDRSTRLEN);
	}

	if (convert_init(UDP_PLUGIN, BUFF_LEN) != 0) {
		MSG_ERROR(msg_module, "Failed to initialize templates");
		retval = 1;
		goto out;
	}

	/* print info */
	MSG_INFO(msg_module, "Input plugin listening on %s, port %s", dst_addr, port);

	/* and pass it to the collector */
	*config = (void*) conf;

	/* normal exit, all OK */
	MSG_INFO(msg_module, "Plugin initialization completed successfully");

out:
	if (default_port == 0 && port != NULL) { /* free when memory was actually allocated */
		free(port);
	}

	if (address != NULL) {
		free(address);
	}

	if (addrinfo != NULL) {
		freeaddrinfo(addrinfo);
	}

	/* free the xml document */
	if (doc != NULL) {
		xmlFreeDoc(doc);
	}

	/* free the global variables that may have been allocated by the xml parser */
	xmlCleanupParser();

	/* free input_info when error occured */
	if (retval != 0 && conf != NULL) {
		if (conf->info.template_life_time != NULL) {
			free (conf->info.template_life_time);
		}
		if (conf->info.options_template_life_time != NULL) {
			free (conf->info.options_template_life_time);
		}
		if (conf->info.template_life_packet != NULL) {
			free (conf->info.template_life_packet);
		}
		if (conf->info.options_template_life_packet != NULL) {
			free (conf->info.options_template_life_packet);
		}
		free(conf);
	}

	return retval;
}
Пример #8
0
/**
 * \brief Input plugin initializtion function
 *
 * \param[in]  params  XML with input parameters
 * \param[out] config  Sets source and destination IP, destination port.
 * \return 0 on success, nonzero else.
 */
int input_init(char *params, void **config)
{
	/* necessary structures */
	struct addrinfo *addrinfo = NULL, hints;
	struct plugin_conf *conf = NULL;
	char *port = NULL, *address = NULL;
	int ai_family = AF_INET6; /* IPv6 is default */
	char dst_addr[INET6_ADDRSTRLEN];
	int ret, ipv6_only = 0, retval = 0, yes = 1; /* yes is for setsockopt */
	/* 1 when using default port - don't free memory */
	int def_port = 0;
#ifdef TLS_SUPPORT
	SSL_CTX *ctx = NULL;       /* SSL context structure */
	SSL **ssl_list = NULL;     /* list of SSL connection structures */
	xmlNode *cur_node_parent;
#endif

	/* parse params */
	xmlDoc *doc = NULL;
	xmlNode *root_element = NULL;
	xmlNode *cur_node = NULL;

	/* allocate plugin_conf structure */
	conf = calloc(1, sizeof(struct plugin_conf));
	if (conf == NULL) {
		MSG_ERROR(msg_module, "Cannot allocate memory for config structure: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	if (!enlarge_sock_addresses(conf)) {
		MSG_ERROR(msg_module, "Cannot initialize array for socket address");
		retval = 1;
		goto out;
	}

	/* empty the master set */
	FD_ZERO(&conf->master);

	/* parse xml string */
	doc = xmlParseDoc(BAD_CAST params);
	if (doc == NULL) {
		MSG_ERROR(msg_module, "Cannot parse configuration file");
		retval = 1;
		goto out;
	}
	/* get the root element node */
	root_element = xmlDocGetRootElement(doc);
	if (root_element == NULL) {
		MSG_ERROR(msg_module, "Cannot get document root element");
		retval = 1;
		goto out;
	}

	/* check that we have the right config xml, BAD_CAST is (xmlChar *) cast defined by libxml */
	if (!xmlStrEqual(root_element->name, BAD_CAST "tcpCollector")) {
		MSG_ERROR(msg_module, "Expecting tcpCollector root element; got %s", root_element->name);
		retval = 1;
		goto out;
	}

	/* go over all elements */
	for (cur_node = root_element->children; cur_node; cur_node = cur_node->next) {
#ifdef TLS_SUPPORT
		/* check whether we want to enable transport layer security */
		if (xmlStrEqual(cur_node->name, BAD_CAST "transportLayerSecurity")) {
			MSG_INFO(msg_module, "TLS enabled");
			conf->tls = 1;   /* TLS enabled */
			cur_node_parent = cur_node;	

			/* TLS configuration options */
			for (cur_node = cur_node->xmlChildrenNode; cur_node; cur_node = cur_node->next) {
			if (cur_node->type == XML_ELEMENT_NODE
						&& cur_node->children != NULL
						&& cur_node->children->content != NULL) {
					int tmp_val_len = strlen((char *) cur_node->children->content) + 1;
					char *tmp_val = malloc(sizeof(char) * tmp_val_len);
					if (!tmp_val) {
						MSG_ERROR(msg_module, "Cannot allocate memory: %s", strerror(errno));
						retval = 1;
						goto out;
					}
					strncpy_safe(tmp_val, (char *)cur_node->children->content, tmp_val_len);
					
					if (xmlStrEqual(cur_node->name, BAD_CAST "localCAfile")) {
						/* location of the CA certificate */
						conf->ca_cert_file = tmp_val;
					} else if (xmlStrEqual(cur_node->name, BAD_CAST "localServerCert")) {
						/* server's certificate */
						conf->server_cert_file = tmp_val;
					} else if (xmlStrEqual(cur_node->name, BAD_CAST "localServerCertKey")) {
						/* server's private key */
						conf->server_pkey_file = tmp_val;
					} else {
						/* unknown option */
						MSG_WARNING(msg_module, "Unknown configuration option: %s", cur_node->name);
						free(tmp_val);
					}
				}
			}

			cur_node = cur_node_parent;

			continue;
		}
#else   /* user wants TLS, but collector was compiled without it */
		if (xmlStrEqual(cur_node->name, BAD_CAST "transportLayerSecurity")) {
			/* user wants to enable TLS, but collector was compiled without it */
			MSG_WARNING(msg_module, "Collector was compiled without TLS support");
			continue;
		}
#endif
		if (cur_node->type == XML_ELEMENT_NODE && cur_node->children != NULL) {
			/* copy value to memory - don't forget the terminating zero */
			int tmp_val_len = strlen((char *) cur_node->children->content) + 1;
			char *tmp_val = malloc(sizeof(char) * tmp_val_len);
			/* this is not a preferred cast, but we really want to use plain chars here */
			if (tmp_val == NULL) {
				MSG_ERROR(msg_module, "Cannot allocate memory: %s", strerror(errno));
				retval = 1;
				goto out;
			}
			strncpy_safe(tmp_val, (char *)cur_node->children->content, tmp_val_len);

			if (xmlStrEqual(cur_node->name, BAD_CAST "localPort") && port == NULL) { /* set local port */
				port = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "localIPAddress") && address == NULL) { /* set local address */
				address = tmp_val;
			/* save following configuration to input_info */
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "templateLifeTime")) {
				conf->info.template_life_time = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "optionsTemplateLifeTime")) {
				conf->info.options_template_life_time = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "templateLifePacket")) {
				conf->info.template_life_packet = tmp_val;
			} else if (xmlStrEqual(cur_node->name, BAD_CAST "optionsTemplateLifePacket")) {
				conf->info.options_template_life_packet = tmp_val;
			} else { /* unknown parameter, ignore */
				/* Free the tmp_val for unknown elements */
				free(tmp_val);
			}
		}
	}

	/* set default port if none given */
	if (port == NULL) {
		port = DEFAULT_PORT;
		def_port = 1;
	}

#ifdef TLS_SUPPORT
	if (conf->tls) {
		/* use default options if not specified in configuration file */
		if (conf->ca_cert_file == NULL) {
			conf->ca_cert_file = strdup(DEFAULT_CA_FILE);
		}

		if (conf->server_cert_file == NULL) {
			conf->server_cert_file = strdup(DEFAULT_SERVER_CERT_FILE);
		}

		if (conf->server_pkey_file == NULL) {
			conf->server_pkey_file = strdup(DEFAULT_SERVER_PKEY_FILE);
		}
	}
#endif

	/* specify parameters of the connection */
	memset (&hints, 0, sizeof(struct addrinfo));
	hints.ai_socktype = SOCK_STREAM; /* TCP */
	hints.ai_family = ai_family; /* select IPv4 or IPv6*/
	hints.ai_flags = AI_V4MAPPED; /* we want to accept mapped addresses */
	if (address == NULL) {
		hints.ai_flags |= AI_PASSIVE; /* no address given, listen on all local addresses */
	}

	/* get server address */
	if ((ret = getaddrinfo(address, port, &hints, &addrinfo)) != 0) {
		MSG_ERROR(msg_module, "getaddrinfo failed: %s", gai_strerror(ret));
		retval = 1;
		goto out;
	}

	/* create socket */
	conf->socket = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
	/* Retry with IPv4 when the implementation does not support the specified address family */
	if (conf->socket == -1 && errno == EAFNOSUPPORT && addrinfo->ai_family == AF_INET6) {
		addrinfo->ai_family = AF_INET;
		conf->socket = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
	}
	if (conf->socket == -1) {
		/* End with error otherwise */
		MSG_ERROR(msg_module, "Cannot create socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* allow IPv4 connections on IPv6 */
	if ((addrinfo->ai_family == AF_INET6) &&
		(setsockopt(conf->socket, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_only, sizeof(ipv6_only)) == -1)) {
		MSG_WARNING(msg_module, "Cannot turn off socket option IPV6_V6ONLY; plugin may not accept IPv4 connections...");
	}

	/* allow to reuse the address immediately */
	if (setsockopt(conf->socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1)
	{
		MSG_WARNING(msg_module, "Cannot turn on socket reuse option; it may take a while before collector can be restarted");
	}

	/* bind socket to address */
	if (bind(conf->socket, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
		MSG_ERROR(msg_module, "Cannot bind socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

	/* this is a listening socket */
	if (listen(conf->socket, BACKLOG) == -1) {
		MSG_ERROR(msg_module, "Cannot listen on socket: %s", strerror(errno));
		retval = 1;
		goto out;
	}

#ifdef TLS_SUPPORT
	if (conf->tls) {
		/* configure TLS */
	
		/* initialize library */
		SSL_load_error_strings();
		SSL_library_init();
	
		/* create CTX structure for TLS */
		ctx = SSL_CTX_new(TLSv1_server_method());
		if (!ctx) {
			MSG_ERROR(msg_module, "Cannot create CTX structure");
			ERR_print_errors_fp(stderr);
			retval = 1;
			goto out;
		}
	
		/* load server certificate into the CTX structure */
		ret = SSL_CTX_use_certificate_file(ctx, conf->server_cert_file, SSL_FILETYPE_PEM);
		if (ret != 1) {
			MSG_ERROR(msg_module, "Unable to load server's certificate from %s", conf->server_cert_file);
			ERR_print_errors_fp(stderr);
			retval = 1;
			goto out;
		}
	
		/* load private keys into the CTX structure */
		SSL_CTX_use_PrivateKey_file(ctx, conf->server_pkey_file, SSL_FILETYPE_PEM);
		if (ret <= 0) {
			MSG_ERROR(msg_module, "Unable to load server's private key from %s", conf->server_pkey_file);
			ERR_print_errors_fp(stderr);
			retval = 1;
			goto out;
		}

		/* set peer certificate verification parameters */
		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL);
		
		ssl_list = (SSL **) malloc(sizeof(SSL *) * DEFAULT_SIZE_SSL_LIST);
		if (ssl_list == NULL) {
			MSG_ERROR(msg_module, "Memory allocation failed (%s:%d)", __FILE__, __LINE__);
			retval = 1;
			goto out;
		}
		memset(ssl_list, 0, DEFAULT_SIZE_SSL_LIST * sizeof(SSL *));

		conf->ssl_list_size = DEFAULT_SIZE_SSL_LIST;
		conf->ctx = ctx;
		conf->ssl_list = ssl_list;
	}
#endif  /* TLS */

	/* fill in general information */
	conf->info.type = SOURCE_TYPE_TCP;
	conf->info.dst_port = atoi(port);
	if (addrinfo->ai_family == AF_INET) { /* IPv4 */
		conf->info.l3_proto = 4;

		/* copy dst IPv4 address */
		conf->info.dst_addr.ipv4.s_addr =
			((struct sockaddr_in*) addrinfo->ai_addr)->sin_addr.s_addr;

		inet_ntop(AF_INET, &conf->info.dst_addr.ipv4, dst_addr, INET6_ADDRSTRLEN);
	} else { /* IPv6 */
		conf->info.l3_proto = 6;

		/* copy dst IPv6 address */
		int i;
		for (i=0; i<4;i++) {
			conf->info.dst_addr.ipv6.s6_addr32[i] =
				((struct sockaddr_in6*) addrinfo->ai_addr)->sin6_addr.s6_addr32[i];
		}

		inet_ntop(AF_INET6, &conf->info.dst_addr.ipv6, dst_addr, INET6_ADDRSTRLEN);
	}

	/* allocate memory for templates */
	if (convert_init(TCP_PLUGIN, BUFF_LEN) != 0) {
		MSG_ERROR(msg_module, "malloc() for templates failed!");
		retval = 1;
		goto out;
	}

	/* print info */
	MSG_INFO(msg_module, "Input plugin listening on %s, port %s", dst_addr, port);

	/* start listening thread */
	if (pthread_create(&listen_thread, NULL, &input_listen, (void *) conf) != 0) {
		MSG_ERROR(msg_module, "Failed to create listening thread");
		retval = 1;
		goto out;
	}

	/* pass general information to the collector */
	*config = (void*) conf;

	/* normal exit, all OK */
	MSG_INFO(msg_module, "Plugin initialization completed successfully");

out:
	if (def_port == 0 && port != NULL) { /* free when memory was actually allocated*/
		free(port);
	}

	if (address != NULL) {
		free(address);
	}

	if (addrinfo != NULL) {
		freeaddrinfo(addrinfo);
	}

	/* free the xml document */
	if (doc != NULL) {
		xmlFreeDoc(doc);
	}

	/* free the global variables that may have been allocated by the xml parser */
	xmlCleanupParser();

	/* free input_info when error occured */
	if (retval != 0 && conf != NULL) {
		if (conf->info.template_life_time != NULL) {
			free (conf->info.template_life_time);
		}
		if (conf->info.options_template_life_time != NULL) {
			free (conf->info.options_template_life_time);
		}
		if (conf->info.template_life_packet != NULL) {
			free (conf->info.template_life_packet);
		}
		if (conf->info.options_template_life_packet != NULL) {
			free (conf->info.options_template_life_packet);
		}
		free(conf);

	}

#ifdef TLS_SUPPORT
	/* error occurs, clean up */
	if ((retval != 0) && (conf != NULL)) {
		if (ssl_list) {
			free(ssl_list);
		}

		if (ctx) {
			SSL_CTX_free(ctx);
		}
	}
#endif

	return retval;
}
Пример #9
0
void CTrans4::InverseDouble(void) {
    convert_init(FFTL_CONVERT_INIT_BACKWARD_DOUBLE);
    convert(CoWnHeapIQ1d, CoWnHeapIQ2d, CoWnHeapIQ3d, ComplexJd_);    
}   
Пример #10
0
void CTrans4::ForwardDouble(void) {
    convert_init(FFTL_CONVERT_INIT_FORWARD_DOUBLE);
    convert(CoWnHeapQ1d, CoWnHeapQ2d, CoWnHeapQ3d, ComplexJd);    
}
Пример #11
0
void CTrans4::InverseFloat(void) {
    convert_init(FFTL_CONVERT_INIT_BACKWARD_FLOAT);
    convert(CoWnHeapIQ1, CoWnHeapIQ2, CoWnHeapIQ3, ComplexJ_);
}
Пример #12
0
void CTrans4::ForwardFloat(void) {
    convert_init(FFTL_CONVERT_INIT_FORWARD_FLOAT);
    convert(CoWnHeapQ1, CoWnHeapQ2, CoWnHeapQ3, ComplexJ);
}