Esempio n. 1
0
int pkg_src_download_signature(pkg_src_t * src)
{
    int err = 0;
    char *url;
    char *sigfile;
    const char *sigext;

    if (strcmp(opkg_config->signature_type, "gpg-asc") == 0)
        sigext = "asc";
    else
        sigext = "sig";

    sprintf_alloc(&sigfile, "%s/%s.%s", opkg_config->lists_dir, src->name,
                  sigext);

    /* get the url for the sig file */
    if (src->extra_data)        /* debian style? */
        sprintf_alloc(&url, "%s/%s/Packages.%s", src->value, src->extra_data,
                      sigext);
    else
        sprintf_alloc(&url, "%s/Packages.%s", src->value, sigext);

    err = opkg_download(url, sigfile, NULL, NULL);
    if (err) {
        opkg_msg(ERROR, "Failed to download signature for %s.\n", src->name);
        goto cleanup;
    }

    opkg_msg(DEBUG, "Downloaded signature for %s.\n", src->name);

 cleanup:
    free(sigfile);
    free(url);
    return err;
}
Esempio n. 2
0
int pkg_dest_init(pkg_dest_t * dest, const char *name, const char *root_dir)
{
    char *status_file_dir;

    dest->name = xstrdup(name);

    /* Guarantee that dest->root_dir ends with a '/' */
    if (root_dir[strlen(root_dir) - 1] == '/') {
        dest->root_dir = xstrdup(root_dir);
    } else {
        sprintf_alloc(&dest->root_dir, "%s/", root_dir);
    }
    file_mkdir_hier(dest->root_dir, 0755);

    sprintf_alloc(&dest->info_dir, "%s/%s", dest->root_dir,
                  opkg_config->info_dir);
    file_mkdir_hier(dest->info_dir, 0755);

    sprintf_alloc(&dest->status_file_name, "%s/%s", dest->root_dir,
                  opkg_config->status_file);

    /* Ensure that the directory in which we will create the status file exists.
     */
    status_file_dir = xdirname(dest->status_file_name);
    file_mkdir_hier(status_file_dir, 0755);
    free(status_file_dir);

    return 0;
}
Esempio n. 3
0
/*! Write a buffer completely into a file.
 *
 *  If the file already exists, it will be overwritten.
 *
 *  \return
 *      0 on success, -1 on failure
 *
 *  \param error
 *      On failure, \c error will be set to a newly allocated string
 *      that contains the error message.
 *      On success, or when out of memory,
 *      \c error will be set to \c NULL.
 *
 *  \param path
 *      path of the file to write to
 *
 *  \param source
 *      buffer to write
 *
 *  \param source_size
 *      size of \c source
 */
static int write_file(char **error, const char *path, const char *source, size_t source_size)
{
    FILE *file;
    size_t written_size;
    *error = NULL;
    file = fopen(path, "wb");
    if (file == NULL) {
        *error = sprintf_alloc("Unable to open file \"%s\" for writing: %s.",
                               path, strerror(errno));
        goto error_cleanup;
    }
    written_size = fwrite(source, 1, source_size, file);
    if (ferror(file)) {
        *error = sprintf_alloc("Unable to write %lu bytes to file \"%s\": %s.",
                               (unsigned long)source_size, path, strerror(errno));
        goto error_cleanup;
    }
    if (written_size != source_size) {
        *error = sprintf_alloc("Unable to write %lu bytes to file \"%s\": Only %lu bytes were written.",
                               (unsigned long)source_size, path, (unsigned long)written_size);
        goto error_cleanup;
    }
    if (fclose(file) != 0) {
        *error = sprintf_alloc("Unable to close file \"%s\" after writing: %s.",
                               path, strerror(errno));
        file = NULL;
        goto error_cleanup;
    }
    return 0;
error_cleanup:
    if (file != NULL) {
        fclose(file);
    }
    return -1;
}
Esempio n. 4
0
static int
opkg_download_cache(const char *src, const char *dest_file_name,
	curl_progress_func cb, void *data)
{
    char *cache_name = xstrdup(src);
    char *cache_location, *p;
    int err = 0;

    if (!conf->cache || str_starts_with(src, "file:")) {
	err = opkg_download(src, dest_file_name, cb, data, 0);
	goto out1;
    }

    if(!file_is_dir(conf->cache)){
	    opkg_msg(ERROR, "%s is not a directory.\n",
			    conf->cache);
	    err = 1;
	    goto out1;
    }

    for (p = cache_name; *p; p++)
	if (*p == '/')
	    *p = ',';	/* looks nicer than | or # */

    sprintf_alloc(&cache_location, "%s/%s", conf->cache, cache_name);
    if (file_exists(cache_location))
	opkg_msg(NOTICE, "Copying %s.\n", cache_location);
    else {
       /* cache file with funky name not found, try simple name */
        free(cache_name);
        char *filename = strrchr(dest_file_name,'/');
        if (filename)
           cache_name = xstrdup(filename+1); // strip leading '/'
        else
           cache_name = xstrdup(dest_file_name);
        free(cache_location);
        sprintf_alloc(&cache_location, "%s/%s", conf->cache, cache_name);
        if (file_exists(cache_location))
           opkg_msg(NOTICE, "Copying %s.\n", cache_location);
        else  {
 	    err = opkg_download(src, cache_location, cb, data, 0);
	    if (err) {
	       (void) unlink(cache_location);
	       goto out2;
	  }
	}
    }

    err = file_copy(cache_location, dest_file_name);


out2:
    free(cache_location);
out1:
    free(cache_name);
    return err;
}
Esempio n. 5
0
static int set_and_load_pkg_dest_list(ipkg_conf_t *conf, nv_pair_list_t *nv_pair_list, char *lists_dir )
{
     nv_pair_list_elt_t *iter;
     nv_pair_t *nv_pair;
     pkg_dest_t *dest;
     char *root_dir;

     for (iter = nv_pair_list->head; iter; iter = iter->next) {
	  nv_pair = iter->data;

	  if (conf->offline_root) {
	       sprintf_alloc(&root_dir, "%s%s", conf->offline_root, nv_pair->value);
	  } else {
	       root_dir = strdup(nv_pair->value);
	  }
	  dest = pkg_dest_list_append(&conf->pkg_dest_list, nv_pair->name, root_dir, lists_dir, conf);
	  free(root_dir);
	  if (dest == NULL) {
	       continue;
	  }
	  if (conf->default_dest == NULL) {
	       conf->default_dest = dest;
	  }
	  if (file_exists(dest->status_file_name)) {
	       pkg_hash_add_from_file(conf, dest->status_file_name,
				      NULL, dest, 1);
	  }
     }

     return 0;
}
Esempio n. 6
0
static int expect_element_end (
    xmlTextReaderPtr reader,
    char *exp_name)
{
    xmlChar *name;
    /* maybe we are already on the end element ... lets see */
    if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT){
         xmlChar *temp;
         xmlChar *temp2;            
         temp = xmlTextReaderName(reader);
         temp2 = (xmlChar*)sprintf_alloc("/%s", temp);
         name = xmlStrdup(temp2);
         xmlFree(temp);
         free(temp2);            
    } else {     
         name = get_xml_element(reader);
    }

    if (name == NULL)
        return -1;    
    if (xmlStrcasecmp(name+1,(xmlChar *)exp_name) != 0 || name[0] != '/'){
        rrd_set_error("line %d: expected </%s> end element but found <%s>",
                      xmlTextReaderGetParserLineNumber(reader),exp_name,name);
        xmlFree(name);            
        return -1;            
    }
    xmlFree(name);    
    return 0;    
} /* expect_element_end */
Esempio n. 7
0
void * render_loop(void * data)
{
    tinfo_t * tinfo = data;
    state_t * state = tinfo->state;
    char * buffer_name = sprintf_alloc("rot%d", tinfo->id);

    float color[4] = {1.0f, 1.0 - .1f*tinfo->id, .1f*tinfo->id, 1.0f};

    while(state->running) {
        double rad = (tinfo->id*M_PI/5) + (vx_util_mtime() % 2000) * 2* M_PI / 1e3;

        vx_object_t * vo = vxo_chain(vxo_mat_rotate_z(rad),
                                     vxo_mat_translate2(0,10),
                                     vxo_box(vxo_mesh_style(color)));

        vx_buffer_add_back(vx_world_get_buffer(state->world, buffer_name), vo);
        vx_buffer_swap(vx_world_get_buffer(state->world, buffer_name));

        usleep(500);
    }
    printf("Exiting render thread %s\n", buffer_name);
    free(buffer_name);

    return NULL;
}
Esempio n. 8
0
int pkg_extract_control_files_to_dir_with_prefix(pkg_t * pkg, const char *dir,
                                                 const char *prefix)
{
    int r = -1;
    char *dir_with_prefix;
    struct opkg_ar *ar;

    sprintf_alloc(&dir_with_prefix, "%s/%s", dir, prefix);

    ar = ar_open_pkg_control_archive(pkg->local_filename);
    if (!ar) {
        opkg_msg(ERROR, "Failed to extract control.tar.gz from package '%s'.\n",
                 pkg->local_filename);
        goto cleanup;
    }

    r = ar_extract_all(ar, dir_with_prefix);
    if (r < 0)
        opkg_msg(ERROR,
                 "Failed to extract all control files from package '%s'.\n",
                 pkg->local_filename);

 cleanup:
    free(dir_with_prefix);
    if (ar)
        ar_close(ar);
    return r;
}
Esempio n. 9
0
int pkg_src_download(pkg_src_t * src)
{
    int err = 0;
    char *url;
    char *feed;
    const char *url_filename;

    sprintf_alloc(&feed, "%s/%s", opkg_config->lists_dir, src->name);

    url_filename = src->gzip ? "Packages.gz" : "Packages";
    if (src->extra_data)        /* debian style? */
        sprintf_alloc(&url, "%s/%s/%s", src->value, src->extra_data,
                      url_filename);
    else
        sprintf_alloc(&url, "%s/%s", src->value, url_filename);

    if (src->gzip) {
        char *cache_location;

        cache_location = opkg_download_cache(url, NULL, NULL);
        if (!cache_location) {
            err = -1;
            goto cleanup;
        }

        err = file_decompress(cache_location, feed);
        free(cache_location);
        if (err) {
            opkg_msg(ERROR, "Couldn't decompress feed for source %s.",
                     src->name);
            goto cleanup;
        }
    } else {
        err = opkg_download(url, feed, NULL, NULL);
        if (err)
            goto cleanup;
    }

    opkg_msg(DEBUG, "Downloaded package list for %s.\n", src->name);

 cleanup:
    free(feed);
    free(url);
    return err;
}
Esempio n. 10
0
File: conf.c Progetto: idtek/knot
struct sockaddr_storage conf_addr(
	conf_val_t *val,
	const char *sock_base_dir)
{
	assert(val != NULL && val->item != NULL);
	assert(val->item->type == YP_TADDR ||
	       (val->item->type == YP_TREF &&
	        val->item->var.r.ref->var.g.id->type == YP_TADDR));

	struct sockaddr_storage out = { AF_UNSPEC };

	if (val->code == KNOT_EOK) {
		bool no_port;
		conf_val(val);
		out = yp_addr(val->data, &no_port);

		if (out.ss_family == AF_UNIX) {
			// val->data[0] is socket type identifier!
			if (val->data[1] != '/' && sock_base_dir != NULL) {
				char *tmp = sprintf_alloc("%s/%s", sock_base_dir,
				                          val->data + 1);
				val->code = sockaddr_set(&out, AF_UNIX, tmp, 0);
				free(tmp);
			}
		} else if (no_port) {
			sockaddr_port_set(&out, val->item->var.a.dflt_port);
		}
	} else {
		const char *dflt_socket = val->item->var.a.dflt_socket;
		if (dflt_socket != NULL) {
			if (dflt_socket[0] == '/' || sock_base_dir == NULL) {
				val->code = sockaddr_set(&out, AF_UNIX,
				                         dflt_socket, 0);
			} else {
				char *tmp = sprintf_alloc("%s/%s", sock_base_dir,
				                          dflt_socket);
				val->code = sockaddr_set(&out, AF_UNIX, tmp, 0);
				free(tmp);
			}
		}
	}

	return out;
}
Esempio n. 11
0
int pkg_src_verify(pkg_src_t * src)
{
    int err = 0;
    char *feed;
    char *sigfile;
    const char *sigext;

    if (strcmp(opkg_config->signature_type, "gpg-asc") == 0)
        sigext = "asc";
    else
        sigext = "sig";

    sprintf_alloc(&feed, "%s/%s", opkg_config->lists_dir, src->name);
    sprintf_alloc(&sigfile, "%s.%s", feed, sigext);

    if (!file_exists(sigfile)) {
        opkg_msg(ERROR,
                 "Signature file is missing for %s. "
                 "Perhaps you need to run 'opkg update'?\n", src->name);
        err = -1;
        goto cleanup;
    }

    err = opkg_verify_signature(feed, sigfile);
    if (err) {
        opkg_msg(ERROR, "Signature verification failed for %s.\n", src->name);
        goto cleanup;
    }

    opkg_msg(DEBUG, "Signature verification passed for %s.\n", src->name);

 cleanup:
    if (err) {
        /* Remove incorrect files. */
        unlink(feed);
        unlink(sigfile);
    }
    free(sigfile);
    free(feed);
    return err;
}
Esempio n. 12
0
/*
 * Downloads file from url, installs in package database, return package name.
 */
int
opkg_prepare_url_for_install(const char *url, char **namep)
{
     int err = 0;
     pkg_t *pkg;

     pkg = pkg_new();

     if (str_starts_with(url, "http://")
	 || str_starts_with(url, "ftp://")) {
	  char *tmp_file;
	  char *file_basec = xstrdup(url);
	  char *file_base = basename(file_basec);

	  sprintf_alloc(&tmp_file, "%s/%s", conf->tmp_dir, file_base);
	  err = opkg_download(url, tmp_file, NULL, NULL, 0);
	  if (err)
	       return err;

	  err = pkg_init_from_file(pkg, tmp_file);
	  if (err)
	       return err;

	  free(tmp_file);
	  free(file_basec);

     } else if (strcmp(&url[strlen(url) - 4], OPKG_PKG_EXTENSION) == 0
                || strcmp(&url[strlen(url) - 4], IPKG_PKG_EXTENSION) == 0
		|| strcmp(&url[strlen(url) - 4], DPKG_PKG_EXTENSION) == 0) {

	  err = pkg_init_from_file(pkg, url);
	  if (err)
	       return err;
	  opkg_msg(DEBUG2, "Package %s provided by hand (%s).\n",
		  pkg->name, pkg->local_filename);
          pkg->provided_by_hand = 1;

     } else {
       pkg_deinit(pkg);
       free(pkg);
       return 0;
     }

     pkg->dest = conf->default_dest;
     pkg->state_want = SW_INSTALL;
     pkg->state_flag |= SF_PREFER;
     hash_insert_pkg(pkg, 1);

     if (namep) {
	  *namep = pkg->name;
     }
     return 0;
}
Esempio n. 13
0
File: conf.c Progetto: idtek/knot
char* conf_abs_path(
	conf_val_t *val,
	const char *base_dir)
{
	const char *path = conf_str(val);
	if (path == NULL) {
		return NULL;
	} else if (path[0] == '/') {
		return strdup(path);
	} else {
		char *abs_path;
		if (base_dir == NULL) {
			char *cwd = realpath("./", NULL);
			abs_path = sprintf_alloc("%s/%s", cwd, path);
			free(cwd);
		} else {
			abs_path = sprintf_alloc("%s/%s", base_dir, path);
		}
		return abs_path;
	}
}
Esempio n. 14
0
// 実行ファイルのディレクトリに、config.ini(デフォルト)を付加した物になります
// 動的にバッファを格納して返却するので、解放必須です
LPTSTR GetConfigPath(LPTSTR fileName)
{
	LPTSTR lpExecDirectory = (LPTSTR)::GlobalAlloc(GMEM_FIXED, MAX_PATH * sizeof(TCHAR));
	if( ::GetExecuteDirectory(lpExecDirectory, MAX_PATH) ) {
		LPTSTR lpConfigPath = sprintf_alloc(L"%s%s", lpExecDirectory, fileName);
		::GlobalFree(lpExecDirectory);
		return lpConfigPath;
	} else {
		::GlobalFree(lpExecDirectory);
		::ShowLastError();
		return NULL;
	}
}
Esempio n. 15
0
int
opkg_download_pkg(pkg_t *pkg, const char *dir)
{
    int err;
    char *url;
    char *stripped_filename;

    if (pkg->src == NULL) {
	opkg_msg(ERROR, "Package %s is not available from any configured src.\n",
		pkg->name);
	return -1;
    }
    if (pkg->filename == NULL) {
	opkg_msg(ERROR, "Package %s does not have a valid filename field.\n",
		pkg->name);
	return -1;
    }

    sprintf_alloc(&url, "%s/%s", pkg->src->value, pkg->filename);

    /* The pkg->filename might be something like
       "../../foo.opk". While this is correct, and exactly what we
       want to use to construct url above, here we actually need to
       use just the filename part, without any directory. */

    stripped_filename = strrchr(pkg->filename, '/');
    if ( ! stripped_filename )
        stripped_filename = pkg->filename;

    sprintf_alloc(&pkg->local_filename, "%s/%s", dir, stripped_filename);

    err = opkg_download_cache(url, pkg->local_filename, NULL, NULL);
    free(url);

    return err;
}
Esempio n. 16
0
static void movie(state_t * state, vx_code_input_stream_t * cins, int record)
{
    if (record) {
        if (state->movie_file != NULL) {
            printf("WRN: Only one movie can be recorded at a time\n");
            return;
        }

        uint64_t mtime = vx_mtime();
        time_t now  = time(NULL);
        struct tm * now2 = localtime(&now);

        pthread_mutex_lock(&state->movie_mutex);
        if (vx_code_input_stream_available(cins) > 0) {
            const char * f2 = cins->read_str(cins);
            state->movie_file = strdup(f2);
        } else { // generate a unique ID
            state->movie_file = sprintf_alloc("m%4d%02d%02d_%02d%02d%02d_%03d.ppms.gz",
                                     now2->tm_year + 1900,
                                     now2->tm_mon + 1,
                                     now2->tm_mday,
                                     now2->tm_hour,
                                     now2->tm_min,
                                     now2->tm_sec,
                                     (int)(mtime%1000));
        }
        pthread_cond_signal(&state->movie_cond);

        pthread_mutex_unlock(&state->movie_mutex);

    } else { // finish recording
        if (state->movie_file == NULL) {
            printf("WRN: Can't stop recording a movie: none in progress\n");
            return;
        }


        pthread_mutex_lock(&state->movie_mutex);
        {
            state->movie_file = NULL;
            pthread_cond_signal(&state->movie_cond);
        }
        pthread_mutex_unlock(&state->movie_mutex);

    }
}
Esempio n. 17
0
char *harmony_setcfg(hdesc_t *hdesc, const char *key, const char *val)
{
    char *buf;
    int retval;

    if (hdesc->state < HARMONY_STATE_CONNECTED) {
        /* User must be preparing for a new session since we're not
         * connected yet.  Store the key/value pair in a local cache.
         */
        buf = stralloc( hcfg_get(hdesc->sess.cfg, key) );
        hcfg_set(hdesc->sess.cfg, key, val);
        return buf;
    }

    if (!key) {
        hdesc->errstr = "Invalid key string.";
        errno = EINVAL;
        return NULL;
    }

    buf = sprintf_alloc("%s=%s", key, val ? val : "");
    if (!buf) {
        hdesc->errstr = "Internal memory allocation error.";
        return NULL;
    }

    /* Prepare a Harmony message. */
    hmesg_scrub(&hdesc->mesg);
    hdesc->mesg.data.string = buf;

    retval = send_request(hdesc, HMESG_SETCFG);
    free(buf);

    if (retval < 0)
        return NULL;

    if (hdesc->mesg.status != HMESG_STATUS_OK) {
        hdesc->errstr = "Invalid message received from server.";
        errno = EINVAL;
        return NULL;
    }

    /* It is the user's responsibility to free this memory. */
    return stralloc(hdesc->mesg.data.string);
}
Esempio n. 18
0
int pkg_dest_init(pkg_dest_t *dest, const char *name, const char *root_dir,const char * lists_dir, ipkg_conf_t *conf)
{
    dest->name = strdup(name);

    /* Guarantee that dest->root_dir ends with a '/' */
    if (str_ends_with(root_dir, "/")) {
	dest->root_dir = strdup(root_dir);
    } else {
	sprintf_alloc(&dest->root_dir, "%s/", root_dir);
    }
    file_mkdir_hier(dest->root_dir, 0755);

    if (!conf->ipkg_libdir) {
	    sprintf_alloc(&dest->ipkg_dir, "%s%s",
			  dest->root_dir, IPKG_STATE_DIR_PREFIX);
    }else{
	    sprintf_alloc(&dest->ipkg_dir, "%s%s",
			  dest->root_dir, conf->ipkg_libdir);
    }
    file_mkdir_hier(dest->ipkg_dir, 0755);

    if (str_starts_with (lists_dir, "/")) 
        sprintf_alloc(&dest->lists_dir, "%s", lists_dir);
    else
        sprintf_alloc(&dest->lists_dir, "/%s", lists_dir);

    file_mkdir_hier(dest->lists_dir, 0755);

    sprintf_alloc(&dest->info_dir, "%s/%s",
		  dest->ipkg_dir, IPKG_INFO_DIR_SUFFIX);
    file_mkdir_hier(dest->info_dir, 0755);

    sprintf_alloc(&dest->status_file_name, "%s/%s",
		  dest->ipkg_dir, IPKG_STATUS_FILE_SUFFIX);

    sprintf_alloc(&dest->status_file_tmp_name, "%s/%s.tmp",
		  dest->ipkg_dir, IPKG_STATUS_FILE_SUFFIX);

    dest->status_file = NULL;

    return 0;
}
Esempio n. 19
0
/*! Remove a directory recursively like <tt>rm -r</tt>.
 *
 *  \return
 *      0 on success, -1 on failure
 *
 *  \param error
 *      On failure, \c error will be set to a newly allocated string
 *      that contains the error message.
 *      On success, or when out of memory,
 *      \c error will be set to \c NULL.
 *
 *  \param dirname
 *      the directory to remove
 */
static int remove_directory_recursively(char **error, const char *dirname)
{
    DIR *dir;
    struct dirent *entry;
    /* continue on errors and report only the first error that occured */
    *error = NULL;
    dir = opendir(dirname);
    if (dir == NULL && *error == NULL) {
        *error = sprintf_alloc("Unable to read directory entries of \"%s\": %s.",
                               dirname, strerror(errno));
    } else {
        for (entry = readdir(dir); entry != NULL; entry = readdir(dir)) {
            char *name;
            if (   strcmp(entry->d_name, ".") == 0
                || strcmp(entry->d_name, "..") == 0) {
                continue;
            }
            name = sprintf_alloc("%s/%s", dirname, entry->d_name);
            if (name == NULL && *error == NULL) {
                *error = sprintf_alloc("Out of memory.");
                continue;
            }
            if (entry->d_type == DT_DIR) {
                char *sub_error;
                if (remove_directory_recursively(&sub_error, name) != 0 && *error == NULL) {
                    *error = sub_error;
                }
            } else {
                if (unlink(name) != 0 && *error == NULL) {
                    *error = sprintf_alloc("Unable to remove file \"%s\": %s.",
                                           name, strerror(errno));
                }
            }
            free(name);
        }
        if (closedir(dir) != 0 && *error == NULL) {
            *error = sprintf_alloc("Unable to close directory \"%s\": %s.",
                                   dirname, strerror(errno));
        }
    }
    if (rmdir(dirname) != 0) {
        if (*error == NULL) {
            *error = sprintf_alloc("Unable to remove directory \"%s\": %s.",
                                   dirname, strerror(errno));
        }
        return -1;
    }
    /* all previous errors are irrelevant because rmdir() was successful */
    *error = NULL;
    return 0;
}
Esempio n. 20
0
static int parse_rdata(struct entry *entry, const char *owner, const char *rrtype, const char *rdata,
		       int ttl, knot_mm_t *mm)
{
	knot_rdataset_init(&entry->data.rrs);
	int ret = knot_rrtype_from_string(rrtype, &entry->data.type);
	if (ret != KNOT_EOK) {
		return ret;
	}

	/* Synthetize RR line */
	char *rr_line = sprintf_alloc("%s %u IN %s %s\n", owner, ttl, rrtype, rdata);
	if (zs_set_input_string(g_scanner, rr_line, strlen(rr_line)) != 0 ||
	    zs_parse_all(g_scanner) != 0) {
		free(rr_line);
		return KNOT_EPARSEFAIL;
	}
	free(rr_line);

	/* Write parsed RDATA. */
	knot_rdata_t rr[knot_rdata_array_size(g_scanner->r_data_length)];
	knot_rdata_init(rr, g_scanner->r_data_length, g_scanner->r_data, ttl);
	return knot_rdataset_add(&entry->data.rrs, rr, mm);
}
Esempio n. 21
0
void remove_maintainer_scripts(pkg_t * pkg)
{
    unsigned int i;
    int err;
    char *globpattern;
    glob_t globbuf;

    if (opkg_config->noaction)
        return;

    sprintf_alloc(&globpattern, "%s/%s.*", pkg->dest->info_dir, pkg->name);

    err = glob(globpattern, 0, NULL, &globbuf);
    free(globpattern);
    if (err)
        return;

    for (i = 0; i < globbuf.gl_pathc; i++) {
        opkg_msg(INFO, "Deleting %s.\n", globbuf.gl_pathv[i]);
        unlink(globbuf.gl_pathv[i]);
    }
    globfree(&globbuf);
}
Esempio n. 22
0
static int parse_rdata(struct entry *entry, const char *owner, const char *rrtype, const char *rdata,
		       int ttl, mm_ctx_t *mm)
{
	knot_rdataset_init(&entry->data.rrs);
	int ret = knot_rrtype_from_string(rrtype, &entry->data.type);
	if (ret != KNOT_EOK) {
		return ret;
	}

	/* Synthetize RR line */
	char *rr_line = sprintf_alloc("%s %u IN %s %s\n", owner, ttl, rrtype, rdata);
	ret = zs_scanner_parse(g_scanner, rr_line, rr_line + strlen(rr_line), true);
	free(rr_line);

	/* Write parsed RDATA. */
	if (ret == KNOT_EOK) {
		knot_rdata_t rr[knot_rdata_array_size(g_scanner->r_data_length)];
		knot_rdata_init(rr, g_scanner->r_data_length, g_scanner->r_data, ttl);
		ret = knot_rdataset_add(&entry->data.rrs, rr, mm);
	}

	return ret;
}
Esempio n. 23
0
static void screen_shot(state_t * state, vx_code_input_stream_t * cins)
{
    char * filename = NULL;
    if (vx_code_input_stream_available(cins) > 0) {
        const char * f2 = cins->read_str(cins);
        filename = strdup(f2);
    } else { // generate a unique ID

        uint64_t mtime = vx_mtime();
        time_t now  = time(NULL);
        struct tm * now2 = localtime(&now);

        filename=sprintf_alloc("p%4d%02d%02d_%02d%02d%02d_%03d.png",
                               now2->tm_year + 1900,
                               now2->tm_mon + 1,
                               now2->tm_mday,
                               now2->tm_hour,
                               now2->tm_min,
                               now2->tm_sec,
                               (int)(mtime % 1000));
    }


    int last_idx = (state->cur_pb_idx + 1) % 2;

    GdkPixbuf * pb = state->pixbufs[last_idx];

    if (pb == NULL)
        return;

    GError * err = NULL;
    gdk_pixbuf_save(pb,filename, "png", & err, NULL);

    printf("Saved screenshot to %s\n", filename);
    free(filename);

}
Esempio n. 24
0
/* Join left and right path components without intervening '/' as left may end
 * with a prefix to be applied to the names of extracted files.
 *
 * The right path component is stripped of leading '/' or './' components. If
 * the right path component is simply '.' after stripping, it should not be
 * created.
 *
 * Returns the joined path, or NULL if the resulting path should not be created.
 */
static char *join_paths(const char *left, const char *right)
{
    char *path;

    /* Skip leading '/' or './' in right-hand path if present. */
    while (right[0] == '.' && right[1] == '/')
        right += 2;
    while (right[0] == '/')
        right++;

    /* Don't create '.' directory. */
    if (right[0] == '.' && right[1] == '\0')
        return NULL;

    /* Don't extract empty paths. */
    if (right[0] == '\0')
        return NULL;

    if (!left)
        return xstrdup(right);

    sprintf_alloc(&path, "%s%s", left, right);
    return path;
}
Esempio n. 25
0
static int set_and_load_pkg_src_list(ipkg_conf_t *conf, pkg_src_list_t *pkg_src_list)
{
     pkg_src_list_elt_t *iter;
     pkg_src_t *src;
     char *list_file;

     for (iter = pkg_src_list->head; iter; iter = iter->next) {
          src = iter->data;
	  if (src == NULL) {
	       continue;
	  }

	  sprintf_alloc(&list_file, "%s/%s", 
			  conf->restrict_to_default_dest ? conf->default_dest->lists_dir : conf->lists_dir, 
			  src->name);

	  if (file_exists(list_file)) {
	       pkg_hash_add_from_file(conf, list_file, src, NULL, 0);
	  }
	  free(list_file);
     }

     return 0;
}
Esempio n. 26
0
/* dept -1 causes depth to be ignored */
static xmlChar* get_xml_element (
    xmlTextReaderPtr reader
    )
{
    int rc;
    while((rc = xmlTextReaderRead(reader)) == 1){
        int type;
        xmlChar *name;
        type = xmlTextReaderNodeType(reader);
        if (type == XML_READER_TYPE_TEXT){
            xmlChar *value;
            value = xmlTextReaderValue(reader);
            rrd_set_error("line %d: expected element but found text '%s'",
                          xmlTextReaderGetParserLineNumber(reader),value);
            xmlFree(value);
            return NULL;
        }
        /* skip all other non-elements */
        if (type != XML_READER_TYPE_ELEMENT && type != XML_READER_TYPE_END_ELEMENT)
            continue;

        name = xmlTextReaderName(reader);
        if (type == XML_READER_TYPE_END_ELEMENT){
            xmlChar *temp;
            xmlChar *temp2;            
            temp = (xmlChar*)sprintf_alloc("/%s",name);
            temp2 = xmlStrdup(temp);
            free(temp);
            xmlFree(name);            
            return temp2;            
        }
        /* all seems well, return the happy news */
        return name;
    }
    if (rc == 0) {
	rrd_set_error("the xml ended while we were looking for an element");
    } else {
	xmlErrorPtr err = xmlGetLastError();
	/* argh: err->message often contains \n at the end. This is not 
	   what we want: Bite the bullet by copying the message, replacing any 
	   \n, constructing the rrd error message and freeing the temp. buffer.
	*/
	char *msgcpy = NULL, *c;
	if (err != NULL && err->message != NULL) {
	    msgcpy = strdup(err->message);
	    if (msgcpy != NULL) {
		for (c = msgcpy ; *c ; c++) {
		    if (*c == '\n') *c = ' ';
		}
		/* strip whitespace from end of message */
		for (c-- ; c != msgcpy ; c--) {
		    if (!isprint(*c)) {
			*c = 0;
		    }
		}
	    } else {
		/* out of memory during error handling, hmmmm */
	    }
	}

	rrd_set_error("error reading/parsing XML: %s", 
		      msgcpy != NULL ? msgcpy : "?");
	if (msgcpy) free(msgcpy);
    }
    return NULL;
} /* get_xml_element */
Esempio n. 27
0
/*! Convert a TeX or LaTeX source to DVI or PDF.
 */
void texcaller_convert(char **result, size_t *result_size, char **info, const char *source, size_t source_size, const char *source_format, const char *result_format, int max_runs)
{
    char *error;
    const char *cmd;
    const char *tmpdir;
    char *dir = NULL;
    char *dir_template = NULL;
    char *source_filename = NULL;
    char *aux_filename = NULL;
    char *log_filename = NULL;
    char *result_filename = NULL;
    char *aux = NULL;
    size_t aux_size = 0;
    char *aux_old = NULL;
    size_t aux_old_size = 0;
    int runs;
    *result = NULL;
    *result_size = 0;
    *info = NULL;
    /* check arguments */
    if        (strcmp(source_format, "TeX") == 0 && strcmp(result_format, "DVI") == 0) {
        cmd = "tex";
    } else if (strcmp(source_format, "TeX") == 0 && strcmp(result_format, "PDF") == 0) {
        cmd = "pdftex";
    } else if (strcmp(source_format, "LaTeX") == 0 && strcmp(result_format, "DVI") == 0) {
        cmd = "latex";
    } else if (strcmp(source_format, "LaTeX") == 0 && strcmp(result_format, "PDF") == 0) {
        cmd = "pdflatex";
    } else {
        *info = sprintf_alloc("Unable to convert from \"%s\" to \"%s\".",
                              source_format, result_format);
        goto cleanup;
    }
    if (max_runs < 2) {
        *info = sprintf_alloc("Argument max_runs is %i, but must be >= 2.",
                              max_runs);
        goto cleanup;
    }
    /* create temporary directory */
    tmpdir = getenv("TMPDIR");
    if (tmpdir == NULL || strcmp(tmpdir, "") == 0) {
        tmpdir = "/tmp";
    }
    dir_template = sprintf_alloc("%s/texcaller-temp-XXXXXX", tmpdir);
    if (dir_template == NULL) {
        goto cleanup;
    }
    dir = mkdtemp(dir_template);
    if (dir == NULL) {
        *info = sprintf_alloc("Unable to create temporary directory from template \"%s\": %s.",
                              dir_template, strerror(errno));
        goto cleanup;
    }
    source_filename = sprintf_alloc("%s/texput.tex", dir);
    if (source_filename == NULL) {
        goto cleanup;
    }
    aux_filename = sprintf_alloc("%s/texput.aux", dir);
    if (aux_filename == NULL) {
        goto cleanup;
    }
    log_filename = sprintf_alloc("%s/texput.log", dir);
    if (log_filename == NULL) {
        goto cleanup;
    }
    if (strcmp(result_format, "DVI") == 0) {
        result_filename = sprintf_alloc("%s/texput.dvi", dir);
    } else {
        result_filename = sprintf_alloc("%s/texput.pdf", dir);
    }
    if (result_filename == NULL) {
        goto cleanup;
    }
    /* create source file */
    if (write_file(&error, source_filename, source, source_size) != 0) {
        *info = error;
        goto cleanup;
    }
    /* run command as often as necessary */
    for (runs = 1; runs <= max_runs; runs++) {
        pid_t pid;
        pid = fork();
        if (pid == -1) {
            *info = sprintf_alloc("Unable to fork child process: %s.",
                                  strerror(errno));
            goto cleanup;
        }
        /* child process */
        if (pid == 0) {
            /* run command within the temporary directory */
            if (chdir(dir) != 0) {
                exit(1);
            }
            /* prevent access to stdin, stdout and stderr */
            fclose(stdin);
            fclose(stdout);
            fclose(stderr);
            /* execute command */
            execlp(cmd,
                   cmd,
                   "-interaction=batchmode",
                   "-halt-on-error",
                   "-file-line-error",
                   "-no-shell-escape",
                   "texput.tex",
                   NULL);
        }
        /* wait for child process */
        for (;;) {
            int status;
            pid_t wpid = waitpid(pid, &status, 0);
            if (wpid == -1) {
                *info = sprintf_alloc("Unable to wait for child process: %s.",
                                      strerror(errno));
                goto cleanup;
            }
            if (WIFSIGNALED(status)) {
                *info = sprintf_alloc("Command \"%s\" was terminated by signal %i.",
                                      cmd, (int)WTERMSIG(status));
                goto cleanup;
            }
            if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
                *info = sprintf_alloc("Command \"%s\" terminated with exit status %i.",
                                      cmd, (int)WEXITSTATUS(status));
                goto cleanup;
            }
            if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
                break;
            }
        }
        /* read new aux file, saving old one */
        free(aux_old);
        aux_old      = aux;
        aux_old_size = aux_size;
        read_file(&aux, &aux_size, &error, aux_filename);
        /* tolerate missing aux file */
        free(error);
        /* check whether aux file stabilized,
           which is also true if there isn't and wasn't any aux file */
        if (aux_size == aux_old_size && memcmp(aux, aux_old, aux_size) == 0) {
            read_file(result, result_size, &error, result_filename);
            if (*result == NULL) {
                *info = error;
                goto cleanup;
            }
            *info = sprintf_alloc("Generated %s (%lu bytes)"
                                  " from %s (%lu bytes) after %i runs.",
                                  result_format, (unsigned long)*result_size,
                                  source_format, (unsigned long)source_size, runs);
            goto cleanup;
        }
    }
    /* aux file didn't stabilize */
    *info = sprintf_alloc("Output didn't stabilize after %i runs.",
                          max_runs);
    goto cleanup;
    /* cleanup all used resources */
cleanup:
    if (log_filename != NULL) {
        char *log;
        size_t log_size;
        read_file(&log, &log_size, &error, log_filename);
        free(error);
        if (log != NULL) {
            if (*info == NULL) {
                *info = log;
            } else {
                char *info_old = *info;
                *info = sprintf_alloc("%s\n\n%s", info_old, log);
                free(info_old);
                free(log);
            }
        }
    }
    if (dir != NULL && remove_directory_recursively(&error, dir) != 0) {
        free(*result);
        *result = NULL;
        *result_size = 0;
        free(*info);
        *info = error;
    }
    free(dir_template);
    free(source_filename);
    free(aux_filename);
    free(log_filename);
    free(result_filename);
    free(aux);
    free(aux_old);
}
Esempio n. 28
0
/*! Read a file completely into a buffer that can be used as a string.
 *
 *  \param result
 *      will be set to a newly allocated buffer that contains
 *      the complete content of the file,
 *      with a \c '\\0' added to the end.
 *      If an error occured,
 *      \c result will be set to \c NULL.
 *
 *  \param result_size
 *      will be set to the size of \c result,
 *      not counting the added \c '\\0'.
 *      If an error occured,
 *      \c result_size will be set to \c 0.
 *
 *  \param error
 *      On failure, \c error will be set to a newly allocated string
 *      that contains the error message.
 *      On success, or when out of memory,
 *      \c error will be set to \c NULL.
 *
 *  \param path
 *      path of the file to read
 */
static void read_file(char **result, size_t *result_size, char **error, const char *path)
{
    FILE *file;
    long file_size;
    size_t read_size;
    *result = NULL;
    *error = NULL;
    file = fopen(path, "rb");
    if (file == NULL) {
        *error = sprintf_alloc("Unable to open file \"%s\" for reading: %s.",
                               path, strerror(errno));
        goto error_cleanup;
    }
    if (fseek(file, 0, SEEK_END) != 0) {
        *error = sprintf_alloc("Unable to seek to end of file \"%s\": %s.",
                               path, strerror(errno));
        goto error_cleanup;
    }
    file_size = ftell(file);
    if (file_size == -1) {
        *error = sprintf_alloc("Unable to obtain size of file \"%s\": %s.",
                               path, strerror(errno));
        goto error_cleanup;
    }
    *result_size = file_size;
    if (fseek(file, 0, SEEK_SET) != 0) {
        *error = sprintf_alloc("Unable to seek back to start of file \"%s\": %s.",
                               path, strerror(errno));
        goto error_cleanup;
    }
    *result = (char *)malloc(*result_size + 1);
    if (*result == NULL) {
        *error = sprintf_alloc("Unable to allocate buffer for reading file \"%s\": %s.",
                               path, strerror(errno));
        goto error_cleanup;
    }
    (*result)[*result_size] = '\0';
    read_size = fread(*result, 1, *result_size, file);
    if (ferror(file)) {
        *error = sprintf_alloc("Unable to read %lu bytes from file \"%s\": %s.",
                               (unsigned long)*result_size, path, strerror(errno));
        goto error_cleanup;
    }
    if (read_size != *result_size) {
        *error = sprintf_alloc("Unable to read %lu bytes from file \"%s\": Got only %lu bytes.",
                               (unsigned long)*result_size, path, (unsigned long)read_size);
        goto error_cleanup;
    }
    if (fclose(file) != 0) {
        *error = sprintf_alloc("Unable to close file \"%s\" after reading: %s.",
                               path, strerror(errno));
        file = NULL;
        goto error_cleanup;
    }
    return;
error_cleanup:
    free(*result);
    *result = NULL;
    *result_size = 0;
    if (file != NULL) {
        fclose(file);
    }
}
Esempio n. 29
0
int rrd_graph_xport(image_desc_t *im) {
  /* prepare the data for processing */
  unsigned long col_cnt=0;
  time_t start=im->start;
  time_t end=im->end;
  unsigned long step=im->step;
  char **legend_v=NULL;
  rrd_value_t *data=NULL;
  /* initialize buffer */
  stringbuffer_t buffer={0,0,NULL,NULL};

  /* check if we have a supported ggraph format */
  switch (im->graph_type) {
    /* allow the following to pass */
  case GTYPE_TIME:
  case GTYPE_XY:
    break;
  default:
    rrd_set_error("Not supported graph type");
    return -1;
  }

  /* if we write a file, then open it */
  if (im->graphfile) {
    buffer.file=fopen(im->graphfile,"w");
  }

  /* do the data processing */
  if (rrd_xport_fn(im,&start,&end,&step,&col_cnt,&legend_v,&data,1)) { return -1;}

  /* fill in some data */
  rrd_infoval_t info;
  info.u_cnt = start;
  grinfo_push(im, sprintf_alloc("graph_start"), RD_I_CNT, info);
  info.u_cnt = end;
  grinfo_push(im, sprintf_alloc("graph_end"), RD_I_CNT, info);
  info.u_cnt = step;
  grinfo_push(im, sprintf_alloc("graph_step"), RD_I_CNT, info);

  /* set locale */

  /* format it for output */
  int r=0;
  switch(im->imgformat) {
  case IF_XML:
    r=rrd_xport_format_xmljson(2,&buffer,im, start, end, step, col_cnt, legend_v, data);
    break;
  case IF_XMLENUM:
    r=rrd_xport_format_xmljson(6,&buffer,im, start, end, step, col_cnt, legend_v, data);
    break;
  case IF_JSON:
    r=rrd_xport_format_xmljson(1,&buffer,im, start, end, step, col_cnt, legend_v, data);
    break;
  case IF_JSONTIME:
    r=rrd_xport_format_xmljson(3,&buffer,im, start, end, step, col_cnt, legend_v, data);
    break;
  case IF_CSV:
    r=rrd_xport_format_sv(',',&buffer,im, start, end, step, col_cnt, legend_v, data);
    break;
  case IF_TSV:
    r=rrd_xport_format_sv('\t',&buffer,im, start, end, step, col_cnt, legend_v, data);
    break;
  case IF_SSV:
    r=rrd_xport_format_sv(';',&buffer,im, start, end, step, col_cnt, legend_v, data);
    break;
  default:
    break;
  }
  /* handle errors */
  if (r) {
    /* free legend */
    for (unsigned long j = 0; j < col_cnt; j++) {
      free(legend_v[j]);
    }
    free(legend_v);
    /* free data */
    free(data);
    /* free the buffer */
    if (buffer.data) {free(buffer.data);}
    /* close the file */
    if (buffer.file) {fclose(buffer.file);}
    /* and return with error */
    return r;
  }

  /* now do the cleanup */
  if (buffer.file) {
    fclose(buffer.file); buffer.file=NULL;
    im->rendered_image_size=0;
    im->rendered_image=NULL;
  } else {
    im->rendered_image_size=buffer.len;
    im->rendered_image=buffer.data;
  }

  /* and print stuff */
  return print_calc(im);
}
Esempio n. 30
0
int
opkg_download(const char *src, const char *dest_file_name,
	curl_progress_func cb, void *data, const short hide_error)
{
    int err = 0;

    char *src_basec = xstrdup(src);
    char *src_base = basename(src_basec);
    char *tmp_file_location;

    opkg_msg(NOTICE,"Downloading %s.\n", src);

    if (str_starts_with(src, "file:")) {
	const char *file_src = src + 5;
	opkg_msg(INFO, "Copying %s to %s...", file_src, dest_file_name);
	err = file_copy(file_src, dest_file_name);
	opkg_msg(INFO, "Done.\n");
        free(src_basec);
	return err;
    }

    sprintf_alloc(&tmp_file_location, "%s/%s", conf->tmp_dir, src_base);
    free(src_basec);
    err = unlink(tmp_file_location);
    if (err && errno != ENOENT) {
	opkg_perror(ERROR, "Failed to unlink %s", tmp_file_location);
	free(tmp_file_location);
	return -1;
    }

    if (conf->http_proxy) {
	opkg_msg(DEBUG, "Setting environment variable: http_proxy = %s.\n",
		conf->http_proxy);
	setenv("http_proxy", conf->http_proxy, 1);
    }
    if (conf->ftp_proxy) {
	opkg_msg(DEBUG, "Setting environment variable: ftp_proxy = %s.\n",
		conf->ftp_proxy);
	setenv("ftp_proxy", conf->ftp_proxy, 1);
    }
    if (conf->no_proxy) {
	opkg_msg(DEBUG,"Setting environment variable: no_proxy = %s.\n",
		conf->no_proxy);
	setenv("no_proxy", conf->no_proxy, 1);
    }

#ifdef HAVE_CURL
    CURLcode res;
    FILE * file = fopen (tmp_file_location, "w");

    curl = opkg_curl_init (cb, data);
    if (curl)
    {
	curl_easy_setopt (curl, CURLOPT_URL, src);
	curl_easy_setopt (curl, CURLOPT_WRITEDATA, file);

	res = curl_easy_perform (curl);
	fclose (file);
	if (res)
	{
	    long error_code;
	    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &error_code);
	    opkg_msg(hide_error?DEBUG2:ERROR, "Failed to download %s: %s.\n",
		    src, curl_easy_strerror(res));
	    free(tmp_file_location);
	    return -1;
	}

    }
    else
    {
	free(tmp_file_location);
	return -1;
    }
#else
    {
      int res;
      const char *argv[8];
      int i = 0;

      argv[i++] = "wget";
      argv[i++] = "-q";
      if (conf->http_proxy || conf->ftp_proxy) {
	argv[i++] = "-Y";
	argv[i++] = "on";
      }
      argv[i++] = "-O";
      argv[i++] = tmp_file_location;
      argv[i++] = src;
      argv[i++] = NULL;
      res = xsystem(argv);

      if (res) {
	opkg_msg(ERROR, "Failed to download %s, wget returned %d.\n", src, res);
	free(tmp_file_location);
	return -1;
      }
    }
#endif

    err = file_move(tmp_file_location, dest_file_name);

    free(tmp_file_location);

    return err;
}