Ejemplo n.º 1
0
static gint
fuzzy_parse_rule (struct rspamd_config *cfg, const ucl_object_t *obj, gint cb_id)
{
	const ucl_object_t *value, *cur;
	struct fuzzy_rule *rule;
	ucl_object_iter_t it = NULL;
	const char *k = NULL;

	if (obj->type != UCL_OBJECT) {
		msg_err_config ("invalid rule definition");
		return -1;
	}

	rule = fuzzy_rule_new (fuzzy_module_ctx->default_symbol,
			fuzzy_module_ctx->fuzzy_pool);

	if ((value = ucl_object_find_key (obj, "mime_types")) != NULL) {
		it = NULL;
		while ((cur = ucl_iterate_object (value, &it, value->type == UCL_ARRAY))
				!= NULL) {
			rule->mime_types = g_list_concat (rule->mime_types,
					parse_mime_types (ucl_obj_tostring (cur)));
		}
	}

	if (rule->mime_types != NULL) {
		rspamd_mempool_add_destructor (fuzzy_module_ctx->fuzzy_pool,
			(rspamd_mempool_destruct_t)g_list_free, rule->mime_types);
	}

	if ((value = ucl_object_find_key (obj, "max_score")) != NULL) {
		rule->max_score = ucl_obj_todouble (value);
	}
	if ((value = ucl_object_find_key (obj,  "symbol")) != NULL) {
		rule->symbol = ucl_obj_tostring (value);
	}
	if ((value = ucl_object_find_key (obj, "read_only")) != NULL) {
		rule->read_only = ucl_obj_toboolean (value);
	}
	if ((value = ucl_object_find_key (obj, "skip_unknown")) != NULL) {
		rule->skip_unknown = ucl_obj_toboolean (value);
	}

	if ((value = ucl_object_find_key (obj, "servers")) != NULL) {
		rule->servers = rspamd_upstreams_create ();
		rspamd_mempool_add_destructor (fuzzy_module_ctx->fuzzy_pool,
				(rspamd_mempool_destruct_t)rspamd_upstreams_destroy,
				rule->servers);
		rspamd_upstreams_from_ucl (rule->servers, value, DEFAULT_PORT, NULL);
	}
	if ((value = ucl_object_find_key (obj, "fuzzy_map")) != NULL) {
		it = NULL;
		while ((cur = ucl_iterate_object (value, &it, true)) != NULL) {
			parse_flags (rule, cfg, cur, cb_id);
		}
	}

	if ((value = ucl_object_find_key (obj, "encryption_key")) != NULL) {
		/* Create key from user's input */
		k = ucl_object_tostring (value);
		if (k == NULL || (rule->peer_key =
					rspamd_http_connection_make_peer_key (k)) == NULL) {
			msg_err_config ("bad encryption key value: %s",
					k);
			return -1;
		}

		rule->local_key = rspamd_http_connection_gen_key ();
	}

	if ((value = ucl_object_find_key (obj, "fuzzy_key")) != NULL) {
		/* Create key from user's input */
		k = ucl_object_tostring (value);
	}

	/* Setup keys */
	if (k == NULL) {
		/* Use some default key for all ops */
		k = "rspamd";
	}
	rule->hash_key = g_string_sized_new (BLAKE2B_KEYBYTES);
	blake2 (rule->hash_key->str, k, NULL, BLAKE2B_KEYBYTES, strlen (k), 0);
	rule->hash_key->len = BLAKE2B_KEYBYTES;

	if ((value = ucl_object_find_key (obj, "fuzzy_shingles_key")) != NULL) {
		k = ucl_object_tostring (value);
	}
	if (k == NULL) {
		k = "rspamd";
	}
	rule->shingles_key = g_string_sized_new (16);
	blake2 (rule->shingles_key->str, k, NULL, 16, strlen (k), 0);
	rule->shingles_key->len = 16;

	if (rspamd_upstreams_count (rule->servers) == 0) {
		msg_err_config ("no servers defined for fuzzy rule with symbol: %s",
			rule->symbol);
		return -1;
	}
	else {
		fuzzy_module_ctx->fuzzy_rules = g_list_prepend (
			fuzzy_module_ctx->fuzzy_rules,
			rule);
		if (rule->symbol != fuzzy_module_ctx->default_symbol) {
			rspamd_symbols_cache_add_symbol (cfg->cache, rule->symbol,
					0,
					NULL, NULL,
					SYMBOL_TYPE_VIRTUAL|SYMBOL_TYPE_FINE,
					cb_id);
		}
	}

	rspamd_mempool_add_destructor (fuzzy_module_ctx->fuzzy_pool, fuzzy_free_rule,
			rule);

	return 0;
}
Ejemplo n.º 2
0
static char *
filename_completion_function (const char *text, int state, input_complete_t flags)
{
    static DIR *directory = NULL;
    static char *filename = NULL;
    static char *dirname = NULL;
    static char *users_dirname = NULL;
    static size_t filename_len;
    int isdir = 1, isexec = 0;
    static vfs_path_t *dirname_vpath = NULL;

    struct dirent *entry = NULL;

    SHOW_C_CTX ("filename_completion_function");

    if (text && (flags & INPUT_COMPLETE_SHELL_ESC))
    {
        char *u_text;
        char *result;
        char *e_result;

        u_text = strutils_shell_unescape (text);

        result = filename_completion_function (u_text, state, flags & (~INPUT_COMPLETE_SHELL_ESC));
        g_free (u_text);

        e_result = strutils_shell_escape (result);
        g_free (result);

        return e_result;
    }

    /* If we're starting the match process, initialize us a bit. */
    if (state == 0)
    {
        const char *temp;

        g_free (dirname);
        g_free (filename);
        g_free (users_dirname);
        vfs_path_free (dirname_vpath);

        if ((*text != '\0') && (temp = strrchr (text, PATH_SEP)) != NULL)
        {
            filename = g_strdup (++temp);
            dirname = g_strndup (text, temp - text);
        }
        else
        {
            dirname = g_strdup (".");
            filename = g_strdup (text);
        }

        /* We aren't done yet.  We also support the "~user" syntax. */

        /* Save the version of the directory that the user typed. */
        users_dirname = dirname;
        dirname = tilde_expand (dirname);
        canonicalize_pathname (dirname);
        dirname_vpath = vfs_path_from_str (dirname);

        /* Here we should do something with variable expansion
           and `command`.
           Maybe a dream - UNIMPLEMENTED yet. */

        directory = mc_opendir (dirname_vpath);
        filename_len = strlen (filename);
    }

    /* Now that we have some state, we can read the directory. */

    while (directory && (entry = mc_readdir (directory)))
    {
        if (!str_is_valid_string (entry->d_name))
            continue;

        /* Special case for no filename.
           All entries except "." and ".." match. */
        if (filename_len == 0)
        {
            if (!strcmp (entry->d_name, ".") || !strcmp (entry->d_name, ".."))
                continue;
        }
        else
        {
            /* Otherwise, if these match up to the length of filename, then
               it may be a match. */
            if ((entry->d_name[0] != filename[0]) ||
                ((NLENGTH (entry)) < filename_len) ||
                strncmp (filename, entry->d_name, filename_len))
                continue;
        }
        isdir = 1;
        isexec = 0;
        {
            struct stat tempstat;
            vfs_path_t *tmp_vpath;

            tmp_vpath = vfs_path_build_filename (dirname, entry->d_name, (char *) NULL);

            /* Unix version */
            if (mc_stat (tmp_vpath, &tempstat) == 0)
            {
                uid_t my_uid = getuid ();
                gid_t my_gid = getgid ();

                if (!S_ISDIR (tempstat.st_mode))
                {
                    isdir = 0;
                    if ((!my_uid && (tempstat.st_mode & 0111)) ||
                        (my_uid == tempstat.st_uid && (tempstat.st_mode & 0100)) ||
                        (my_gid == tempstat.st_gid && (tempstat.st_mode & 0010)) ||
                        (tempstat.st_mode & 0001))
                        isexec = 1;
                }
            }
            else
            {
                /* stat failed, strange. not a dir in any case */
                isdir = 0;
            }
            vfs_path_free (tmp_vpath);
        }
        if ((flags & INPUT_COMPLETE_COMMANDS) && (isexec || isdir))
            break;
        if ((flags & INPUT_COMPLETE_CD) && isdir)
            break;
        if (flags & (INPUT_COMPLETE_FILENAMES))
            break;
    }

    if (entry == NULL)
    {
        if (directory)
        {
            mc_closedir (directory);
            directory = NULL;
        }
        g_free (dirname);
        dirname = NULL;
        vfs_path_free (dirname_vpath);
        dirname_vpath = NULL;
        g_free (filename);
        filename = NULL;
        g_free (users_dirname);
        users_dirname = NULL;
        return NULL;
    }

    {
        GString *temp;

        temp = g_string_sized_new (16);

        if (users_dirname != NULL && (users_dirname[0] != '.' || users_dirname[1] != '\0'))
        {
            g_string_append (temp, users_dirname);

            /* We need a '/' at the end. */
            if (temp->str[temp->len - 1] != PATH_SEP)
                g_string_append_c (temp, PATH_SEP);
        }
        g_string_append (temp, entry->d_name);
        if (isdir)
            g_string_append_c (temp, PATH_SEP);

        return g_string_free (temp, FALSE);
    }
}
Ejemplo n.º 3
0
static void
rspamd_process_file (const gchar *fname)
{
	struct rspamd_task *task;
	GIOChannel *f;
	GError *err = NULL;
	GString *buf;
	struct received_header rh;
	gdouble t1, t2;

	f = g_io_channel_new_file (fname, "r", &err);

	if (!f) {
		rspamd_fprintf (stderr, "cannot open %s: %e\n", fname, err);
		g_error_free (err);

		return;
	}

	g_io_channel_set_encoding (f, NULL, NULL);
	buf = g_string_sized_new (8192);
	task = g_malloc0 (sizeof (*task));
	task->task_pool = rspamd_mempool_new (rspamd_mempool_suggest_size (), "test");

	while (g_io_channel_read_line_string (f, buf, NULL, &err)
			== G_IO_STATUS_NORMAL) {

		while (buf->len > 0 && g_ascii_isspace (buf->str[buf->len - 1])) {
			buf->len --;
		}

		t1 = rspamd_get_virtual_ticks ();
		rspamd_smtp_recieved_parse (task, buf->str, buf->len, &rh);
		t2 = rspamd_get_virtual_ticks ();

		total_time += t2 - t1;
		total_parsed ++;

		if (rh.addr) {
			total_real_ip ++;
		}
		if (rh.real_hostname) {
			total_real_host ++;
		}
		if (rh.type != RSPAMD_RECEIVED_UNKNOWN) {
			total_known_proto ++;
		}

		if (rh.by_hostname || rh.timestamp > 0) {
			total_valid ++;
		}

		if (rh.timestamp != 0) {
			total_known_ts ++;
		}
	}

	if (err) {
		rspamd_fprintf (stderr, "cannot read %s: %e\n", fname, err);
		g_error_free (err);
	}

	g_io_channel_unref (f);
	g_string_free (buf, TRUE);
	rspamd_mempool_delete (task->task_pool);
	g_free (task);
}
Ejemplo n.º 4
0
static GAppInfo* app_info_create_from_commandline(const char *commandline,
                                               const char *application_name,
                                               const char *bin_name,
                                               const char *mime_type,
                                               gboolean terminal, gboolean keep)
{
    GAppInfo* app = NULL;
    char* dirname = g_build_filename (g_get_user_data_dir (), "applications", NULL);
    const char* app_basename = strrchr(bin_name, '/');

    if(app_basename)
        app_basename++;
    else
        app_basename = bin_name;
    if(g_mkdir_with_parents(dirname, 0700) == 0)
    {
        char* filename = g_strdup_printf ("%s/userapp-%s-XXXXXX.desktop", dirname, app_basename);
        int fd = g_mkstemp (filename);
        if(fd != -1)
        {
            GString* content = g_string_sized_new(256);
            g_string_printf(content,
                "[" G_KEY_FILE_DESKTOP_GROUP "]\n"
                G_KEY_FILE_DESKTOP_KEY_TYPE "=" G_KEY_FILE_DESKTOP_TYPE_APPLICATION "\n"
                G_KEY_FILE_DESKTOP_KEY_NAME "=%s\n"
                G_KEY_FILE_DESKTOP_KEY_EXEC "=%s\n"
                G_KEY_FILE_DESKTOP_KEY_CATEGORIES "=Other;\n"
                G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY "=true\n",
                application_name,
                commandline
            );
            if(mime_type)
                g_string_append_printf(content,
                                       G_KEY_FILE_DESKTOP_KEY_MIME_TYPE "=%s\n",
                                       mime_type);
            g_string_append_printf(content,
                                   G_KEY_FILE_DESKTOP_KEY_TERMINAL "=%s\n",
                                   terminal ? "true" : "false");
            if(terminal)
                g_string_append_printf(content, "X-KeepTerminal=%s\n",
                                       keep ? "true" : "false");
            close(fd); /* g_file_set_contents() may fail creating duplicate */
            if(g_file_set_contents(filename, content->str, content->len, NULL))
            {
                char *fbname = g_path_get_basename(filename);
                app = G_APP_INFO(g_desktop_app_info_new(fbname));
                g_free(fbname);
                /* if there is mime_type set then created application will be
                   saved for the mime type (see fm_choose_app_for_mime_type()
                   below) but if not then we should remove this temp. file */
                if(!mime_type || !application_name[0])
                    /* save the name so this file will be removed later */
                    g_object_weak_ref(G_OBJECT(app), on_temp_appinfo_destroy,
                                      g_strdup(filename));
            }
            else
                g_unlink(filename);
            g_string_free(content, TRUE);
        }
        g_free(filename);
    }
    g_free(dirname);
    return app;
}
Ejemplo n.º 5
0
int tbl_to_db(struct freeq_ctx *ctx, struct freeq_table *tbl, sqlite4 *mDb)
{
        sqlite4_stmt *stmt;
        GString *sql = g_string_sized_new(255);
        GSList *colp[tbl->numcols];

        memset(colp, 0, tbl->numcols * sizeof(GSList *) );
        for (int j = 0; j < tbl->numcols; j++)
                colp[j] = tbl->columns[j].data;

        int res;

        freeq_table_print(ctx, tbl, stdout);

        if (sqlite4_exec(mDb, "BEGIN TRANSACTION;", NULL, NULL) != SQLITE4_OK)
        {
                dbg(ctx, "unable to start transaction: %s\n", sqlite4_errmsg(mDb));
                return 1;
        }

        g_string_printf(sql, "DROP TABLE %s;", tbl->name);
        if (sqlite4_exec(mDb, sql->str, NULL, NULL) != SQLITE4_OK)
                dbg(ctx, "failed to drop table, ignoring\n");

        table_ddl(ctx, tbl, sql);
        if (sqlite4_exec(mDb, sql->str, NULL, NULL) != SQLITE4_OK)
        {
                dbg(ctx, "failed to create table, rolling back\n");
                sqlite4_exec(mDb, "ROLLBACK;", NULL, NULL);
                g_string_free(sql, 1);
                return 1;
        }

        ddl_insert(ctx, tbl, sql);
        if ((res = sqlite4_prepare(mDb, sql->str, sql->len, &stmt, NULL)) != SQLITE4_OK)
        {
                dbg(ctx, "failed to create statement (%d), rolling back\n", res);
                sqlite4_exec(mDb, "ROLLBACK;", NULL, NULL);
                g_string_free(sql,1);
                return 1;
        }

        g_string_free(sql,1);
        for (uint32_t i = 0; i < tbl->numrows; i++)
        {
                for (uint32_t j = 0; j < tbl->numcols; j++)
                {
                        switch (tbl->columns[j].coltype)
                        {
                        case FREEQ_COL_STRING:
                                res = sqlite4_bind_text(stmt,
                                                        j+1,
                                                        colp[j]->data == NULL ? "" : colp[j]->data,
                                                        colp[j]->data == NULL ? 0 : strlen(colp[j]->data),
                                                        SQLITE4_TRANSIENT, NULL);
                                if (res != SQLITE4_OK)
                                {
                                        dbg(ctx, "stmt: %s\n", (char *)stmt);
                                        dbg(ctx, "row %d failed binding string column %d %s: %s (%d)\n", i, j, (char *)colp[j]->data, sqlite4_errmsg(mDb), res);
                                }
                                break;
                        case FREEQ_COL_NUMBER:
                                res = sqlite4_bind_int(stmt, j, GPOINTER_TO_INT(colp[j]->data));
                                if (res != SQLITE4_OK)
                                {
                                        dbg(ctx, "row %d failed bind: %s\n", i, sqlite4_errmsg(mDb));
                                }
                                break;
                        default:
                                break;
                        }
                        colp[j] = g_slist_next(colp[j]);
                }
                if (sqlite4_step(stmt) != SQLITE4_DONE)
                {
                        dbg(ctx, "execute failed: %s\n", sqlite4_errmsg(mDb));
                        sqlite4_exec(mDb, "ROLLBACK;", NULL, NULL);
                        sqlite4_finalize(stmt);
                        return -1;
                } else {
                        sqlite4_reset(stmt);
                }
        }

        dbg(ctx, "committing transaction\n");
        res = sqlite4_exec(mDb, "COMMIT TRANSACTION;", NULL, NULL);
        dbg(ctx, "result of commit was %d\n", res);
        sqlite4_finalize(stmt);
        return 0;
}
Ejemplo n.º 6
0
static void request_get_and_head(DavServer *server, DavRequest *request) {
	GString *physpath = g_string_sized_new(0);
	GString *mimetype;
	struct stat st;
	int fd = -1;

	dav_server_map_path(physpath, server, request->url_path);

	if (-1 == dav_intrsafe_open(physpath->str, O_RDONLY)) {
		switch (errno) {
		case EACCES:
			dav_response_error(server, request, 403);
			goto cleanup;
		case ENOENT:
		case ENOTDIR:
			dav_response_error(server, request, 404);
			goto cleanup;
		default:
			dav_response_error(server, request, 500);
			/* TODO: log error */
			goto cleanup;
		}
	}

	if (-1 == fstat(fd, &st)) {
		dav_response_error(server, request, 500);
		/* TODO: log error */
		goto cleanup;
	}

	if (S_ISDIR(st.st_mode) && '/' != request->url_path->str[request->url_path->len-1]) {
		dav_append_trailing_slash(request->url_path);
		dav_response_location(server, request, request->url_path);
		request->response_status = 301;
		goto cleanup;
	}

	if (S_ISDIR(st.st_mode)) {
		/* TODO: print dirlist? */
		request->response_status = 200;
		goto cleanup;
	} else if (!S_ISREG(st.st_mode)) {
		dav_response_error(server, request, 403);
		goto cleanup;
	}

	if (DAV_HEAD != request->method) {
		/* no real content on head */
		request->response_filename = physpath;
		physpath = NULL;
		request->response_fd = fd;
		fd = -1;
	}

	/* TODO: support etag/if-modified and similar/ranged requests... */

	mimetype = dav_server_get_mimetype(server, physpath);
	g_string_append_printf(dav_response_get_header(server, request), "Content-Length: %" G_GOFFSET_FORMAT "\r\nContent-Type: %s\r\n", (goffset) st.st_size, mimetype->str);

	request->response_status = 200;

cleanup:
	if (NULL != physpath) g_string_free(physpath, TRUE);
	if (-1 != fd) dav_intrsafe_close(fd);
}
Ejemplo n.º 7
0
static gboolean
update (NMDnsPlugin *plugin,
        const GSList *vpn_configs,
        const GSList *dev_configs,
        const GSList *other_configs,
        const char *hostname,
        const char *iface)
{
	NMDnsDnsmasq *self = NM_DNS_DNSMASQ (plugin);
	GString *conf;
	GSList *iter;
	const char *argv[11];
	GError *error = NULL;
	int ignored;
	GPid pid = 0;

	/* Kill the old dnsmasq; there doesn't appear to be a way to get dnsmasq
	 * to reread the config file using SIGHUP or similar.  This is a small race
	 * here when restarting dnsmasq when DNS requests could go to the upstream
	 * servers instead of to dnsmasq.
	 */
	nm_dns_plugin_child_kill (plugin);

	/* Build up the new dnsmasq config file */
	conf = g_string_sized_new (150);

	/* Use split DNS for VPN configs */
	for (iter = (GSList *) vpn_configs; iter; iter = g_slist_next (iter)) {
		if (NM_IS_IP4_CONFIG (iter->data))
			add_ip4_config (conf, NM_IP4_CONFIG (iter->data), TRUE);
		else if (NM_IS_IP6_CONFIG (iter->data))
			add_ip6_config (conf, NM_IP6_CONFIG (iter->data), TRUE, iface);
	}

	/* Now add interface configs without split DNS */
	for (iter = (GSList *) dev_configs; iter; iter = g_slist_next (iter)) {
		if (NM_IS_IP4_CONFIG (iter->data))
			add_ip4_config (conf, NM_IP4_CONFIG (iter->data), FALSE);
		else if (NM_IS_IP6_CONFIG (iter->data))
			add_ip6_config (conf, NM_IP6_CONFIG (iter->data), FALSE, iface);
	}

	/* And any other random configs */
	for (iter = (GSList *) other_configs; iter; iter = g_slist_next (iter)) {
		if (NM_IS_IP4_CONFIG (iter->data))
			add_ip4_config (conf, NM_IP4_CONFIG (iter->data), FALSE);
		else if (NM_IS_IP6_CONFIG (iter->data))
			add_ip6_config (conf, NM_IP6_CONFIG (iter->data), FALSE, iface);
	}

	/* Write out the config file */
	if (!g_file_set_contents (CONFFILE, conf->str, -1, &error)) {
		nm_log_warn (LOGD_DNS, "Failed to write dnsmasq config file %s: (%d) %s",
		             CONFFILE,
		             error ? error->code : -1,
		             error && error->message ? error->message : "(unknown)");
		g_clear_error (&error);
		goto out;
	}
	ignored = chmod (CONFFILE, 0600);

	nm_log_dbg (LOGD_DNS, "dnsmasq local caching DNS configuration:");
	nm_log_dbg (LOGD_DNS, "%s", conf->str);

	argv[0] = find_dnsmasq ();
	argv[1] = "--no-resolv";  /* Use only commandline */
	argv[2] = "--keep-in-foreground";
	argv[3] = "--strict-order";
	argv[4] = "--bind-interfaces";
	argv[5] = "--pid-file=" PIDFILE;
	argv[6] = "--listen-address=127.0.0.1"; /* Should work for both 4 and 6 */
	argv[7] = "--conf-file=" CONFFILE;
	argv[8] = "--cache-size=400";
	argv[9] = NULL;

	/* And finally spawn dnsmasq */
	pid = nm_dns_plugin_child_spawn (NM_DNS_PLUGIN (self), argv, PIDFILE, "bin/dnsmasq");

out:
	g_string_free (conf, TRUE);
	return pid ? TRUE : FALSE;
}
Ejemplo n.º 8
0
GString* li_chunk_extract(liVRequest *vr, liChunkParserMark from, liChunkParserMark to) {
	GString *str = g_string_sized_new(0);
	if (li_chunk_extract_to(vr, from, to, str)) return str;
	g_string_free(str, TRUE);
	return NULL;
}
Ejemplo n.º 9
0
static gchar *
log_matcher_posix_re_replace(LogMatcher *s, LogMessage *msg, gint value_handle, const gchar *value, gssize value_len, LogTemplate *replacement, gssize *new_length)
{
  LogMatcherPosixRe *self = (LogMatcherPosixRe *) s; 
  regmatch_t matches[RE_MAX_MATCHES];
  gboolean rc;
  GString *new_value = NULL;
  gsize current_ofs = 0;
  gboolean first_round = TRUE;
  gchar *buf;
  
  APPEND_ZERO(buf, value, value_len);

  do
    {
      if (current_ofs == value_len)
        break;

      rc = !regexec(&self->pattern, buf + current_ofs, RE_MAX_MATCHES, matches, current_ofs > 0 ? REG_NOTBOL : 0);
      if (rc)
        {
          /* start_ofs & end_ofs are relative to the original string */
          gsize start_ofs = matches[0].rm_so + current_ofs;
          gsize end_ofs = matches[0].rm_eo + current_ofs;

          if (start_ofs == end_ofs && !first_round)
            {
              start_ofs++;
              end_ofs++;
            }

          log_matcher_posix_re_feed_backrefs(s, msg, value_handle, matches, buf + current_ofs);

          if (!new_value)
            new_value = g_string_sized_new(value_len);

          g_string_append_len(new_value, buf + current_ofs, start_ofs - current_ofs);
          log_template_append_format(replacement, msg, NULL, LTZ_LOCAL, 0, NULL, new_value);
          current_ofs = end_ofs;

          if ((self->super.flags & LMF_GLOBAL) == 0)
            {
              g_string_append_len(new_value, buf + current_ofs, value_len - current_ofs);
              break;
            }
        }
      else
        {
          if (new_value)
            {
              /* no more matches, append the end of the string */
              g_string_append_len(new_value, buf + current_ofs, value_len - current_ofs);
            }
        }
      first_round = FALSE;
    }
  while (rc && (self->super.flags & LMF_GLOBAL));

  if (new_value)
    {
      if (new_length)
        *new_length = new_value->len;
      return g_string_free(new_value, FALSE);
    }
  return NULL;
}
Ejemplo n.º 10
0
/* Parse emacs modelines.
 * Emacs modelines looks like this: "-*- key1: value1; key2: value2 -*-"
 * They can happen on the first line, or on the second one if the first line is
 * a shebang (#!)
 * See http://www.delorie.com/gnu/docs/emacs/emacs_486.html
 */
static gchar *
parse_emacs_modeline (gchar           *s,
		      ModelineOptions *options)
{
	guint intval;
	GString *key, *value;

	key = g_string_sized_new (8);
	value = g_string_sized_new (8);

	while (*s != '\0')
	{
		while (*s != '\0' && (*s == ';' || g_ascii_isspace (*s)))
			s++;
		if (*s == '\0' || strncmp (s, "-*-", 3) == 0)
			break;

		g_string_assign (key, "");
		g_string_assign (value, "");

		while (*s != '\0' && *s != ':' && *s != ';' &&
		       !g_ascii_isspace (*s))
		{
			g_string_append_c (key, *s);
			s++;
		}

		if (!skip_whitespaces (&s))
			break;

		if (*s != ':')
			continue;
		s++;

		if (!skip_whitespaces (&s))
			break;

		while (*s != '\0' && *s != ';' && !g_ascii_isspace (*s))
		{
			g_string_append_c (value, *s);
			s++;
		}

		gedit_debug_message (DEBUG_PLUGINS,
				     "Emacs modeline bit: %s = %s",
				     key->str, value->str);

		/* "Mode" key is case insenstive */
		if (g_ascii_strcasecmp (key->str, "Mode") == 0)
		{
			g_free (options->language_id);
			options->language_id = get_language_id_emacs (value->str);
			
			options->set |= MODELINE_SET_LANGUAGE;
		}
		else if (strcmp (key->str, "tab-width") == 0)
		{
			intval = atoi (value->str);
			
			if (intval)
			{
				options->tab_width = intval;
				options->set |= MODELINE_SET_TAB_WIDTH;
			}
		}
		else if (strcmp (key->str, "indent-offset") == 0)
		{
			intval = atoi (value->str);
			
			if (intval)
			{
				options->indent_width = intval;
				options->set |= MODELINE_SET_INDENT_WIDTH;
			}
		}
		else if (strcmp (key->str, "indent-tabs-mode") == 0)
		{
			intval = strcmp (value->str, "nil") == 0;
			options->insert_spaces = intval;
			
			options->set |= MODELINE_SET_INSERT_SPACES;
		}
		else if (strcmp (key->str, "autowrap") == 0)
		{
			intval = strcmp (value->str, "nil") != 0;
			options->wrap_mode = intval ? GTK_WRAP_WORD : GTK_WRAP_NONE;
			
			options->set |= MODELINE_SET_WRAP_MODE;
		}
	}

	g_string_free (key, TRUE);
	g_string_free (value, TRUE);

	return *s == '\0' ? s : s + 2;
}
Ejemplo n.º 11
0
/*
 * Parse kate modelines.
 * Kate modelines are of the form "kate: key1 value1; key2 value2;"
 * These can happen on the 10 first or 10 last lines of the buffer.
 * See http://wiki.kate-editor.org/index.php/Modelines
 */
static gchar *
parse_kate_modeline (gchar           *s,
		     ModelineOptions *options)
{
	guint intval;
	GString *key, *value;

	key = g_string_sized_new (8);
	value = g_string_sized_new (8);

	while (*s != '\0')
	{
		while (*s != '\0' && (*s == ';' || g_ascii_isspace (*s)))
			s++;
		if (*s == '\0')
			break;

		g_string_assign (key, "");
		g_string_assign (value, "");

		while (*s != '\0' && *s != ';' && !g_ascii_isspace (*s))
		{
			g_string_append_c (key, *s);
			s++;
		}

		if (!skip_whitespaces (&s))
			break;
		if (*s == ';')
			continue;

		while (*s != '\0' && *s != ';' &&
		       !g_ascii_isspace (*s))
		{
			g_string_append_c (value, *s);
			s++;
		}

		gedit_debug_message (DEBUG_PLUGINS,
				     "Kate modeline bit: %s = %s",
				     key->str, value->str);

		if (strcmp (key->str, "hl") == 0 ||
		    strcmp (key->str, "syntax") == 0)
		{
			g_free (options->language_id);
			options->language_id = get_language_id_kate (value->str);
			
			options->set |= MODELINE_SET_LANGUAGE;
		}
		else if (strcmp (key->str, "tab-width") == 0)
		{
			intval = atoi (value->str);
			
			if (intval)
			{
				options->tab_width = intval;
				options->set |= MODELINE_SET_TAB_WIDTH;
			}
		}
		else if (strcmp (key->str, "indent-width") == 0)
		{
			intval = atoi (value->str);
			if (intval) options->indent_width = intval;
		}
		else if (strcmp (key->str, "space-indent") == 0)
		{
			intval = strcmp (value->str, "on") == 0 ||
			         strcmp (value->str, "true") == 0 ||
			         strcmp (value->str, "1") == 0;

			options->insert_spaces = intval;
			options->set |= MODELINE_SET_INSERT_SPACES;
		}
		else if (strcmp (key->str, "word-wrap") == 0)
		{
			intval = strcmp (value->str, "on") == 0 ||
			         strcmp (value->str, "true") == 0 ||
			         strcmp (value->str, "1") == 0;

			options->wrap_mode = intval ? GTK_WRAP_WORD : GTK_WRAP_NONE;

			options->set |= MODELINE_SET_WRAP_MODE;			
		}
		else if (strcmp (key->str, "word-wrap-column") == 0)
		{
			intval = atoi (value->str);
			
			if (intval)
			{
				options->right_margin_position = intval;
				options->display_right_margin = TRUE;
				
				options->set |= MODELINE_SET_RIGHT_MARGIN_POSITION |
				                MODELINE_SET_SHOW_RIGHT_MARGIN;
			}
		}
	}

	g_string_free (key, TRUE);
	g_string_free (value, TRUE);

	return s;
}
Ejemplo n.º 12
0
/* Parse vi(m) modelines.
 * Vi(m) modelines looks like this: 
 *   - first form:   [text]{white}{vi:|vim:|ex:}[white]{options}
 *   - second form:  [text]{white}{vi:|vim:|ex:}[white]se[t] {options}:[text]
 * They can happen on the three first or last lines.
 */
static gchar *
parse_vim_modeline (gchar           *s,
		    ModelineOptions *options)
{
	gboolean in_set = FALSE;
	gboolean neg;
	guint intval;
	GString *key, *value;

	key = g_string_sized_new (8);
	value = g_string_sized_new (8);

	while (*s != '\0' && !(in_set && *s == ':'))
	{
		while (*s != '\0' && (*s == ':' || g_ascii_isspace (*s)))
			s++;

		if (*s == '\0')
			break;

		if (strncmp (s, "set ", 4) == 0 ||
		    strncmp (s, "se ", 3) == 0)
		{
			s = strchr(s, ' ') + 1;
			in_set = TRUE;
		}

		neg = FALSE;
		if (strncmp (s, "no", 2) == 0)
		{
			neg = TRUE;
			s += 2;
		}

		g_string_assign (key, "");
		g_string_assign (value, "");

		while (*s != '\0' && *s != ':' && *s != '=' &&
		       !g_ascii_isspace (*s))
		{
			g_string_append_c (key, *s);
			s++;
		}

		if (*s == '=')
		{
			s++;
			while (*s != '\0' && *s != ':' &&
			       !g_ascii_isspace (*s))
			{
				g_string_append_c (value, *s);
				s++;
			}
		}

		if (strcmp (key->str, "ft") == 0 ||
		    strcmp (key->str, "filetype") == 0)
		{
			g_free (options->language_id);
			options->language_id = get_language_id_vim (value->str);
			
			options->set |= MODELINE_SET_LANGUAGE;
		}
		else if (strcmp (key->str, "et") == 0 ||
		    strcmp (key->str, "expandtab") == 0)
		{
			options->insert_spaces = !neg;
			options->set |= MODELINE_SET_INSERT_SPACES;
		}
		else if (strcmp (key->str, "ts") == 0 ||
			 strcmp (key->str, "tabstop") == 0)
		{
			intval = atoi (value->str);
			
			if (intval)
			{
				options->tab_width = intval;
				options->set |= MODELINE_SET_TAB_WIDTH;
			}
		}
		else if (strcmp (key->str, "sw") == 0 ||
			 strcmp (key->str, "shiftwidth") == 0)
		{
			intval = atoi (value->str);
			
			if (intval)
			{
				options->indent_width = intval;
				options->set |= MODELINE_SET_INDENT_WIDTH;
			}
		}
		else if (strcmp (key->str, "wrap") == 0)
		{
			options->wrap_mode = neg ? GTK_WRAP_NONE : GTK_WRAP_WORD;

			options->set |= MODELINE_SET_WRAP_MODE;
		}
		else if (strcmp (key->str, "textwidth") == 0 ||
		         strcmp (key->str, "tw") == 0)
		{
			intval = atoi (value->str);
			
			if (intval)
			{
				options->right_margin_position = intval;
				options->display_right_margin = TRUE;
				
				options->set |= MODELINE_SET_SHOW_RIGHT_MARGIN |
				                MODELINE_SET_RIGHT_MARGIN_POSITION;
				
			}
		}
	}

	g_string_free (key, TRUE);
	g_string_free (value, TRUE);

	return s;
}
Ejemplo n.º 13
0
/**
* sksrc: A HKP source
* keyids: the keyids to look up
* output: The output stream the data will end in
*
* Gets data from the keyserver, writes it to the output stream
**/
static void
seahorse_hkp_source_export_async (SeahorseServerSource *source,
                                  const gchar **keyids,
                                  GCancellable *cancellable,
                                  GAsyncReadyCallback callback,
                                  gpointer user_data)
{
	SeahorseHKPSource *self = SEAHORSE_HKP_SOURCE (source);
	ExportClosure *closure;
	GSimpleAsyncResult *res;
	SoupMessage *message;
	SoupURI *uri;
	const gchar *fpr;
	gchar hexfpr[11];
	GHashTable *form;
	guint len;
	gint i;

	res = g_simple_async_result_new (G_OBJECT (self), callback, user_data,
	                                 seahorse_hkp_source_export_async);
	closure = g_new0 (ExportClosure, 1);
	closure->source = g_object_ref (self);
	closure->data = g_string_sized_new (1024);
	closure->session = create_hkp_soup_session ();
	closure->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
	g_simple_async_result_set_op_res_gpointer (res, closure, export_closure_free);

	if (!keyids || !keyids[0]) {
		g_simple_async_result_complete_in_idle (res);
		g_object_unref (res);
		return;
	}

	uri = get_http_server_uri (self, "/pks/lookup");
	g_return_if_fail (uri);

	/* prepend the hex prefix (0x) to make keyservers happy */
	strncpy (hexfpr, "0x", 3);

	form = g_hash_table_new (g_str_hash, g_str_equal);
	for (i = 0; keyids[i] != NULL; i++) {
		g_hash_table_remove_all (form);

		/* Get the key id and limit it to 8 characters */
		fpr = keyids[i];
		len = strlen (fpr);
		if (len > 8)
			fpr += (len - 8);
	
		strncpy (hexfpr + 2, fpr, 9);

		/* The get key URI */
		g_hash_table_insert (form, "op", "get");
		g_hash_table_insert (form, "search", (char *)hexfpr);
		soup_uri_set_query_from_form (uri, form);

		message = soup_message_new_from_uri ("GET", uri);

		soup_session_queue_message (closure->session, message,
		                            on_export_message_complete,
		                            g_object_ref (res));

		closure->requests++;
		seahorse_progress_prep_and_begin (cancellable, message, NULL);
	}

	if (cancellable)
		closure->cancelled_sig = g_cancellable_connect (cancellable,
		                                                G_CALLBACK (on_session_cancelled),
		                                                closure->session, NULL);

	g_hash_table_destroy (form);
	g_object_unref (res);
}
Ejemplo n.º 14
0
/**
* sksrc: The HKP source to use
* input: The input stream to add
*
* Imports a list of keys from the input stream to the keyserver
**/
static void
seahorse_hkp_source_import_async (SeahorseServerSource *source,
                                  GInputStream *input,
                                  GCancellable *cancellable,
                                  GAsyncReadyCallback callback,
                                  gpointer user_data)
{
	SeahorseHKPSource *self = SEAHORSE_HKP_SOURCE (source);
	GSimpleAsyncResult *res;
	source_import_closure *closure;
	SoupMessage *message;
	GList *keydata = NULL;
	GString *buf = NULL;
	GHashTable *form;
	gchar *key;
	SoupURI *uri;
	GList *l;
	guint len;

	res = g_simple_async_result_new (G_OBJECT (source), callback, user_data,
	                                 seahorse_hkp_source_import_async);
	closure = g_new0 (source_import_closure, 1);
	closure->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
	closure->input = g_object_ref (input);
	closure->source = g_object_ref (self);
	closure->session = create_hkp_soup_session ();
	g_simple_async_result_set_op_res_gpointer (res, closure, source_import_free);

	for (;;) {

		buf = g_string_sized_new (2048);
		len = seahorse_util_read_data_block (buf, input,
		                                     "-----BEGIN PGP PUBLIC KEY BLOCK-----",
		                                     "-----END PGP PUBLIC KEY BLOCK-----");

		if (len > 0) {
			keydata = g_list_prepend (keydata, g_string_free (buf, FALSE));
		} else {
			g_string_free (buf, TRUE);
			break;
		}
	}

	if (g_list_length (keydata) == 0) {
		g_simple_async_result_complete_in_idle (res);
		g_object_unref (res);
		return;
	}

	/* Figure out the URI we're sending to */
	uri = get_http_server_uri (self, "/pks/add");
	g_return_if_fail (uri);

	/* New operation and away we go */
	keydata = g_list_reverse (keydata);

	form = g_hash_table_new (g_str_hash, g_str_equal);
	for (l = keydata; l; l = g_list_next (l)) {
		g_assert (l->data != NULL);
		g_hash_table_remove_all (form);

		g_hash_table_insert (form, "keytext", l->data);
		key = soup_form_encode_urlencoded (form);

		message = soup_message_new_from_uri ("POST", uri);
		soup_message_set_request (message, "application/x-www-form-urlencoded",
		                          SOUP_MEMORY_TAKE, key, strlen (key));

		soup_session_queue_message (closure->session, message,
		                            on_import_message_complete, g_object_ref (res));

		closure->requests++;
		seahorse_progress_prep_and_begin (cancellable, GUINT_TO_POINTER (closure->requests), NULL);
	}
	g_hash_table_destroy (form);

	if (cancellable)
		closure->cancelled_sig = g_cancellable_connect (cancellable,
		                                                G_CALLBACK (on_session_cancelled),
		                                                closure->session, NULL);

	soup_uri_free (uri);

	for (l = keydata; l != NULL; l = g_list_next (l))
		g_free (l->data);
	g_list_free (keydata);

	g_object_unref (res);
}
Ejemplo n.º 15
0
Archivo: file.c Proyecto: pkot/gnokii
GNOKII_API gint DB_Look (const gchar * const phone)
{
  DIR *dir;
  struct dirent *dirent;
  FILE *smsFile;
  GString *buf;
  gint numError, error;
  gint empty = 1;


  if (spool[0] == '\0')  // if user don't set spool dir, sending is disabled
    return (SMSD_NOK);
    
  if ((dir = opendir (spool)) == NULL)
  {
    g_print (_("Cannot open directory %s\n"), spool);
    return (SMSD_NOK);
  }

  buf = g_string_sized_new (64);
  
  while ((dirent = readdir (dir)))
  {
    gn_sms sms;
    gint slen = 0;
    
    if (strcmp (dirent->d_name, ".") == 0 || strcmp (dirent->d_name, "..") == 0 ||
        strncmp (dirent->d_name, "ERR.", 4) == 0)
      continue;
    
    g_string_printf (buf, "%s/%s", spool, dirent->d_name);
    
    if ((smsFile = fopen (buf->str, "r")) == NULL)
    {
      g_print (_("Can't open file %s for reading!\n"), buf->str);
      continue;
    }
    
    empty = 0;
    gn_sms_default_submit (&sms);
    memset (&sms.remote.number, 0, sizeof (sms.remote.number));

    if (fgets (sms.remote.number, sizeof (sms.remote.number), smsFile))
      slen = strlen (sms.remote.number);
    if (slen < 1)
    {
      error = -1;
      fclose (smsFile);
      g_print (_("Remote number is empty in %s!\n"), buf->str);
      goto handle_file;
    }
    
    if (sms.remote.number[slen - 1] == '\n')
      sms.remote.number[slen - 1] = '\0';
    
    /* Initialize SMS text */
    memset (&sms.user_data[0].u.text, 0, sizeof (sms.user_data[0].u.text));
    
    slen = fread ((gchar *) sms.user_data[0].u.text, 1, GN_SMS_MAX_LENGTH, smsFile);
    if (slen > 0 && sms.user_data[0].u.text[slen - 1] == '\n')
      sms.user_data[0].u.text[slen - 1] = '\0';
     
    fclose (smsFile);
    
//    sms.delivery_report = (smsdConfig.smsSets & SMSD_READ_REPORTS);

    if (sms.remote.number[0] == '+')
      sms.remote.type = GN_GSM_NUMBER_International;
    else
      sms.remote.type = GN_GSM_NUMBER_Unknown;
    
    sms.user_data[0].length = strlen ((gchar *) sms.user_data[0].u.text);
    sms.user_data[0].type = GN_SMS_DATA_Text;
    sms.user_data[1].type = GN_SMS_DATA_None;
    if (!gn_char_def_alphabet (sms.user_data[0].u.text))
       sms.dcs.u.general.alphabet = GN_SMS_DCS_UCS2;


    gn_log_xdebug ("Sending SMS: %s, %s\n", sms.remote.number, sms.user_data[0].u.text);
    
    numError = 0;
    do
    {
      if ((error = WriteSMS (&sms)) == GN_ERR_NONE)
        break;
      sleep (1);
    }
    while ((error == GN_ERR_TIMEOUT || error == GN_ERR_FAILED) && numError++ < 3);

 handle_file:
    if (error == GN_ERR_NONE)
    {
      if (unlink (buf->str))
        g_print (_("Cannot unlink %s."), buf->str);
    }
    else
    {
      GString *buf2;
      
      buf2 = g_string_sized_new (64);
      g_string_printf (buf2, "%s/ERR.%s", spool, dirent->d_name);
      
      g_print (_("Cannot send sms from file %s\n"), buf->str);
      if (rename (buf->str, buf2->str))
      {
        g_print (_("Cannot rename file %s to %s. Trying to unlink it.\n"),
                 buf->str, buf2->str);
        if (unlink (buf->str))
          g_print (_("Cannot unlink %s."), buf->str);
      }
      g_string_free (buf2, TRUE);
    }
  }
  
  g_string_free (buf, TRUE);
  closedir (dir);

  if (empty)
    return (SMSD_OUTBOXEMPTY);
  else
    return (SMSD_OK);
}
Ejemplo n.º 16
0
static gchar *
log_matcher_string_replace(LogMatcher *s, LogMessage *msg, gint value_handle, const gchar *value, gssize value_len, LogTemplate *replacement, gssize *new_length)
{
  LogMatcherString *self = (LogMatcherString *) s; 
  GString *new_value = NULL;
  gsize current_ofs = 0;
  gboolean first_round = TRUE;

  if (value_len < 0)
    value_len = strlen(value);

  const gchar *match;

  do
    {
      if (current_ofs == value_len)
        break;

      match = log_matcher_string_match_string(self, value + current_ofs, value_len - current_ofs);

      if (match != NULL)
        {
          /* start_ofs & end_ofs are relative to the original string */
          gsize start_ofs = match - value;
          gsize end_ofs = start_ofs + self->pattern_len;

          if (start_ofs == end_ofs && !first_round)
            {
              start_ofs++;
              end_ofs++;
            }

          if ((s->flags & LMF_STORE_MATCHES))
            log_msg_clear_matches(msg);

          if (!new_value)
            new_value = g_string_sized_new(value_len);

          g_string_append_len(new_value, value + current_ofs, start_ofs - current_ofs);
          log_template_append_format(replacement, msg, NULL, LTZ_LOCAL, 0, NULL, new_value);
          current_ofs = end_ofs;

          if ((self->super.flags & LMF_GLOBAL) == 0)
            {
              g_string_append_len(new_value, value + current_ofs, value_len - current_ofs);
              break;
            }
        }
      else
        {
          if (new_value)
            {
              /* no more matches, append the end of the string */
              g_string_append_len(new_value, value + current_ofs, value_len - current_ofs);
            }
        }
      first_round = FALSE;
    }
  while (match && (self->super.flags & LMF_GLOBAL));

  if (new_value)
    {
      if (new_length)
        *new_length = new_value->len;
      return g_string_free(new_value, FALSE);
    }
  return NULL;
}
Ejemplo n.º 17
0
static void request_proppatch(DavServer *server, DavRequest *request) {
	GString *buffer;
	GString *physpath = g_string_sized_new(0);
	struct stat st;
	GPtrArray *proplist = NULL;
	guint i, l;
	guint status;

	if (!dav_xml_parse_proppatch(server, request, &proplist)) goto cleanup;

	dav_server_map_path(physpath, server, request->url_path);

	if (-1 == stat(physpath->str, &st)) {
		switch (errno) {
		case EACCES:
			dav_response_error(server, request, 403);
			goto cleanup;
		case ENOENT:
		case ENOTDIR:
			dav_response_error(server, request, 404);
			goto cleanup;
		default:
			dav_response_error(server, request, 500);
			/* TODO: log error */
			goto cleanup;
		}
	}

	if (S_ISDIR(st.st_mode) && '/' != request->url_path->str[request->url_path->len-1]) {
		dav_append_trailing_slash(request->url_path);
		dav_response_location(server, request, request->url_path);
	}

	if (S_ISDIR(st.st_mode) || S_ISREG(st.st_mode)) {
		dav_response_error(server, request, 403);
		goto cleanup;
	}

	if (!dav_server_set_properties_begin(server, request)) {
		/* hard fail - internal server error. reason should be logged already */
		dav_response_error(server, request, 500);
		goto cleanup;
	}

	buffer = dav_response_prepare_buffer(server, request, 0);

	request->response_status = 207;
	g_string_append_len(buffer, GSTR_LEN(&XML_Start));
	g_string_append_len(buffer, GSTR_LEN(&MultiStatus_Start));

	g_string_append_len(buffer, CONST_STR_LEN("<D:response><D:href>"));
	g_string_append_len(buffer, GSTR_LEN(request->http_base));
	g_string_append_len(buffer, GSTR_LEN(request->url_path)); /* TODO: encode url */
	g_string_append_len(buffer, CONST_STR_LEN("</D:href><D:propstat><D:prop>"));

	for (i = 0, l = proplist->len; i < l; i += 3) {
		GString *prop_ns = g_ptr_array_index(proplist, i);
		GString *prop_name = g_ptr_array_index(proplist, i+1);
		GString *value = g_ptr_array_index(proplist, i+2);

		status = dav_server_set_property_check(server, request, physpath, prop_ns, prop_name, value);

		if (200 != status) goto failed_check;
	}

	/* everything looks fine. now really set and commit */

	for (i = 0, l = proplist->len; i < l; i += 3) {
		GString *prop_ns = g_ptr_array_index(proplist, i);
		GString *prop_name = g_ptr_array_index(proplist, i+1);
		GString *value = g_ptr_array_index(proplist, i+2);

		if (!dav_server_set_property(server, request, physpath, prop_ns, prop_name, value)) {
			/* hard fail - internal server error. reason should be logged already */
			dav_server_set_properties_rollback(server, request);
			dav_response_error(server, request, 500);
			goto cleanup;
		}

		if (GSTR_EQUAL(prop_ns, "DAV:")) {
			g_string_append_printf(buffer, "<D:%s/>", prop_name->str);
		} else {
			g_string_append_printf(buffer, "<R:%s xmlns:R=\"%s\"/>", prop_name->str, prop_ns->str);
		}
	}

	if (!dav_server_set_properties_commit(server, request)) {
		/* hard fail - internal server error. reason should be logged already */
		dav_response_error(server, request, 500);
		goto cleanup;
	}

	g_string_append_len(buffer, CONST_STR_LEN("</D:prop><D:status>" STATUS_LINE_200 "</D:status></D:propstat>"));
	g_string_append_len(buffer, CONST_STR_LEN("</D:response>\n"));

	g_string_append_len(buffer, GSTR_LEN(&MultiStatus_End));
	dav_response_xml_header(server, request);

	goto cleanup;

failed_check:
	{
		guint failed_ndx = i;
		{
			GString *prop_ns = g_ptr_array_index(proplist, failed_ndx);
			GString *prop_name = g_ptr_array_index(proplist, failed_ndx+1);

			if (GSTR_EQUAL(prop_ns, "DAV:")) {
				g_string_append_printf(buffer, "<D:%s/>", prop_name->str);
			} else {
				g_string_append_printf(buffer, "<R:%s xmlns:R=\"%s\"/>", prop_name->str, prop_ns->str);
			}
			g_string_append_printf(buffer, "</D:prop><D:status>HTTP/1.1 %i %s</D:status></D:propstat>", status, dav_response_status_str(status));
		}

		if (proplist->len > 3) {
			for (i = 0, l = proplist->len; i < l; i += 3) {
				GString *prop_ns = g_ptr_array_index(proplist, i);
				GString *prop_name = g_ptr_array_index(proplist, i+1);

				if (failed_ndx == i) continue;

				if (GSTR_EQUAL(prop_ns, "DAV:")) {
					g_string_append_printf(buffer, "<D:%s/>", prop_name->str);
				} else {
					g_string_append_printf(buffer, "<R:%s xmlns:R=\"%s\"/>", prop_name->str, prop_ns->str);
				}
			}
			g_string_append_len(buffer, CONST_STR_LEN("</D:prop><D:status>" STATUS_LINE_424 "</D:status></D:propstat>"));
		}
	}
	g_string_append_len(buffer, CONST_STR_LEN("</D:response>\n"));

	g_string_append_len(buffer, GSTR_LEN(&MultiStatus_End));
	dav_response_xml_header(server, request);

cleanup:
	g_ptr_array_free(proplist, TRUE);
	g_string_free(physpath, TRUE);
}
Ejemplo n.º 18
0
static gchar *
log_matcher_pcre_re_replace(LogMatcher *s, LogMessage *msg, gint value_handle, const gchar *value, gssize value_len, LogTemplate *replacement, gssize *new_length)
{
  LogMatcherPcreRe *self = (LogMatcherPcreRe *) s; 
  GString *new_value = NULL;
  gint *matches;
  gsize matches_size;
  gint num_matches;
  gint rc;
  gint start_offset, last_offset;
  gint options;
  gboolean last_match_was_empty;

  if (pcre_fullinfo(self->pattern, self->extra, PCRE_INFO_CAPTURECOUNT, &num_matches) < 0)
    g_assert_not_reached();
  if (num_matches > RE_MAX_MATCHES)
    num_matches = RE_MAX_MATCHES;

  matches_size = 3 * (num_matches + 1);
  matches = g_alloca(matches_size * sizeof(gint));

  /* we need zero initialized offsets for the last match as the
   * algorithm tries uses that as the base position */

  matches[0] = matches[1] = matches[2] = 0;

  if (value_len == -1)
    value_len = strlen(value);

  last_offset = start_offset = 0;
  last_match_was_empty = FALSE;
  do
    {
      /* loop over the string, replacing one occurence at a time. */

      /* NOTE: zero length matches need special care, as we could spin
       * forever otherwise (since the current position wouldn't be
       * advanced).
       *
       * A zero-length match can be as simple as "a*" which will be
       * returned unless PCRE_NOTEMPTY is specified.
       *
       * By supporting zero-length matches, we basically make it
       * possible to insert replacement between each incoming
       * character.
       *
       * For example:
       *     pattern: a*
       *     replacement: #
       *     input: message
       *     result: #m#e#s#s#a#g#e#
       *
       * This mimics Perl behaviour.
       */

      if (last_match_was_empty)
        {
          /* Otherwise, arrange to run another match at the same point
           * to see if a non-empty match can be found.
           */

          options = PCRE_NOTEMPTY | PCRE_ANCHORED;
        }
      else
        {
          options = 0;
        }

      rc = pcre_exec(self->pattern, self->extra,
                     value, value_len,
                     start_offset, (self->match_options | options), matches, matches_size);
      if (rc < 0 && rc != PCRE_ERROR_NOMATCH)
        {
          msg_error("Error while matching regexp",
                    evt_tag_int("error_code", rc),
                    NULL);
          break;
        }
      else if (rc < 0)
        {
          if ((options & PCRE_NOTEMPTY) == 0)
            {
              /* we didn't match, even when we permitted to match the
               * empty string. Nothing to find here, bail out */
              break;
            }

          /* we didn't match, quite possibly because the empty match
           * was not permitted. Skip one character in order to avoid
           * infinite loop over the same zero-length match. */

          start_offset = start_offset + 1;
          /* FIXME: handle complex sequences like utf8 and newline characters */
          last_match_was_empty = FALSE;
          continue;
        }
      else
        {
          /* if the output array was too small, truncate the number of
             captures to RE_MAX_MATCHES */

          if (rc == 0)
            rc = matches_size / 3;

          log_matcher_pcre_re_feed_backrefs(s, msg, value_handle, matches, rc, value);
          log_matcher_pcre_re_feed_named_substrings(s, msg, matches, value);

          if (!new_value)
            new_value = g_string_sized_new(value_len); 
          /* append non-matching portion */
          g_string_append_len(new_value, &value[last_offset], matches[0] - last_offset);
          /* replacement */
          log_template_append_format(replacement, msg, NULL, LTZ_LOCAL, 0, NULL, new_value);

          last_match_was_empty = (matches[0] == matches[1]);
          start_offset = last_offset = matches[1];
        }
    }
  while (self->super.flags & LMF_GLOBAL && start_offset < value_len);

  if (new_value)
    { 
      /* append the last literal */
      g_string_append_len(new_value, &value[last_offset], value_len - last_offset);
      if (new_length)
        *new_length = new_value->len;
      return g_string_free(new_value, FALSE);
    }
  return NULL;
}
Ejemplo n.º 19
0
static int init(struct sr_output *o)
{
	struct context *ctx;
	struct sr_probe *probe;
	GSList *l;
	int num_probes;
	uint64_t samplerate;
	time_t t;
	unsigned int i;

	if (!o) {
		sr_err("csv out: %s: o was NULL", __func__);
		return SR_ERR_ARG;
	}

	if (!o->device) {
		sr_err("csv out: %s: o->device was NULL", __func__);
		return SR_ERR_ARG;
	}

	if (!o->device->plugin) {
		sr_err("csv out: %s: o->device->plugin was NULL", __func__);
		return SR_ERR_ARG;
	}

	if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
		sr_err("csv out: %s: ctx malloc failed", __func__);
		return SR_ERR_MALLOC;
	}

	o->internal = ctx;

	/* Get the number of probes, their names, and the unitsize. */
	/* TODO: Error handling. */
	for (l = o->device->probes; l; l = l->next) {
		probe = l->data;
		if (!probe->enabled)
			continue;
		ctx->probelist[ctx->num_enabled_probes++] = probe->name;
	}
	ctx->probelist[ctx->num_enabled_probes] = 0;
	ctx->unitsize = (ctx->num_enabled_probes + 7) / 8;

	num_probes = g_slist_length(o->device->probes);

	if (sr_device_has_hwcap(o->device, SR_HWCAP_SAMPLERATE)) {
		samplerate = *((uint64_t *) o->device->plugin->get_device_info(
				o->device->plugin_index, SR_DI_CUR_SAMPLERATE));
		/* TODO: Error checks. */
	} else {
		samplerate = 0; /* TODO: Error or set some value? */
	}
	ctx->samplerate = samplerate;

	ctx->separator = ',';

	ctx->header = g_string_sized_new(512);

	t = time(NULL);

	/* Some metadata */
	g_string_append_printf(ctx->header, "; CSV, generated by %s on %s",
			       PACKAGE_STRING, ctime(&t));
	g_string_append_printf(ctx->header, "; Samplerate: %"PRIu64"\n",
			       ctx->samplerate);

	/* Columns / channels */
	g_string_append_printf(ctx->header, "; Channels (%d/%d): ",
			       ctx->num_enabled_probes, num_probes);
	for (i = 0; i < ctx->num_enabled_probes; i++)
		g_string_append_printf(ctx->header, "%s, ", ctx->probelist[i]);
	g_string_append_printf(ctx->header, "\n");

	return 0; /* TODO: SR_OK? */
}
Ejemplo n.º 20
0
GString*
net_post_blocking(const char *url, GSList *headers, GString *post,
                  NetStatusCallback cb, gpointer data,
                  GError **err) {
	CURL *curl;
	CURLcode curlres;
	char proxyuserpass[1024];
	char errorbuf[CURL_ERROR_SIZE];
	RequestData requestdata = {0};
	struct curl_slist *curlheaders = NULL;

	curl = curl_easy_init();
	if (curl == NULL) {
		g_set_error(err, NET_ERROR, NET_ERROR_GENERIC,
				_("Unable to intialize CURL"));
		return NULL;
	}

	curl_easy_setopt(curl, CURLOPT_VERBOSE, conf.options.netdump != 0);
	curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorbuf);

	/*
	 * curl's progress function is mostly useless; we instead track writes.
	 *
	 * curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, curl_progress_cb);
	 * curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, nr);
	 */
	
	curl_easy_setopt(curl, CURLOPT_URL, url);

	if (conf.options.useproxy) {
		curl_easy_setopt(curl, CURLOPT_PROXY, conf.proxy);
		if (conf.options.useproxyauth) {
			g_snprintf(proxyuserpass, sizeof(proxyuserpass), "%s:%s", 
					conf.proxyuser, conf.proxypass);
			curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxyuserpass);
		}
	}

	curl_easy_setopt(curl, CURLOPT_USERAGENT, LOGJAM_USER_AGENT);

	if (headers) {
		GSList *l;
		for (l = headers; l; l = l->next)
			curlheaders = curl_slist_append(curlheaders, l->data);
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curlheaders);
	}

	if (post) {
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post->str);
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post->len);
		curl_easy_setopt(curl, CURLOPT_POST, 1);
	}

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlwrite_cb);
	requestdata.curl = curl;
	requestdata.response = g_string_sized_new(READ_BLOCK_SIZE);
	requestdata.user_cb = cb;
	requestdata.user_data = data;
	curl_easy_setopt(curl, CURLOPT_FILE, &requestdata);
	
	if (conf.options.netdump && post) 
		fprintf(stderr, _("Request: [%s]\n"), post->str);

	curlres = curl_easy_perform(curl);
	if (curlheaders)
		curl_slist_free_all(curlheaders);
	curl_easy_cleanup(curl);

	if (curlres != CURLE_OK) {
		g_set_error(err, NET_ERROR, NET_ERROR_GENERIC,
				_("cURL error: %s."), errorbuf);
		g_string_free(requestdata.response, TRUE);
		return NULL;
	}

	if (conf.options.netdump) 
		fprintf(stderr, _("Response: [%s]\n"), requestdata.response->str);

	return requestdata.response;
}
Ejemplo n.º 21
0
static void control_ng_incoming(struct obj *obj, str *buf, struct sockaddr_in6 *sin, char *addr) {
	struct control_ng *c = (void *) obj;
	bencode_buffer_t bencbuf;
	bencode_item_t *dict, *resp;
	str cmd, cookie, data, reply, *to_send, callid;
	const char *errstr;
	struct msghdr mh;
	struct iovec iov[3];
	GString *log_str;

	struct control_ng_stats* cur = get_control_ng_stats(c,&sin->sin6_addr);

	str_chr_str(&data, buf, ' ');
	if (!data.s || data.s == buf->s) {
		ilog(LOG_WARNING, "Received invalid data on NG port (no cookie) from %s: "STR_FORMAT, addr, STR_FMT(buf));
		return;
	}

	bencode_buffer_init(&bencbuf);
	resp = bencode_dictionary(&bencbuf);

	cookie = *buf;
	cookie.len -= data.len;
	*data.s++ = '\0';
	data.len--;

	errstr = "Invalid data (no payload)";
	if (data.len <= 0)
		goto err_send;

	to_send = cookie_cache_lookup(&c->cookie_cache, &cookie);
	if (to_send) {
		ilog(LOG_INFO, "Detected command from %s as a duplicate", addr);
		resp = NULL;
		goto send_only;
	}

	dict = bencode_decode_expect_str(&bencbuf, &data, BENCODE_DICTIONARY);
	errstr = "Could not decode dictionary";
	if (!dict)
		goto err_send;

	bencode_dictionary_get_str(dict, "command", &cmd);
	errstr = "Dictionary contains no key \"command\"";
	if (!cmd.s)
		goto err_send;

	bencode_dictionary_get_str(dict, "call-id", &callid);
	log_info_str(&callid);

	ilog(LOG_INFO, "Received command '"STR_FORMAT"' from %s", STR_FMT(&cmd), addr);

	if (get_log_level() >= LOG_DEBUG) {
		log_str = g_string_sized_new(256);
		g_string_append_printf(log_str, "Dump for '"STR_FORMAT"' from %s: ", STR_FMT(&cmd), addr);
		pretty_print(dict, log_str);
		ilog(LOG_DEBUG, "%.*s", (int) log_str->len, log_str->str);
		g_string_free(log_str, TRUE);
	}

	errstr = NULL;
	if (!str_cmp(&cmd, "ping")) {
		bencode_dictionary_add_string(resp, "result", "pong");
		g_atomic_int_inc(&cur->ping);
	}
	else if (!str_cmp(&cmd, "offer")) {
		errstr = call_offer_ng(dict, c->callmaster, resp, addr, sin);
		g_atomic_int_inc(&cur->offer);
	}
	else if (!str_cmp(&cmd, "answer")) {
		errstr = call_answer_ng(dict, c->callmaster, resp);
		g_atomic_int_inc(&cur->answer);
	}
	else if (!str_cmp(&cmd, "delete")) {
		errstr = call_delete_ng(dict, c->callmaster, resp);
		g_atomic_int_inc(&cur->delete);
	}
static void powerword_markup_add_text(const gchar *text, gssize length, std::string *pango, std::string::size_type &cur_pos, LinksPosList *links_list)
{
	const gchar *p;
	const gchar *end;
	p = text;
	end = text + length;

	GString *str;
	str = g_string_sized_new (length);

	const gchar *n;
	bool find;
	bool previous_islink = false;
	std::string marktags;
	guint currentmarktag = 0;
	while (p != end) {
		const gchar *next;
		next = g_utf8_next_char (p);
		switch (*p) {
			case '}':
				if (currentmarktag==0) {
					g_string_append (str, "}");
					previous_islink = false;
				}
				else {
					currentmarktag--;
					switch (marktags[currentmarktag]) {
						case 'b':
						case 'B':
							g_string_append (str, "</b>");
							previous_islink = false;
							break;
						case 'I':
							g_string_append (str, "</i>");
							previous_islink = false;
							break;
						case '+':
							g_string_append (str, "</sup>");
							previous_islink = false;
							break;
						case '-':
							g_string_append (str, "</sub>");
							previous_islink = false;
							break;
						case 'x':
							g_string_append (str, "</span>");
							previous_islink = false;
							break;
						case 'l':
						case 'D':
						case 'L':
						case 'U':
							g_string_append (str, "</span>");
							previous_islink = true;
							break;
						default:
							previous_islink = false;
							break;
					}
				}
				break;
			case '&':
				find = false;
				if (next!=end) {
					n = g_utf8_next_char(next);
					if (n!=end && *n == '{') {
						find=true;
						currentmarktag++;
						if (marktags.length()<currentmarktag)
							marktags+=*next;
						else
							marktags[currentmarktag-1]=*next;
						switch (*next) {
							case 'b':
							case 'B':
								g_string_append (str, "<b>");
								next = n+1;
								break;
							case 'I':
								g_string_append (str, "<i>");
								next = n+1;
								break;
							case '+':
								g_string_append (str, "<sup>");
								next = n+1;
								break;
							case '-':
								g_string_append (str, "<sub>");
								next = n+1;
								break;
							case 'x':
								g_string_append (str, "<span foreground=\"blue\" underline=\"single\">");
								next = n+1;
								break;
							case 'X':
							case '2':
								{
								const gchar *tag_end = n+1;
								while (tag_end!=end) {
									if (*tag_end=='}')
										break;
									else
										tag_end++;
								}
								g_string_append (str, "<span foreground=\"blue\">");
								gchar *tag_str;
								if (*next == 'X') {
									tag_str = toUtfPhonetic(n+1, tag_end - (n+1));
								} else {
									tag_str = toUtfPhonetic2(n+1, tag_end - (n+1));
								}
								g_string_append (str, tag_str);
								g_free(tag_str);
								g_string_append (str, "</span>");
								currentmarktag--;
								if (tag_end!=end)
									next = tag_end+1;
								else
									next = end;
								previous_islink = false;
								break;
								}
							case 'l':
							case 'D':
							case 'L':
							case 'U':
								if (previous_islink)
									g_string_append (str, "\t");
								if (*next == 'l' || *next == 'D')
									g_string_append (str, "<span foreground=\"blue\" underline=\"single\">");
								else
									g_string_append (str, "<span foreground=\"#008080\" underline=\"single\">");
								*pango += str->str;
								cur_pos += xml_strlen(str->str);
								g_string_erase(str, 0, -1);
								{
								const gchar *tag_end = n+1;
								while (tag_end!=end) {
									if (*tag_end=='}')
										break;
									else
										tag_end++;
								}
								char *tmpstr = g_markup_escape_text(n+1, tag_end - (n+1));
								size_t xml_len = xml_strlen(tmpstr);
								std::string link("query://");
								link.append(n+1, tag_end - (n+1));
								links_list->push_back(LinkDesc(cur_pos, xml_len, link));
								*pango += tmpstr;
								cur_pos += xml_len;
								g_free(tmpstr);
								g_string_append (str, "</span>");
								currentmarktag--;
								if (tag_end!=end)
									next = tag_end+1;
								else
									next = end;
								previous_islink = true;
								break;
								}
							/*case ' ':
							case '9':
							case 'S':*/
							default:
								next = n+1;
								break;
						}
					}
				}
				if (!find) {
					previous_islink = false;
					g_string_append (str, "&amp;");
				}
				break;
			case '<':
				previous_islink = false;
				g_string_append (str, "&lt;");
				break;
			case '>':
				previous_islink = false;
				g_string_append (str, "&gt;");
				break;
			case '\'':
				previous_islink = false;
				g_string_append (str, "&apos;");
				break;
			case '"':
				previous_islink = false;
				g_string_append (str, "&quot;");
				break;
			default:
				previous_islink = false;
				g_string_append_len (str, p, next - p);
				break;
		}
		p = next;
	}
	if (currentmarktag>0) {
		do {
			currentmarktag--;
			switch (marktags[currentmarktag]) {
				case 'b':
				case 'B':
					g_string_append (str, "</b>");
					break;
				case 'I':
					g_string_append (str, "</i>");
					break;
				case '+':
					g_string_append (str, "</sup>");
					break;
				case '-':
					g_string_append (str, "</sub>");
					break;
				case 'x':
				case 'l':
				case 'D':
				case 'L':
				case 'U':
					g_string_append (str, "</span>");
					break;
				default:
					break;
			}
		} while (currentmarktag>0);
	}
	*pango += str->str;
	cur_pos += xml_strlen(str->str);
	g_string_free (str, TRUE);
}
Ejemplo n.º 23
0
static void draw_page(GtkPrintOperation *operation, GtkPrintContext *context,
					  gint page_nr, gpointer user_data)
{
	DocInfo *dinfo = user_data;
	GeanyEditor *editor;
	cairo_t *cr;
	gdouble width, height;
	gdouble x = 0.0, y = 0.0;
	/*gint layout_h;*/
	gint count;
	GString *str;

	if (dinfo == NULL || page_nr >= dinfo->n_pages)
		return;

	editor = dinfo->doc->editor;

	if (dinfo->n_pages > 0)
	{
		gdouble fraction = (page_nr + 1) / (gdouble) dinfo->n_pages;
		gchar *text = g_strdup_printf(_("Page %d of %d"), page_nr, dinfo->n_pages);
		gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(main_widgets.progressbar), fraction);
		gtk_progress_bar_set_text(GTK_PROGRESS_BAR(main_widgets.progressbar), text);
		g_free(text);
	}

#ifdef GEANY_PRINT_DEBUG
	geany_debug("draw_page = %d, pages = %d, (real) lines_per_page = %d",
		page_nr, dinfo->n_pages, dinfo->lines_per_page);
#endif

	str = g_string_sized_new(256);
	cr = gtk_print_context_get_cairo_context(context);
	width = gtk_print_context_get_width(context);
	height = gtk_print_context_get_height(context);

	cairo_set_source_rgb(cr, 0, 0, 0);
#ifdef GEANY_PRINT_DEBUG
	cairo_set_line_width(cr, 0.2);
	cairo_rectangle(cr, 0, 0, width, height);
	cairo_stroke(cr);
#endif
	cairo_move_to(cr, 0, 0);

	pango_layout_set_width(dinfo->layout, width * PANGO_SCALE);
	pango_layout_set_alignment(dinfo->layout, PANGO_ALIGN_LEFT);
	pango_layout_set_ellipsize(dinfo->layout, FALSE);
	pango_layout_set_justify(dinfo->layout, FALSE);

	if (printing_prefs.print_page_header)
		add_page_header(dinfo, cr, width, page_nr);

	count = 0;	/* the actual line counter for the current page, might be different from
				 * dinfo->cur_line due to possible line breaks */
	while (count < dinfo->lines_per_page)
	{
		gchar c = 'a';
		gint style = -1;
		PangoAttrList *layout_attr;
		PangoAttribute *attr;
		gint colours[3] = { 0 };
		gboolean add_linenumber = TRUE;
		gboolean at_eol;

		while (count < dinfo->lines_per_page && c != '\0')
		{
			at_eol = FALSE;

			g_string_erase(str, 0, str->len); /* clear the string */

			/* line numbers */
			if (printing_prefs.print_line_numbers && add_linenumber)
			{
				/* if we had a wrapped line on the last page which needs to be continued, don't
				 * add a line number */
				if (dinfo->long_line)
				{
					add_linenumber = FALSE;
				}
				else
				{
					gchar *line_number = NULL;
					gint cur_line_number_margin = get_line_numbers_arity(dinfo->cur_line + 1);
					gchar *fill = g_strnfill(
						dinfo->max_line_number_margin - cur_line_number_margin - 1, ' ');

					line_number = g_strdup_printf("%s%d ", fill, dinfo->cur_line + 1);
					g_string_append(str, line_number);
					dinfo->cur_line++; /* increase document line */
					add_linenumber = FALSE;
					style = STYLE_LINENUMBER;
					c = 'a'; /* dummy value */
					g_free(fill);
					g_free(line_number);
				}
			}
			/* data */
			else
			{
				style = sci_get_style_at(dinfo->doc->editor->sci, dinfo->cur_pos);
				c = sci_get_char_at(dinfo->doc->editor->sci, dinfo->cur_pos);
				if (c == '\0' || style == -1)
				{	/* if c gets 0, we are probably out of document boundaries,
					 * so stop to break out of outer loop */
					count = dinfo->lines_per_page;
					break;
				}
				dinfo->cur_pos++;

				/* convert tabs to spaces which seems to be better than using Pango tabs */
				if (c == '\t')
				{
					gint tab_width = sci_get_tab_width(editor->sci);
					gchar *s = g_strnfill(tab_width, ' ');
					g_string_append(str, s);
					g_free(s);
				}
				/* don't add line breaks, they are handled manually below */
				else if (c == '\r' || c == '\n')
				{
					gchar c_next = sci_get_char_at(dinfo->doc->editor->sci, dinfo->cur_pos);
					at_eol = TRUE;
					if (c == '\r' && c_next == '\n')
						dinfo->cur_pos++; /* skip LF part of CR/LF */
				}
				else
				{
					g_string_append_c(str, c); /* finally add the character */

					/* handle UTF-8: since we add char by char (better: byte by byte), we need to
					 * keep UTF-8 characters together(e.g. two bytes for one character)
					 * the input is always UTF-8 and c is signed, so all non-Ascii
					 * characters are less than 0 and consist of all bytes less than 0.
					 * style doesn't change since it is only one character with multiple bytes. */
					while (c < 0)
					{
						c = sci_get_char_at(dinfo->doc->editor->sci, dinfo->cur_pos);
						if (c < 0)
						{	/* only add the byte when it is part of the UTF-8 character
							 * otherwise we could add e.g. a '\n' and it won't be visible in the
							 * printed document */
							g_string_append_c(str, c);
							dinfo->cur_pos++;
						}
					}
				}
			}

			if (! at_eol)
			{
				/* set text */
				pango_layout_set_text(dinfo->layout, str->str, -1);
				/* attributes */
				layout_attr = pango_attr_list_new();
				/* foreground colour */
				get_rgb_values(dinfo->styles[style][FORE], &colours[0], &colours[1], &colours[2]);
				attr = pango_attr_foreground_new(colours[0], colours[1], colours[2]);
				ADD_ATTR(layout_attr, attr);
				/* background colour */
				get_rgb_values(dinfo->styles[style][BACK], &colours[0], &colours[1], &colours[2]);
				attr = pango_attr_background_new(colours[0], colours[1], colours[2]);
				ADD_ATTR(layout_attr, attr);
				/* bold text */
				if (dinfo->styles[style][BOLD])
				{
					attr = pango_attr_weight_new(PANGO_WEIGHT_BOLD);
					ADD_ATTR(layout_attr, attr);
				}
				/* italic text */
				if (dinfo->styles[style][ITALIC])
				{
					attr = pango_attr_style_new(PANGO_STYLE_ITALIC);
					ADD_ATTR(layout_attr, attr);
				}
				pango_layout_set_attributes(dinfo->layout, layout_attr);
				pango_layout_context_changed(dinfo->layout);
				pango_attr_list_unref(layout_attr);
			}

			cairo_get_current_point(cr, &x, &y);


			/* normal line break at eol character in document */
			if (at_eol)
			{
				/*pango_layout_get_size(dinfo->layout, NULL, &layout_h);*/
				/*cairo_move_to(cr, 0, y + (gdouble)layout_h / PANGO_SCALE);*/
				cairo_move_to(cr, 0, y + dinfo->line_height);

				count++;
				/* we added a new document line so request a new line number */
				add_linenumber = TRUE;
			}
			else
			{
				gint x_offset = 0;
				/* maybe we need to force a line break because of too long line */
				if (x >= (width - dinfo->font_width))
				{
					/* don't start the line at horizontal origin because we need to skip the
					 * line number margin */
					if (printing_prefs.print_line_numbers)
					{
						x_offset = (dinfo->max_line_number_margin + 1) * dinfo->font_width;
					}

					/*pango_layout_get_size(dinfo->layout, NULL, &layout_h);*/
					/*cairo_move_to(cr, x_offset, y + (gdouble)layout_h / PANGO_SCALE);*/
					/* this is faster but not exactly the same as above */
					cairo_move_to(cr, x_offset, y + dinfo->line_height);
					cairo_get_current_point(cr, &x, &y);
					count++;
				}
				if (count < dinfo->lines_per_page)
				{
					/* str->len is counted in bytes not characters, so use g_utf8_strlen() */
					x_offset = (g_utf8_strlen(str->str, -1) * dinfo->font_width);

					if (dinfo->long_line && count == 0)
					{
						x_offset = (dinfo->max_line_number_margin + 1) * dinfo->font_width;
						dinfo->long_line = FALSE;
					}

					pango_cairo_show_layout(cr, dinfo->layout);
					cairo_move_to(cr, x + x_offset, y);
				}
				else
				/* we are on a wrapped line but we are out of lines on this page, so continue
				 * the current line on the next page and remember to continue in current line */
					dinfo->long_line = TRUE;
			}
		}
	}

	if (printing_prefs.print_line_numbers)
	{	/* print a thin line between the line number margin and the data */
		gint y_start = 0;

		if (printing_prefs.print_page_header)
			y_start = (dinfo->line_height * 3) - 2;	/* "- 2": to connect the line number line to
													 * the page header frame */

		cairo_set_line_width(cr, 0.3);
		cairo_move_to(cr, (dinfo->max_line_number_margin * dinfo->font_width) + 1, y_start);
		cairo_line_to(cr, (dinfo->max_line_number_margin * dinfo->font_width) + 1,
			y + dinfo->line_height); /* y is last added line, we reuse it */
		cairo_stroke(cr);
	}

	if (printing_prefs.print_page_numbers)
	{
		gchar *line = g_strdup_printf("<small>- %d -</small>", page_nr + 1);
		pango_layout_set_markup(dinfo->layout, line, -1);
		pango_layout_set_alignment(dinfo->layout, PANGO_ALIGN_CENTER);
		cairo_move_to(cr, 0, height - dinfo->line_height);
		pango_cairo_show_layout(cr, dinfo->layout);
		g_free(line);

#ifdef GEANY_PRINT_DEBUG
		cairo_set_line_width(cr, 0.3);
		cairo_move_to(cr, 0, height - (1.25 * dinfo->line_height));
		cairo_line_to(cr, width - 1, height - (1.25 * dinfo->line_height));
		cairo_stroke(cr);
#endif
	}
	g_string_free(str, TRUE);
}
Ejemplo n.º 24
0
static void proxy_send_headers(liVRequest *vr, liChunkQueue *out) {
	GString *head = g_string_sized_new(4095);
	liHttpHeader *header;
	GList *iter;
	liHttpHeaderTokenizer header_tokenizer;
	GString *tmp_str = vr->wrk->tmp_str;

	g_string_append_len(head, GSTR_LEN(vr->request.http_method_str));
	g_string_append_len(head, CONST_STR_LEN(" "));

	g_string_append_len(head, GSTR_LEN(vr->request.uri.raw_path));

	switch (vr->request.http_version) {
	case LI_HTTP_VERSION_1_1:
		/* g_string_append_len(head, CONST_STR_LEN(" HTTP/1.1\r\n")); */
		g_string_append_len(head, CONST_STR_LEN(" HTTP/1.0\r\n"));
		break;
	case LI_HTTP_VERSION_1_0:
	default:
		g_string_append_len(head, CONST_STR_LEN(" HTTP/1.0\r\n"));
		break;
	}

	li_http_header_tokenizer_start(&header_tokenizer, vr->request.headers, CONST_STR_LEN("Connection"));
	while (li_http_header_tokenizer_next(&header_tokenizer, tmp_str)) {
		if (0 == g_ascii_strcasecmp(tmp_str->str, "Upgrade")) {
			g_string_append_len(head, CONST_STR_LEN("Connection: Upgrade\r\n"));
		}
	}

	if (LI_HTTP_METHOD_GET != vr->request.http_method && LI_HTTP_METHOD_HEAD != vr->request.http_method) {
		g_string_append_printf(head, "Content-Length: %" LI_GOFFSET_MODIFIER "i\r\n", vr->request.content_length);
	}

	for (iter = g_queue_peek_head_link(&vr->request.headers->entries); iter; iter = g_list_next(iter)) {
		header = (liHttpHeader*) iter->data;
		if (li_http_header_key_is(header, CONST_STR_LEN("Content-Length"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("Transfer-Encoding"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("TE"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("Connection"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("Proxy-Connection"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("X-Forwarded-Proto"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("X-Forwarded-For"))) continue;
		g_string_append_len(head, GSTR_LEN(header->data));
		g_string_append_len(head, CONST_STR_LEN("\r\n"));
	}

	g_string_append_len(head, CONST_STR_LEN("X-Forwarded-For: "));
	g_string_append_len(head, GSTR_LEN(vr->coninfo->remote_addr_str));
	g_string_append_len(head, CONST_STR_LEN("\r\n"));

	if (vr->coninfo->is_ssl) {
		g_string_append_len(head, CONST_STR_LEN("X-Forwarded-Proto: https\r\n"));
	} else {
		g_string_append_len(head, CONST_STR_LEN("X-Forwarded-Proto: http\r\n"));
	}

	/* terminate http header */
	g_string_append_len(head, CONST_STR_LEN("\r\n"));

	li_chunkqueue_append_string(out, head);
}
Ejemplo n.º 25
0
void
mkp_project_enumerate_targets (MkpProject *project, AnjutaProjectNode *parent)
{
    GHashTableIter iter;
    gpointer key;
    MkpRule *rule;

    /* Check pattern rules */
    for (g_hash_table_iter_init (&iter, project->rules); g_hash_table_iter_next (&iter, (gpointer)&key, (gpointer)&rule);)
    {
        if (rule->phony) continue;

        if (g_hash_table_lookup (project->suffix, rule->name))
        {
            /* Single suffix rule */
            rule->pattern = TRUE;
            rule->part = NULL;
        }
        else
        {
            GString *pattern = g_string_sized_new (16);
            GList *suffix;
            GList *src;

            /* Check double suffix rule */
            suffix = g_hash_table_get_keys (project->suffix);

            for (src = g_list_first (suffix); src != NULL; src = g_list_next (src))
            {
                GList *obj;

                for (obj = g_list_first (suffix); obj != NULL; obj = g_list_next (obj))
                {
                    g_string_assign (pattern, src->data);
                    g_string_append (pattern, obj->data);

                    if (strcmp (pattern->str, rule->name) == 0)
                    {
                        rule->pattern = TRUE;
                        rule->part = rule->name + strlen (src->data);
                        break;
                    }
                }
                if (rule->pattern) break;
            }

            g_string_free (pattern, TRUE);
            g_list_free (suffix);
        }
    }

    /* Create new target */
    for (g_hash_table_iter_init (&iter, project->rules); g_hash_table_iter_next (&iter, (gpointer)&key, (gpointer)&rule);)
    {
        MkpTarget *target;
        AnjutaToken *prerequisite;
        AnjutaToken *arg;

        //g_message ("rule =%s=", rule->name);
        if (rule->phony || rule->pattern) continue;

        /* Create target */
        target = MKP_TARGET(mkp_target_new (rule->name, ANJUTA_PROJECT_UNKNOWN));
        mkp_target_add_token (target, rule->rule);
        anjuta_project_node_append (parent, ANJUTA_PROJECT_NODE(target));

        /* Get prerequisite */
        prerequisite = anjuta_token_first_word (rule->rule);
        if (prerequisite != NULL) prerequisite = anjuta_token_next_word (prerequisite);
        if (prerequisite != NULL) prerequisite = anjuta_token_next_word (prerequisite);

        /* Add prerequisite */
        for (arg = anjuta_token_first_word (prerequisite); arg != NULL; arg = anjuta_token_next_word (arg))
        {
            AnjutaProjectNode *node;
            gchar *name;
            GList *dependencies;

            name = anjuta_token_evaluate (arg);
            if (name != NULL)
            {
                name = g_strstrip (name);
                dependencies = mkp_project_find_dependencies (project, name, parent, 0);
                if (dependencies == NULL)
                {
                    /* Add only one object node */
                    node = mkp_object_new (name);
                    node->type = ANJUTA_PROJECT_OBJECT | ANJUTA_PROJECT_PROJECT;
                    anjuta_project_node_append (ANJUTA_PROJECT_NODE(target), ANJUTA_PROJECT_NODE(node));
                    g_free (name);
                }
                else
                {
                    GFile *src_file;
                    gchar *name;

                    AnjutaProjectNode *parent = (AnjutaProjectNode *)target;
                    while (g_list_next (dependencies) != NULL)
                    {
                        /* Create object nodes */
                        name = (gchar *)dependencies->data;
                        node = mkp_object_new (name);
                        node->type = ANJUTA_PROJECT_OBJECT | ANJUTA_PROJECT_PROJECT;
                        anjuta_project_node_append (parent, node);
                        g_free (name);
                        parent = node;
                        dependencies = g_list_delete_link (dependencies, dependencies);
                    }

                    /* Create source node */
                    name = (gchar *)dependencies->data;
                    src_file = g_file_get_child (project->root_file, name);
                    node = mkp_source_new (src_file);
                    node->type = ANJUTA_PROJECT_SOURCE | ANJUTA_PROJECT_PROJECT;
                    g_object_unref (src_file);
                    anjuta_project_node_append (parent, node);
                    g_free (name);
                    g_list_free (dependencies);
                }
            }
        }
    }
}
Ejemplo n.º 26
0
/**
 * thunar_dialogs_show_job_ask:
 * @parent   : the parent #GtkWindow or %NULL.
 * @question : the question text.
 * @choices  : possible responses.
 *
 * Utility function to display a question dialog for the ThunarJob::ask
 * signal.
 *
 * Return value: the #ThunarJobResponse.
 **/
ThunarJobResponse
thunar_dialogs_show_job_ask (GtkWindow        *parent,
                             const gchar      *question,
                             ThunarJobResponse choices)
{
  const gchar *separator;
  const gchar *mnemonic;
  GtkWidget   *message;
  GtkWidget   *button;
  GString     *secondary = g_string_sized_new (256);
  GString     *primary = g_string_sized_new (256);
  gint         response;
  gint         n;
  gboolean     has_cancel = FALSE;

  _thunar_return_val_if_fail (parent == NULL || GTK_IS_WINDOW (parent), THUNAR_JOB_RESPONSE_CANCEL);
  _thunar_return_val_if_fail (g_utf8_validate (question, -1, NULL), THUNAR_JOB_RESPONSE_CANCEL);

  /* try to separate the question into primary and secondary parts */
  separator = strstr (question, ": ");
  if (G_LIKELY (separator != NULL))
    {
      /* primary is everything before the colon, plus a dot */
      g_string_append_len (primary, question, separator - question);
      g_string_append_c (primary, '.');

      /* secondary is everything after the colon (skipping whitespace) */
      do
        ++separator;
      while (g_ascii_isspace (*separator));
      g_string_append (secondary, separator);
    }
  else
    {
      /* otherwise separate based on the \n\n */
      separator = strstr (question, "\n\n");
      if (G_LIKELY (separator != NULL))
        {
          /* primary is everything before the newlines */
          g_string_append_len (primary, question, separator - question);

          /* secondary is everything after the newlines (skipping whitespace) */
          while (g_ascii_isspace (*separator))
            ++separator;
          g_string_append (secondary, separator);
        }
      else
        {
          /* everything is primary */
          g_string_append (primary, question);
        }
    }

  /* allocate the question message dialog */
  message = gtk_message_dialog_new (parent,
                                    GTK_DIALOG_MODAL |
                                    GTK_DIALOG_DESTROY_WITH_PARENT,
                                    GTK_MESSAGE_QUESTION,
                                    GTK_BUTTONS_NONE,
                                    "%s", primary->str);
  if (G_LIKELY (*secondary->str != '\0'))
    gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (message), "%s", secondary->str);

  /* add the buttons based on the possible choices */
  for (n = 6; n >= 0; --n)
    {
      /* check if the response is set */
      response = choices & (1 << n);
      if (response == 0)
        continue;

      switch (response)
        {
        case THUNAR_JOB_RESPONSE_YES:
          mnemonic = _("_Yes");
          break;

        case THUNAR_JOB_RESPONSE_YES_ALL:
          mnemonic = _("Yes to _all");
          break;

        case THUNAR_JOB_RESPONSE_NO:
          mnemonic = _("_No");
          break;

        case THUNAR_JOB_RESPONSE_NO_ALL:
          mnemonic = _("N_o to all");
          break;

        case THUNAR_JOB_RESPONSE_RETRY:
          mnemonic = _("_Retry");
          break;

        case THUNAR_JOB_RESPONSE_FORCE:
          mnemonic = _("Copy _Anyway");
          break;

        case THUNAR_JOB_RESPONSE_CANCEL:
          /* cancel is always the last option */
          has_cancel = TRUE;
          continue;

        default:
          g_assert_not_reached ();
          break;
        }

      button = gtk_button_new_with_mnemonic (mnemonic);
      gtk_widget_set_can_default (button, TRUE);
      gtk_dialog_add_action_widget (GTK_DIALOG (message), button, response);
      gtk_widget_show (button);

      gtk_dialog_set_default_response (GTK_DIALOG (message), response);
    }

  if (has_cancel)
    {
      button = gtk_button_new_with_mnemonic (_("_Cancel"));
      gtk_widget_set_can_default (button, TRUE);
      gtk_dialog_add_action_widget (GTK_DIALOG (message), button, GTK_RESPONSE_CANCEL);
      gtk_widget_show (button);
      gtk_dialog_set_default_response (GTK_DIALOG (message), GTK_RESPONSE_CANCEL);
    }

  /* run the question dialog */
  response = gtk_dialog_run (GTK_DIALOG (message));
  gtk_widget_destroy (message);

  /* transform the result as required */
  if (G_UNLIKELY (response <= 0))
    response = THUNAR_JOB_RESPONSE_CANCEL;

  /* cleanup */
  g_string_free (secondary, TRUE);
  g_string_free (primary, TRUE);

  return response;
}
Ejemplo n.º 27
0
/*------------------------------------------------------------------------
 * The user has selected to change their profile.
 *
 *  @param gc		The connection object
 *  @param fields	The fields from the request pop-up
 */
static void mxit_profile_cb( PurpleConnection* gc, PurpleRequestFields* fields )
{
	struct MXitSession*		session	= purple_connection_get_protocol_data( gc );
	PurpleRequestField*		field	= NULL;
	const char*				name	= NULL;
	const char*				bday	= NULL;
	const char*				err		= NULL;
	GList*					entry	= NULL;

	purple_debug_info( MXIT_PLUGIN_ID, "mxit_profile_cb\n" );

	PURPLE_ASSERT_CONNECTION_IS_VALID(gc);

	/* validate name */
	name = purple_request_fields_get_string( fields, "name" );
	if ( ( !name ) || ( strlen( name ) < 3 ) ) {
		err = _( "The Display Name you entered is invalid." );
		goto out;
	}

	/* validate birthdate */
	bday = purple_request_fields_get_string( fields, "bday" );
	if ( ( !bday ) || ( strlen( bday ) < 10 ) || ( !validateDate( bday ) ) ) {
		err = _( "The birthday you entered is invalid. The correct format is: 'YYYY-MM-DD'." );
		goto out;
	}

out:
	if ( !err ) {
		struct MXitProfile*	profile		= session->profile;
		GString*			attributes	= g_string_sized_new( 128 );
		char				attrib[512];
		unsigned int		acount		= 0;


		/* update name */
		g_strlcpy( profile->nickname, name, sizeof( profile->nickname ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_FULLNAME, CP_PROFILE_TYPE_UTF8, profile->nickname );
		g_string_append( attributes, attrib );
		acount++;

		/* update birthday */
		g_strlcpy( profile->birthday, bday, sizeof( profile->birthday ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_BIRTHDATE, CP_PROFILE_TYPE_UTF8, profile->birthday );
		g_string_append( attributes, attrib );
		acount++;

		/* update gender */
		profile->male = ( purple_request_fields_get_choice( fields, "male" ) != 0 );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_GENDER, CP_PROFILE_TYPE_BOOL, ( profile->male ) ? "1" : "0" );
		g_string_append( attributes, attrib );
		acount++;

		/* update title */
		name = purple_request_fields_get_string( fields, "title" );
		if ( !name )
			profile->title[0] = '\0';
		else
			g_strlcpy( profile->title, name, sizeof( profile->title ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_TITLE, CP_PROFILE_TYPE_UTF8, profile->title );
		g_string_append( attributes, attrib );
		acount++;

		/* update firstname */
		name = purple_request_fields_get_string( fields, "firstname" );
		if ( !name )
			profile->firstname[0] = '\0';
		else
			g_strlcpy( profile->firstname, name, sizeof( profile->firstname ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_FIRSTNAME, CP_PROFILE_TYPE_UTF8, profile->firstname );
		g_string_append( attributes, attrib );
		acount++;

		/* update lastname */
		name = purple_request_fields_get_string( fields, "lastname" );
		if ( !name )
			profile->lastname[0] = '\0';
		else
			g_strlcpy( profile->lastname, name, sizeof( profile->lastname ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_LASTNAME, CP_PROFILE_TYPE_UTF8, profile->lastname );
		g_string_append( attributes, attrib );
		acount++;

		/* update email address */
		name = purple_request_fields_get_string( fields, "email" );
		if ( !name )
			profile->email[0] = '\0';
		else
			g_strlcpy( profile->email, name, sizeof( profile->email ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_EMAIL, CP_PROFILE_TYPE_UTF8, profile->email );
		g_string_append( attributes, attrib );
		acount++;

		/* update mobile number */
		name = purple_request_fields_get_string( fields, "mobilenumber" );
		if ( !name )
			profile->mobilenr[0] = '\0';
		else
			g_strlcpy( profile->mobilenr, name, sizeof( profile->mobilenr ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_MOBILENR, CP_PROFILE_TYPE_UTF8, profile->mobilenr );
		g_string_append( attributes, attrib );
		acount++;

		/* update about me */
		name = purple_request_fields_get_string( fields, "aboutme" );
		if ( !name )
			profile->aboutme[0] = '\0';
		else
			g_strlcpy( profile->aboutme, name, sizeof( profile->aboutme ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_ABOUTME, CP_PROFILE_TYPE_UTF8, profile->aboutme );
		g_string_append( attributes, attrib );
		acount++;

		/* update where am i */
		name = purple_request_fields_get_string( fields, "whereami" );
		if ( !name )
			profile->whereami[0] = '\0';
		else
			g_strlcpy( profile->whereami, name, sizeof( profile->whereami ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%s", CP_PROFILE_WHEREAMI, CP_PROFILE_TYPE_UTF8, profile->whereami );
		g_string_append( attributes, attrib );
		acount++;

		/* relationship status */
		field = purple_request_fields_get_field( fields, "relationship" );
		entry = g_list_first( purple_request_field_list_get_selected( field ) );
		profile->relationship = atoi( purple_request_field_list_get_data( field, entry->data ) );
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%i", CP_PROFILE_RELATIONSHIP, CP_PROFILE_TYPE_SHORT, profile->relationship );
		g_string_append( attributes, attrib );
		acount++;

		/* update flags */
		field = purple_request_fields_get_field( fields, "searchable" );
		if ( purple_request_field_bool_get_value( field ) )		/* is searchable -> clear not-searchable flag */
			profile->flags &= ~CP_PROF_NOT_SEARCHABLE;
		else
			profile->flags |= CP_PROF_NOT_SEARCHABLE;
		field = purple_request_fields_get_field( fields, "suggestable" );
		if ( purple_request_field_bool_get_value( field ) )		/* is suggestable -> clear not-suggestable flag */
			profile->flags &= ~CP_PROF_NOT_SUGGESTABLE;
		else
			profile->flags |= CP_PROF_NOT_SUGGESTABLE;
		g_snprintf( attrib, sizeof( attrib ), "\01%s\01%i\01%" G_GINT64_FORMAT, CP_PROFILE_FLAGS, CP_PROFILE_TYPE_LONG, profile->flags);
		g_string_append( attributes, attrib );
		acount++;

		/* send the profile update to MXit */
		mxit_send_extprofile_update( session, NULL, acount, attributes->str );
		g_string_free( attributes, TRUE );
	}
	else {
		/* show error to user */
		mxit_popup( PURPLE_NOTIFY_MSG_ERROR, _( "Profile Update Error" ), err );
	}
}
Ejemplo n.º 28
0
bool bp_script_sign(struct bp_keystore *ks, const GString *fromPubKey,
		    const struct bp_tx *txTo, unsigned int nIn,
		    int nHashType)
{
	if (!txTo || !txTo->vin || nIn >= txTo->vin->len)
		return false;

	struct bp_txin *txin = g_ptr_array_index(txTo->vin, nIn);

	/* get signature hash */
	bu256_t hash;
	bp_tx_sighash(&hash, fromPubKey, txTo, nIn, nHashType);

	/* match fromPubKey against templates, to find what pubkey[hashes]
	 * are required for signing
	 */
	struct bscript_addr addrs;
	if (!bsp_addr_parse(&addrs, fromPubKey->str, fromPubKey->len))
		return false;

	GString *scriptSig = g_string_sized_new(64);
	bool rc = false;
	bu160_t key_id;
	struct buffer *kbuf;

	/* sign, based on script template matched above */
	switch (addrs.txtype) {
	case TX_PUBKEY:
		kbuf = addrs.pub->data;
		bu_Hash160((unsigned char *)&key_id, kbuf->p, kbuf->len);

		if (!sign1(&key_id, ks, &hash, nHashType, scriptSig))
			goto out;
		break;

	case TX_PUBKEYHASH:
		kbuf = addrs.pubhash->data;
		memcpy(&key_id, kbuf->p, kbuf->len);

		if (!sign1(&key_id, ks, &hash, nHashType, scriptSig))
			goto out;
		if (!bkeys_pubkey_append(ks, &key_id, scriptSig))
			goto out;
		break;

	case TX_SCRIPTHASH:		/* TODO; not supported yet */
	case TX_MULTISIG:
		goto out;

	case TX_NONSTANDARD:		/* unknown script type, cannot sign */
		goto out;
	}

	if (txin->scriptSig)
		g_string_free(txin->scriptSig, TRUE);
	txin->scriptSig = scriptSig;
	scriptSig = NULL;
	rc = true;

out:
	if (scriptSig)
		g_string_free(scriptSig, TRUE);
	bsp_addr_free(&addrs);
	return rc;
}
Ejemplo n.º 29
0
char* fm_path_list_to_uri_list(FmPathList* pl)
{
	GString* buf = g_string_sized_new(4096);
	fm_path_list_write_uri_list(pl, buf);
	return g_string_free(buf, FALSE);
}
Ejemplo n.º 30
0
static void
lua_tcp_write_helper (struct lua_tcp_cbdata *cbd)
{
	struct iovec *start;
	guint niov, i;
	gint flags = 0;
	gsize remain;
	gssize r;
	struct iovec *cur_iov;
	struct msghdr msg;

	if (cbd->pos == cbd->total) {
		goto call_finish_handler;
	}

	start = &cbd->iov[0];
	niov = cbd->iovlen;
	remain = cbd->pos;
	/* We know that niov is small enough for that */
	cur_iov = alloca (niov * sizeof (struct iovec));
	memcpy (cur_iov, cbd->iov, niov * sizeof (struct iovec));
	for (i = 0; i < cbd->iovlen && remain > 0; i++) {
		/* Find out the first iov required */
		start = &cur_iov[i];
		if (start->iov_len <= remain) {
			remain -= start->iov_len;
			start = &cur_iov[i + 1];
			niov--;
		}
		else {
			start->iov_base = (void *)((char *)start->iov_base + remain);
			start->iov_len -= remain;
			remain = 0;
		}
	}

	memset (&msg, 0, sizeof (msg));
	msg.msg_iov = start;
	msg.msg_iovlen = MIN (IOV_MAX, niov);
	g_assert (niov > 0);
#ifdef MSG_NOSIGNAL
	flags = MSG_NOSIGNAL;
#endif
	r = sendmsg (cbd->fd, &msg, flags);

	if (r == -1) {
		lua_tcp_push_error (cbd, "IO write error");
		lua_tcp_maybe_free (cbd);
		return;
	}
	else {
		cbd->pos += r;
	}

	if (cbd->pos >= cbd->total) {
		goto call_finish_handler;
	}
	else {
		/* Want to write more */
		event_add (&cbd->ev, &cbd->tv);
	}

	return;

call_finish_handler:

	if (!cbd->partial) {
		cbd->in = g_string_sized_new (BUFSIZ);
		rspamd_mempool_add_destructor (cbd->pool, rspamd_gstring_free_hard,
				cbd->in);
	}

	event_del (&cbd->ev);
	event_set (&cbd->ev, cbd->fd, EV_READ | EV_PERSIST, lua_tcp_handler, cbd);
	event_base_set (cbd->ev_base, &cbd->ev);
	event_add (&cbd->ev, &cbd->tv);
}