gboolean plugin_init(GKeyFile *config, const char *enable, const char *disable) { GSList *list; GDir *dir; const gchar *file; char **conf_disabled, **cli_disabled, **cli_enabled; unsigned int i; /* Make a call to BtIO API so its symbols got resolved before the * plugins are loaded. */ bt_io_error_quark(); if (config) conf_disabled = g_key_file_get_string_list(config, "General", "DisablePlugins", NULL, NULL); else conf_disabled = NULL; if (enable) cli_enabled = g_strsplit_set(enable, ", ", -1); else cli_enabled = NULL; if (disable) cli_disabled = g_strsplit_set(disable, ", ", -1); else cli_disabled = NULL; //+++ BRCM #ifdef BT_ALT_STACK // For BTLA, do not load built in plugins #else DBG("Loading builtin plugins"); for (i = 0; __bluetooth_builtin[i]; i++) { if (!enable_plugin(__bluetooth_builtin[i]->name, conf_disabled, cli_enabled, cli_disabled)) continue; add_plugin(NULL, __bluetooth_builtin[i]); } #endif //--- BRCM if (strlen(PLUGINDIR) == 0) goto start; DBG("Loading plugins %s", PLUGINDIR); dir = g_dir_open(PLUGINDIR, 0, NULL); if (!dir) goto start; while ((file = g_dir_read_name(dir)) != NULL) { struct bluetooth_plugin_desc *desc; void *handle; gchar *filename; //+++ BRCM #ifdef BT_ALT_STACK // For BTLA, only load HID, NETWORK, and HID Device plugin if (strcmp (file, "input.so") != 0 /*&& strcmp (file, "network.so") != 0 && strcmp (file, "hiddevice.so") != 0 */) { info("Skipping plugin %s", file); continue; } #else if (g_str_has_prefix(file, "lib") == TRUE || g_str_has_suffix(file, ".so") == FALSE) continue; #endif //--- BRCM filename = g_build_filename(PLUGINDIR, file, NULL); handle = dlopen(filename, RTLD_NOW); if (handle == NULL) { error("Can't load plugin %s: %s", filename, dlerror()); g_free(filename); continue; } g_free(filename); desc = dlsym(handle, "bluetooth_plugin_desc"); if (desc == NULL) { error("Can't load plugin description: %s", dlerror()); dlclose(handle); continue; } if (!enable_plugin(desc->name, conf_disabled, cli_enabled, cli_disabled)) { dlclose(handle); continue; } if (add_plugin(handle, desc) == FALSE) dlclose(handle); } g_dir_close(dir); start: for (list = plugins; list; list = list->next) { struct bluetooth_plugin *plugin = list->data; if (plugin->desc->init() < 0) { error("Failed to init %s plugin", plugin->desc->name); continue; } plugin->active = TRUE; } g_strfreev(conf_disabled); g_strfreev(cli_enabled); g_strfreev(cli_disabled); return TRUE; }
void read_proc_stat() { GError *gerror = NULL; char *contents = NULL; gsize len; int n; gchar **arr_file, **arr_line; char *path = "/proc/stat"; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { g_critical("%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } } arr_file = g_strsplit_set(contents,"\n", -1); int newlines = g_strv_length(arr_file) - 1; char* ctxt=NULL; char* procs_running = NULL; for(n=0; n < newlines ; n++) { arr_line = g_strsplit_set(arr_file[n], " ", -1); if(!g_strcmp0(arr_line[0],"ctxt")) { ctxt = g_strdup(arr_line[1]); } if(!g_strcmp0(arr_line[0],"procs_running")) { procs_running = g_strdup(arr_line[1]); } g_strfreev(arr_line); } arr_line = g_strsplit(arr_file[0], " ", -1); // cpu0 g_message("%s_stat: u:%s ulp:%s sys:%s i:%s iow:%s int:%s sint:%s cs:%s pr:%s", //path, arr_line[0], arr_line[2], // arr_line[1] is an empty string arr_line[3], arr_line[4], arr_line[5], arr_line[6], arr_line[7], arr_line[8], ctxt, procs_running ); g_strfreev(arr_line); g_free(ctxt); g_free(procs_running); g_strfreev(arr_file); g_free(contents); }
/* Converts the string representation of a command into it's internal representation, or * NULL on failure. */ TIL_Cmd * cmdFromString (gchar * str) { Mapping cmdMap[] = { {"move", TIL_Cmd_Move}, {"cursor", TIL_Cmd_Cursor}, {"select", TIL_Cmd_Select}, {"search", TIL_Cmd_Search}, {"delete", TIL_Cmd_Delete}, {"insert", TIL_Cmd_Insert}, {"replace", TIL_Cmd_Replace}, {"copy", TIL_Cmd_Copy}, {"undo", TIL_Cmd_Undo}, {"redo", TIL_Cmd_Redo}, {"override", TIL_Cmd_Override}, {"indent", TIL_Cmd_Indent}, {"complete", TIL_Cmd_Complete}, {"format", TIL_Cmd_Format}, {"open", TIL_Cmd_Open}, {"status", TIL_Cmd_Status}, {NULL, TIL_Cmd_Unknown}, }; TIL_Cmd *cmd = NULL; g_strstrip (str); gchar **words = g_strsplit_set (str, " \t", -1); TIL_CmdID id = TIL_Cmd_Unknown; if (words[0] != NULL) id = (TIL_CmdID) map (cmdMap, words[0]); switch (id) { case TIL_Cmd_Move: { Mapping entityMap[] = { {"row", TIL_Cmd_Move_Row}, {"line", TIL_Cmd_Move_Line}, {"col", TIL_Cmd_Move_Column}, {"char", TIL_Cmd_Move_Character}, {"word", TIL_Cmd_Move_Word}, {"sent", TIL_Cmd_Move_Sentence}, {"block", TIL_Cmd_Move_Block}, {"par", TIL_Cmd_Move_Paragraph}, {"page", TIL_Cmd_Move_Page}, {"doc", TIL_Cmd_Move_Doc}, {NULL, -1}, }; Mapping flagsMap[] = { {"back", TIL_Cmd_Move_Backwards}, {"end", TIL_Cmd_Move_EndOf}, {"abs", TIL_Cmd_Move_Absolute}, {"nowrap", TIL_Cmd_Move_NoLineWrap}, {"screen", TIL_Cmd_Move_Screen}, {NULL, 0}, }; int i=1; TIL_Cmd_Move_Args args = { TIL_Cmd_Move_Row, 1, 0 }; if (words[i] == NULL) goto out; /* try to read the entity count */ if (sscanf (words[i], "%d", &args.count) > 0) i++; if (words[i] == NULL) goto out; args.entity = (TIL_Cmd_Move_Entity) map (entityMap, words[i]); i++; if (words[i] != NULL) { /* the flags */ gchar **flags = g_strsplit (words[i], "|", -1); gboolean error = FALSE; for (int j = 0; flags[j] != NULL; j++) { int flag = map (flagsMap, flags[j]); if (flag == 0) error = TRUE; else args.flags |= flag; } g_strfreev (flags); if (error) goto out; /* if there are additional parameters, go out */ if (words[i+1] != NULL) goto out; } /* allocate the command and init it with the args */ cmd = til_createCmd (id, &args, sizeof (args)); } break; case TIL_Cmd_Cursor: { Mapping shapeMap[] = { {"line", TIL_Cmd_Cursor_Line}, {"block", TIL_Cmd_Cursor_Block}, {NULL, -1}, }; if (words[1] == NULL) goto out; TIL_Cmd_Cursor_Args args; args.shape = (TIL_Cmd_Cursor_Shape) map (shapeMap, words[1]); if ((int) args.shape < 0) goto out; if (words[2] != NULL) goto out; /* allocate the command and init it with the args */ cmd = til_createCmd (id, &args, sizeof (args)); } break; case TIL_Cmd_Select: { Mapping modeMap[] = { {"none", TIL_Cmd_Select_None}, {"def", TIL_Cmd_Select_Default}, {"norm", TIL_Cmd_Select_Normal}, {"line", TIL_Cmd_Select_Line}, {"block", TIL_Cmd_Select_Block}, {NULL, -1}, }; TIL_Cmd_Select_Args args = { TIL_Cmd_Select_Default }; if (words[1] != NULL) { args.mode = (TIL_Cmd_Select_Mode) map (modeMap, words[1]); if ((int) args.mode < 0) goto out; if (words[2] != NULL) goto out; } /* allocate the command and init it with the args */ cmd = til_createCmd (id, &args, sizeof (args)); } break; case TIL_Cmd_Search: break; case TIL_Cmd_Delete: /* delete takes no args */ if (words[1] != NULL) goto out; cmd = til_createCmd (id, NULL, 0); break; case TIL_Cmd_Insert: case TIL_Cmd_Replace: { gboolean clipboard = TRUE; gchar *text = NULL; if (words[1] != NULL) { if (g_str_has_prefix (words[1], "c")) { /* clipboard */ if (words[2] != NULL) goto out; } else if (g_str_has_prefix (words[1], "t")) { /* text */ if (words[2] == NULL || words[3] != NULL) goto out; clipboard = FALSE; text = unescapeText (words[2]); } else goto out; } size_t size = sizeof(TIL_Cmd) + sizeof(TIL_Cmd_Insert_Args) + (text != NULL ? (strlen (text) + 1) : 0); cmd = g_malloc (size); cmd->size = size; cmd->id = id; ((TIL_Cmd_Insert_Args*) cmd->args)->clipboard = clipboard; if (text != NULL) { strcpy (((TIL_Cmd_Insert_Args*) cmd->args)->text, text); g_free (text); } } break; case TIL_Cmd_Copy: break; case TIL_Cmd_Undo: break; case TIL_Cmd_Redo: break; case TIL_Cmd_Override: { Mapping modeMap[] = { {"on", 1}, {"off", 0}, {NULL, -1}, }; if (words[1] == NULL) goto out; int flag = map (modeMap, words[1]); if (flag < 0) goto out; gboolean overrideOn = flag; if (words[2] != NULL) goto out; /* allocate the command and init it with the args */ cmd = til_createCmd (id, &overrideOn, sizeof (gboolean)); } break; case TIL_Cmd_Indent: break; case TIL_Cmd_Complete: break; case TIL_Cmd_Format: break; case TIL_Cmd_Open: break; case TIL_Cmd_Status: break; case TIL_Cmd_Unknown: goto out; } out: g_strfreev (words); return cmd; }
static gboolean ui_to_setting (CEPageIP4 *self, GError **error) { CEPageIP4Private *priv = CE_PAGE_IP4_GET_PRIVATE (self); GtkTreeModel *model; GtkTreeIter tree_iter; int int_method = IP4_METHOD_AUTO; const char *method; GPtrArray *tmp_array = NULL; char **dns_servers = NULL; char **search_domains = NULL; GPtrArray *addresses = NULL; char *gateway = NULL; gboolean valid = FALSE, iter_valid; const char *text; gboolean ignore_auto_dns = FALSE; const char *dhcp_client_id = NULL; char **items = NULL, **iter; gboolean may_fail = FALSE; /* Method */ if (gtk_combo_box_get_active_iter (priv->method, &tree_iter)) { gtk_tree_model_get (GTK_TREE_MODEL (priv->method_store), &tree_iter, METHOD_COL_NUM, &int_method, -1); } switch (int_method) { case IP4_METHOD_LINK_LOCAL: method = NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL; break; case IP4_METHOD_MANUAL: method = NM_SETTING_IP4_CONFIG_METHOD_MANUAL; break; case IP4_METHOD_SHARED: method = NM_SETTING_IP4_CONFIG_METHOD_SHARED; break; case IP4_METHOD_DISABLED: method = NM_SETTING_IP4_CONFIG_METHOD_DISABLED; break; case IP4_METHOD_AUTO_ADDRESSES: ignore_auto_dns = TRUE; /* fall through */ default: method = NM_SETTING_IP4_CONFIG_METHOD_AUTO; break; } /* IP addresses */ model = gtk_tree_view_get_model (priv->addr_list); iter_valid = gtk_tree_model_get_iter_first (model, &tree_iter); addresses = g_ptr_array_sized_new (1); while (iter_valid) { char *addr = NULL, *netmask = NULL, *addr_gw = NULL; NMIPAddress *nm_addr; guint32 prefix; gtk_tree_model_get (model, &tree_iter, COL_ADDRESS, &addr, COL_PREFIX, &netmask, COL_GATEWAY, &addr_gw, -1); if ( !addr || !nm_utils_ipaddr_valid (AF_INET, addr) || is_address_unspecified (addr)) { g_set_error (error, NMA_ERROR, NMA_ERROR_GENERIC, _("IPv4 address \"%s\" invalid"), addr ? addr : ""); g_free (addr); g_free (netmask); g_free (addr_gw); goto out; } if (!parse_netmask (netmask, &prefix)) { g_set_error (error, NMA_ERROR, NMA_ERROR_GENERIC, _("IPv4 address netmask \"%s\" invalid"), netmask ? netmask : ""); g_free (addr); g_free (netmask); g_free (addr_gw); goto out; } /* Gateway is optional... */ if (addr_gw && *addr_gw && !nm_utils_ipaddr_valid (AF_INET, addr_gw)) { g_set_error (error, NMA_ERROR, NMA_ERROR_GENERIC, _("IPv4 gateway \"%s\" invalid"), addr_gw); g_free (addr); g_free (netmask); g_free (addr_gw); goto out; } nm_addr = nm_ip_address_new (AF_INET, addr, prefix, NULL); g_ptr_array_add (addresses, nm_addr); if (addresses->len == 1 && addr_gw && *addr_gw) { gateway = addr_gw; addr_gw = NULL; } g_free (addr); g_free (netmask); g_free (addr_gw); iter_valid = gtk_tree_model_iter_next (model, &tree_iter); } /* Don't pass empty array to the setting */ if (!addresses->len) { g_ptr_array_free (addresses, TRUE); addresses = NULL; } /* DNS servers */ tmp_array = g_ptr_array_new (); text = gtk_entry_get_text (GTK_ENTRY (priv->dns_servers)); if (text && strlen (text)) { items = g_strsplit_set (text, ", ;:", 0); for (iter = items; *iter; iter++) { struct in_addr tmp_addr; char *stripped = g_strstrip (*iter); if (!*stripped) continue; if (inet_pton (AF_INET, stripped, &tmp_addr)) g_ptr_array_add (tmp_array, g_strdup (stripped)); else { g_set_error (error, NMA_ERROR, NMA_ERROR_GENERIC, _("IPv4 DNS server \"%s\" invalid"), stripped); g_strfreev (items); g_ptr_array_free (tmp_array, TRUE); goto out; } } g_strfreev (items); } g_ptr_array_add (tmp_array, NULL); dns_servers = (char **) g_ptr_array_free (tmp_array, FALSE); /* Search domains */ tmp_array = g_ptr_array_new (); text = gtk_entry_get_text (GTK_ENTRY (priv->dns_searches)); if (text && strlen (text)) { items = g_strsplit_set (text, ", ;:", 0); for (iter = items; *iter; iter++) { char *stripped = g_strstrip (*iter); if (strlen (stripped)) g_ptr_array_add (tmp_array, g_strdup (stripped)); } g_strfreev (items); } g_ptr_array_add (tmp_array, NULL); search_domains = (char **) g_ptr_array_free (tmp_array, FALSE); /* DHCP client ID */ if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO)) { dhcp_client_id = gtk_entry_get_text (priv->dhcp_client_id); if (dhcp_client_id && !strlen (dhcp_client_id)) dhcp_client_id = NULL; } may_fail = !gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (priv->ip4_required)); /* Update setting */ g_object_set (priv->setting, NM_SETTING_IP_CONFIG_METHOD, method, NM_SETTING_IP_CONFIG_ADDRESSES, addresses, NM_SETTING_IP_CONFIG_GATEWAY, gateway, NM_SETTING_IP_CONFIG_DNS, dns_servers, NM_SETTING_IP_CONFIG_DNS_SEARCH, search_domains, NM_SETTING_IP_CONFIG_IGNORE_AUTO_DNS, ignore_auto_dns, NM_SETTING_IP4_CONFIG_DHCP_CLIENT_ID, dhcp_client_id, NM_SETTING_IP_CONFIG_MAY_FAIL, may_fail, NULL); valid = TRUE; out: if (addresses) { g_ptr_array_foreach (addresses, (GFunc) free_one_addr, NULL); g_ptr_array_free (addresses, TRUE); } g_free (gateway); g_strfreev (dns_servers); g_strfreev (search_domains); return valid; }
static struct messages_message *pull_message_data(const char **reply) { struct messages_message *data = g_new0(struct messages_message, 1); data->handle = g_strdup(reply[MESSAGE_HANDLE] + MESSAGE_HANDLE_PREFIX_LEN); if (strlen(reply[MESSAGE_SUBJECT]) != 0) data->subject = g_strdup(reply[MESSAGE_SUBJECT]); else data->subject = g_strdup(reply[MESSAGE_CONTENT]); data->mask |= PMASK_SUBJECT; if (strlen(reply[MESSAGE_SDATE]) != 0) { char **date = g_strsplit_set(reply[MESSAGE_SDATE], ":-Z", -1); data->datetime = g_strjoinv(NULL, date); g_strfreev(date); } else if (strlen(reply[MESSAGE_RDATE]) != 0) { char **date = g_strsplit_set(reply[MESSAGE_RDATE], ":-Z", -1); data->datetime = g_strjoinv(NULL, date); g_strfreev(date); } else { data->datetime = g_strdup(""); } data->mask |= PMASK_DATETIME; data->sender_name = merge_names(reply[MESSAGE_FROM_N], reply[MESSAGE_FROM_LASTN]); data->mask |= PMASK_SENDER_NAME; data->sender_addressing = g_strdup(reply[MESSAGE_FROM_PHONE]); data->mask |= PMASK_SENDER_ADDRESSING; data->recipient_name = merge_names(reply[MESSAGE_TO_N], reply[MESSAGE_TO_LASTN]); data->mask |= PMASK_RECIPIENT_NAME; data->recipient_addressing = g_strdup(reply[MESSAGE_TO_PHONE]); data->mask |= PMASK_RECIPIENT_ADDRESSING; data->type = g_strdup("SMS_GSM"); data->mask |= PMASK_TYPE; data->size = g_strdup_printf("%d", strlen(reply[MESSAGE_CONTENT]) + BMESSAGE_BASE_LEN); data->mask |= PMASK_SIZE; data->text = TRUE; data->mask |= PMASK_TEXT; data->reception_status = g_strdup("complete"); data->mask |= PMASK_RECEPTION_STATUS; data->attachment_size = g_strdup("0"); data->mask |= PMASK_ATTACHMENT_SIZE; data->priority = FALSE; data->mask |= PMASK_PRIORITY; data->read = g_strcmp0(reply[MESSAGE_READ], "true") == 0 ? TRUE : FALSE; data->mask |= PMASK_READ; data->sent = g_strcmp0(reply[MESSAGE_SENT], "true") == 0 ? TRUE : FALSE; data->mask |= PMASK_SENT; data->protect = FALSE; data->mask |= PMASK_PROTECTED; return data; }
static void clipboard_received_cb (GtkClipboard *clipboard, GtkSelectionData *selection_data, gpointer user_data) { PasteData *paste_data = user_data; GthBrowser *browser = paste_data->browser; const char *raw_data; char **clipboard_data; int i; GtkTreePath *path; int position; GthTask *task; raw_data = (const char *) gtk_selection_data_get_data (selection_data); if (raw_data == NULL) { paste_data_free (paste_data); return; } clipboard_data = g_strsplit_set (raw_data, "\n\r", -1); if ((clipboard_data == NULL) || (clipboard_data[0] == NULL)) { g_strfreev (clipboard_data); paste_data_free (paste_data); return; } paste_data->cut = strcmp (clipboard_data[0], "cut") == 0; paste_data->files = NULL; for (i = 1; clipboard_data[i] != NULL; i++) if (strcmp (clipboard_data[i], "") != 0) paste_data->files = g_list_prepend (paste_data->files, g_file_new_for_uri (clipboard_data[i])); paste_data->files = g_list_reverse (paste_data->files); paste_data->file_source = gth_main_get_file_source (paste_data->destination->file); if (paste_data->cut && ! gth_file_source_can_cut (paste_data->file_source, paste_data->files->data)) { GtkWidget *dialog; int response; dialog = _gtk_message_dialog_new (GTK_WINDOW (browser), GTK_DIALOG_MODAL, _GTK_ICON_NAME_DIALOG_QUESTION, _("Could not move the files"), _("Files cannot be moved to the current location, as alternative you can choose to copy them."), _GTK_LABEL_CANCEL, GTK_RESPONSE_CANCEL, _("Copy"), GTK_RESPONSE_OK, NULL); response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); if (response == GTK_RESPONSE_CANCEL) { paste_data_free (paste_data); return; } paste_data->cut = FALSE; } position = -1; path = gth_file_selection_get_last_selected (GTH_FILE_SELECTION (gth_browser_get_file_list_view (browser))); if (path != NULL) { int *indices; indices = gtk_tree_path_get_indices (path); if (indices != NULL) position = indices[0] + 1; gtk_tree_path_free (path); } task = gth_copy_task_new (paste_data->file_source, paste_data->destination, paste_data->cut, paste_data->files, position); gth_browser_exec_task (browser, task, GTH_TASK_FLAGS_DEFAULT); g_object_unref (task); paste_data_free (paste_data); }
/* Warning: qq_connect_later destory all connection * Any function should be care of use qq_data after call this function * Please conside tcp_pending and udp_pending */ gboolean qq_connect_later(gpointer data) { PurpleConnection *gc; char *tmp_server; int port; gchar **segments; qq_data *qd; gc = (PurpleConnection *) data; g_return_val_if_fail(gc != NULL && gc->proto_data != NULL, FALSE); qd = (qq_data *) gc->proto_data; tmp_server = NULL; if (qd->check_watcher > 0) { purple_timeout_remove(qd->check_watcher); qd->check_watcher = 0; } qq_disconnect(gc); if (qd->redirect_ip.s_addr != 0) { /* redirect to new server */ tmp_server = g_strdup_printf("%s:%d", inet_ntoa(qd->redirect_ip), qd->redirect_port); qd->servers = g_list_append(qd->servers, tmp_server); qd->curr_server = tmp_server; tmp_server = NULL; qd->redirect_ip.s_addr = 0; qd->redirect_port = 0; qd->connect_retry = QQ_CONNECT_MAX; } if (qd->curr_server == NULL || strlen (qd->curr_server) == 0 || qd->connect_retry <= 0) { if ( set_new_server(qd) != TRUE) { purple_connection_error_reason(gc, PURPLE_CONNECTION_ERROR_NETWORK_ERROR, _("Unable to connect")); return FALSE; } qd->connect_retry = QQ_CONNECT_MAX; } segments = g_strsplit_set(qd->curr_server, ":", 0); tmp_server = g_strdup(segments[0]); if (NULL != segments[1]) { port = atoi(segments[1]); if (port <= 0) { purple_debug_info("QQ", "Port not define in %s, use default.\n", qd->curr_server); port = QQ_DEFAULT_PORT; } } else { purple_debug_info("QQ", "Error splitting server string: %s, setting port to default.\n", qd->curr_server); port = QQ_DEFAULT_PORT; } g_strfreev(segments); qd->connect_retry--; if ( !connect_to_server(gc, tmp_server, port) ) { purple_connection_error_reason(gc, PURPLE_CONNECTION_ERROR_NETWORK_ERROR, _("Unable to connect")); } g_free(tmp_server); tmp_server = NULL; qd->check_watcher = purple_timeout_add_seconds(QQ_CONNECT_CHECK, connect_check, gc); return FALSE; /* timeout callback stops */ }
void Avahi::Heap::ResolverCallback (AvahiServiceResolver *resolver, AvahiIfIndex /*interface*/, AvahiProtocol /*protocol*/, AvahiResolverEvent event, const char * name_, const char * typ, const char * /*domain*/, const char* host_name, const AvahiAddress */*address*/, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags flags) { std::string name; std::string software; std::string presence; std::string status; gchar *url = NULL; AvahiStringList *txt_tmp = NULL; // filter out seeing ourselves // FIXME: doesn't it hide other people on the same box too? if (flags & AVAHI_LOOKUP_RESULT_LOCAL) { avahi_service_resolver_free (resolver); #if DEBUG std::cout << __PRETTY_FUNCTION__ << " LOCAL RESULT" << std::endl; #endif return; } switch (event) { case AVAHI_RESOLVER_FOUND: { #if DEBUG std::cout << __PRETTY_FUNCTION__ << " AVAHI_RESOLVER_FOUND" << std::endl; #endif name = name_; for (txt_tmp = txt; txt_tmp != NULL; txt_tmp = txt_tmp->next) { char *ckey = NULL; char *cvalue = NULL; size_t valsize; if (avahi_string_list_get_pair (txt_tmp, &ckey, &cvalue, &valsize) >= 0) { if (ckey != NULL && cvalue != NULL) { std::string key (ckey); std::string value (cvalue); if (key == "presence") presence = value; else if (key == "status") status = value; else if (key == "software") software = value; } if (ckey != NULL) free (ckey); if (cvalue != NULL) free (cvalue); } } resolver_callback_helper helper(name); visit_presentities (boost::ref (helper)); if (helper.found_presentity ()) { /* known contact has been updated */ presence_received (helper.found_presentity ()->get_uri (), presence); status_received (helper.found_presentity ()->get_uri (), status); } else { /* ok, this is a new contact */ gchar** broken = NULL; broken = g_strsplit_set (typ, "._", 0); boost::shared_ptr<Ekiga::PresenceCore> pcore = presence_core.lock (); if (broken != NULL && broken[0] != NULL && broken[1] != NULL && pcore) { std::set<std::string> groups; groups.insert (_("Neighbours")); url = g_strdup_printf ("%s:neighbour@%s:%d", broken[1], host_name, port); boost::shared_ptr<Ekiga::URIPresentity> presentity (new Ekiga::URIPresentity (pcore, name, url, groups)); status_received (url, status); presence_received (url, presence); add_presentity (presentity); g_free (url); } g_strfreev (broken); } avahi_service_resolver_free (resolver); break;} case AVAHI_RESOLVER_FAILURE: #if DEBUG std::cout << __PRETTY_FUNCTION__ << " AVAHI_RESOLVER_FAILURE" << std::endl; #endif avahi_service_resolver_free (resolver); break; default: /* shouldn't happen */ #if DEBUG std::cout << __PRETTY_FUNCTION__ << " SHOULDN'T HAPPEN" << std::endl; #endif break; } }
static gboolean skypeweb_uri_handler(const char *proto, const char *cmd, GHashTable *params) { PurpleAccount *account; PurpleConnection *pc; if (!g_str_equal(proto, "skype")) return FALSE; /*skype uri's: skype: //does nothing skype:{buddyname} //open im with {buddyname} skype:{buddynames}?chat //open multi-user chat with {buddynames} skype:?chat&blob={blob id} //open public multi-user chat with the blob id of {blob id} skype:?chat&id={chat id} //open multi-user chat with the id of {chat id} skype:{buddyname}?add //add user to buddy list skype:{buddyname}?userinfo //get buddy's info skype:{buddynames}?call //call {buddynames} skype:{buddyname}?voicemail //send a voice mail message skype:{buddyname}?sendfile //send a file */ account = find_acct(SKYPEWEB_PLUGIN_ID, g_hash_table_lookup(params, "account")); pc = purple_account_get_connection(account); if (g_hash_table_lookup(params, "chat")) { if (cmd && *cmd) { //there'll be a bunch of usernames, seperated by semi-colon if (strchr(cmd, ';')) { gchar **users = g_strsplit_set(cmd, ";", -1); skypeweb_initiate_chat(purple_connection_get_protocol_data(pc), users[0]); //TODO the other users g_strfreev(users); } else { PurpleIMConversation *imconv; imconv = purple_conversations_find_im_with_account(cmd, account); if (!imconv) { imconv = purple_im_conversation_new(account, cmd); } purple_conversation_present(PURPLE_CONVERSATION(imconv)); } } else { //probably a public multi-user chat? GHashTable *chatinfo = NULL; if (g_hash_table_lookup(params, "id")) { chatinfo = skypeweb_chat_info_defaults(pc, g_hash_table_lookup(params, "id")); } else if (g_hash_table_lookup(params, "blob")) { chatinfo = skypeweb_chat_info_defaults(pc, g_hash_table_lookup(params, "blob")); } if (chatinfo != NULL) { skypeweb_join_chat(pc, chatinfo); g_hash_table_destroy(chatinfo); } } } else if (g_hash_table_lookup(params, "add")) { purple_blist_request_add_buddy(account, cmd, "Skype", g_hash_table_lookup(params, "displayname")); return TRUE; } else if (g_hash_table_lookup(params, "call")) { } else if (g_hash_table_lookup(params, "userinfo")) { skypeweb_get_info(pc, cmd); return TRUE; } else if (g_hash_table_lookup(params, "voicemail")) { } else if (g_hash_table_lookup(params, "sendfile")) { } else if (strlen(cmd)) { //supposed to be the same as call? } //we don't know how to handle this return FALSE; }
char * nm_dhcp_dhclient_create_config (const char *interface, NMSettingIP4Config *s_ip4, guint8 *anycast_addr, const char *hostname, const char *orig_path, const char *orig_contents) { GString *new_contents; GPtrArray *alsoreq; int i; new_contents = g_string_new (_("# Created by NetworkManager\n")); alsoreq = g_ptr_array_sized_new (5); if (orig_contents) { char **lines, **line; gboolean in_alsoreq = FALSE; g_string_append_printf (new_contents, _("# Merged from %s\n\n"), orig_path); lines = g_strsplit_set (orig_contents, "\n\r", 0); for (line = lines; lines && *line; line++) { char *p = *line; if (!strlen (g_strstrip (p))) continue; /* Override config file "dhcp-client-id" and use one from the * connection. */ if ( s_ip4 && nm_setting_ip4_config_get_dhcp_client_id (s_ip4) && !strncmp (p, CLIENTID_TAG, strlen (CLIENTID_TAG))) continue; /* Override config file hostname and use one from the connection */ if (hostname && !strncmp (p, HOSTNAME_TAG, strlen (HOSTNAME_TAG))) continue; /* Check for "also require" */ if (!strncmp (p, ALSOREQ_TAG, strlen (ALSOREQ_TAG))) { in_alsoreq = TRUE; p += strlen (ALSOREQ_TAG); } if (in_alsoreq) { char **areq, **aiter; /* Grab each 'also require' option and save for later */ areq = g_strsplit_set (p, "\t ,", -1); for (aiter = areq; aiter && *aiter; aiter++) { if (!strlen (g_strstrip (*aiter))) continue; if (*aiter[0] == ';') { /* all done */ in_alsoreq = FALSE; break; } if (!g_ascii_isalnum ((*aiter)[0])) continue; if ((*aiter)[strlen (*aiter) - 1] == ';') { /* Remove the EOL marker */ (*aiter)[strlen (*aiter) - 1] = '\0'; in_alsoreq = FALSE; } add_also_request (alsoreq, *aiter); } if (areq) g_strfreev (areq); continue; } /* Existing configuration line is OK, add it to new configuration */ g_string_append (new_contents, *line); g_string_append_c (new_contents, '\n'); } if (lines) g_strfreev (lines); } else g_string_append_c (new_contents, '\n'); /* Add NM options from connection */ if (s_ip4) { const char *tmp; gboolean added = FALSE; tmp = nm_setting_ip4_config_get_dhcp_client_id (s_ip4); if (tmp) { gboolean is_octets = TRUE; const char *p = tmp; while (*p) { if (!g_ascii_isxdigit (*p) && (*p != ':')) { is_octets = FALSE; break; } p++; } /* If the client ID is just hex digits and : then don't use quotes, * because dhclient expects either a quoted ASCII string, or a byte * array formated as hex octets separated by : */ if (is_octets) g_string_append_printf (new_contents, CLIENTID_FORMAT_OCTETS "\n", tmp); else g_string_append_printf (new_contents, CLIENTID_FORMAT "\n", tmp); added = TRUE; } if (hostname) { char *plain_hostname, *dot; plain_hostname = g_strdup (hostname); dot = strchr (plain_hostname, '.'); /* get rid of the domain */ if (dot) *dot = '\0'; g_string_append_printf (new_contents, HOSTNAME_FORMAT "\n", plain_hostname); added = TRUE; g_free (plain_hostname); } if (added) g_string_append_c (new_contents, '\n'); } /* Define options for classless static routes */ g_string_append (new_contents, "option rfc3442-classless-static-routes code 121 = array of unsigned integer 8;\n"); g_string_append (new_contents, "option ms-classless-static-routes code 249 = array of unsigned integer 8;\n"); /* Web Proxy Auto-Discovery option (bgo #368423) */ g_string_append (new_contents, "option wpad code 252 = string;\n"); g_string_append_c (new_contents, '\n'); /* Everything we want to request from the DHCP server */ add_also_request (alsoreq, "rfc3442-classless-static-routes"); add_also_request (alsoreq, "ms-classless-static-routes"); add_also_request (alsoreq, "wpad"); add_also_request (alsoreq, "ntp-servers"); /* And add it to the dhclient configuration */ for (i = 0; i < alsoreq->len; i++) { char *t = g_ptr_array_index (alsoreq, i); g_string_append_printf (new_contents, "also request %s;\n", t); g_free (t); } g_ptr_array_free (alsoreq, TRUE); g_string_append_c (new_contents, '\n'); if (anycast_addr) { g_string_append_printf (new_contents, "interface \"%s\" {\n" " initial-interval 1; \n" " anycast-mac ethernet %02x:%02x:%02x:%02x:%02x:%02x;\n" "}\n", interface, anycast_addr[0], anycast_addr[1], anycast_addr[2], anycast_addr[3], anycast_addr[4], anycast_addr[5]); } return g_string_free (new_contents, FALSE); }
/** This function is called to create/update the users ~/.gconf.path * file to point at the location of the gnucash schema files. It * should add two lines to the file. The first points at the user's * local .gconf directory and the second points at gnucash. If this * isn't done then all the gnucash keys end up being interpreted as * read-only keys and the user isn't allowed to change anything. * * This function first checks to file to see if the ~/.gconf line * already exists in the path file. If so, it won't add it a second * time. The function then adds the one or two needed lines to the * end of the file. Any errors are reported to the caller. * * @param error This argument points to a location where error * information can be stored. It is updated if there is a problem * executing the command. * * @return This functions returns TRUE if all the steps needed to * update the users ~/.gconf.path file were able to complete * successfully. It returns FALSE otherwise. */ static gboolean assistant_gconf_update_path (GError **error) { gchar *path_filename, *data_filename; gchar *contents, **lines, *line; gboolean found_user_dir = FALSE; FILE *output; gchar *gconfdir; data_filename = g_build_filename(g_get_home_dir(), ".gconf", (char *)NULL); path_filename = g_build_filename(g_get_home_dir(), ".gconf.path", (char *)NULL); if (g_file_test(path_filename, G_FILE_TEST_EXISTS)) { if (!g_file_get_contents(path_filename, &contents, NULL, error)) { g_free(path_filename); g_free(data_filename); return FALSE; } lines = g_strsplit_set(contents, "\r\n", -1); for (line = *lines; line; line++) { if (line[0] == '#') continue; if ((strstr(line, "$(HOME)/.gconf") == 0) || (strstr(line, "~/.gconf") == 0) || (strstr(line, data_filename))) { found_user_dir = TRUE; break; } } g_strfreev(lines); } output = g_fopen(path_filename, "a"); if (output == NULL) { *error = g_error_new (G_FILE_ERROR, g_file_error_from_errno(errno), "Error opening file %s for writing.", path_filename); g_free(path_filename); g_free(data_filename); return FALSE; } fprintf(output, "\n######## The following lines were added by GnuCash. ########\n"); if (!found_user_dir) fprintf(output, PATH_STRING1); gconfdir = gnc_path_get_gconfdir (TRUE); fprintf(output, PATH_STRING2, gconfdir); g_free (gconfdir); fprintf(output, "############## End of lines added by GnuCash. ##############\n"); if (fclose(output) != 0) { *error = g_error_new (G_FILE_ERROR, g_file_error_from_errno(errno), "Error closing file %s.", path_filename); g_free(path_filename); g_free(data_filename); return FALSE; } g_free(path_filename); g_free(data_filename); return TRUE; }
/* Setup header fields (From:/To:/Date: etc) and message body for the e-mail. * This data is supposed to be sent to libcurl just before any media data. * This function is called once for each e-mail: * 1. we are about the send the first attachment * 2. we have sent all the attachments and continue sending new ones within * a new e-mail (transfer options have been reset). */ static gboolean gst_curl_smtp_sink_set_transfer_options_unlocked (GstCurlBaseSink * bcsink) { GstCurlSmtpSink *sink = GST_CURL_SMTP_SINK (bcsink); GstCurlTlsSinkClass *parent_class; gchar *request_headers; GDateTime *date; gchar *date_str; gchar **tmp_list = NULL; gchar *subject_header = NULL; gchar *message_body = NULL; gchar *rcpt_header = NULL; gchar *enc_rcpt; gchar *from_header = NULL; gchar *enc_from; gint i; CURLcode res; g_assert (sink->payload_headers == NULL); g_assert (sink->mail_rcpt != NULL); g_assert (sink->mail_from != NULL); /* time */ date = g_date_time_new_now_local (); date_str = g_date_time_format (date, "%a %b %e %H:%M:%S %Y %z"); g_date_time_unref (date); /* recipient, sender and subject are all UTF-8 strings, which are additionally * base64-encoded */ /* recipient */ enc_rcpt = generate_encoded_word (sink->mail_rcpt); rcpt_header = g_strdup_printf ("%s <%s>", enc_rcpt, sink->mail_rcpt); g_free (enc_rcpt); /* sender */ enc_from = generate_encoded_word (sink->mail_from); from_header = g_strdup_printf ("%s <%s>", enc_from, sink->mail_from); g_free (enc_from); /* subject */ if (sink->subject != NULL) { subject_header = generate_encoded_word (sink->subject); } /* message */ if (sink->message_body != NULL) { message_body = g_base64_encode ((const guchar *) sink->message_body, strlen (sink->message_body)); } request_headers = g_strdup_printf ( /* headers */ "To: %s\r\n" "From: %s\r\n" "Subject: %s\r\n" "Date: %s\r\n" MIME_VERSION "\r\n" "Content-Type: multipart/mixed; boundary=%s\r\n" "\r\n" /* body headers */ "--" BOUNDARY_STRING "\r\n" "Content-Type: text/plain; charset=utf-8\r\n" "Content-Transfer-Encoding: BASE64\r\n" /* message body */ "\r\n%s\r\n", rcpt_header, from_header, subject_header ? subject_header : "", date_str, BOUNDARY_STRING, message_body ? message_body : ""); sink->payload_headers = g_byte_array_new (); g_byte_array_append (sink->payload_headers, (guint8 *) request_headers, strlen (request_headers)); g_free (date_str); g_free (subject_header); g_free (message_body); g_free (rcpt_header); g_free (from_header); g_free (request_headers); res = curl_easy_setopt (bcsink->curl, CURLOPT_MAIL_FROM, sink->mail_from); if (res != CURLE_OK) { bcsink->error = g_strdup_printf ("failed to set SMTP sender email address: %s", curl_easy_strerror (res)); return FALSE; } if (sink->curl_recipients != NULL) { curl_slist_free_all (sink->curl_recipients); sink->curl_recipients = NULL; } tmp_list = g_strsplit_set (sink->mail_rcpt, MAIL_RCPT_DELIMITER, -1); for (i = 0; i < g_strv_length (tmp_list); i++) { sink->curl_recipients = curl_slist_append (sink->curl_recipients, tmp_list[i]); } g_strfreev (tmp_list); /* note that the CURLOPT_MAIL_RCPT takes a list, not a char array */ res = curl_easy_setopt (bcsink->curl, CURLOPT_MAIL_RCPT, sink->curl_recipients); if (res != CURLE_OK) { bcsink->error = g_strdup_printf ("failed to set SMTP recipient email address: %s", curl_easy_strerror (res)); return FALSE; } res = curl_easy_setopt (bcsink->curl, CURLOPT_UPLOAD, 1L); if (res != CURLE_OK) { bcsink->error = g_strdup_printf ("failed to prepare for upload: %s", curl_easy_strerror (res)); return FALSE; } parent_class = GST_CURL_TLS_SINK_GET_CLASS (sink); if (sink->use_ssl) { return parent_class->set_options_unlocked (bcsink); } return TRUE; }
static void __get_view_properties(xmlNode *node, MgdSchemaTypeAttr *type) { xmlNode *cur; MgdSchemaPropertyAttr *rprop_attr = NULL; gchar *property_name = NULL; for (cur = node->children; cur; cur = cur->next) { if (cur->type == XML_ELEMENT_NODE && g_str_equal(cur->name, "property")) { /* FIXME, add property to reserved words constants */ property_name = NULL; rprop_attr = NULL; xmlChar *name = xmlGetProp(cur, (const xmlChar *)TYPE_RW_NAME); if (!name || (name && *name == '\0')) __view_error(cur, "Can not register view with empty property", NULL); xmlChar *use_prop = xmlGetProp(cur, (const xmlChar *) "use"); /* FIXME, use reserved word */ if (!use_prop || (use_prop && *use_prop == '\0')) __view_error(cur, "Referenced class:property can not be empty", NULL); gchar **rprop = g_strsplit_set ((const gchar *)use_prop, ":.", -1); xmlFree (use_prop); if (!rprop || rprop[0] == NULL || rprop[1] == NULL) { __view_error(cur, "Referenced property can not be empty", NULL); return; } MidgardObjectClass *klass = MIDGARD_OBJECT_GET_CLASS_BY_NAME(rprop[0]); if (!klass) __view_error (cur, "Defined '%s' class is not registered as midagrd_object derived one", rprop[0]); const gchar *table = midgard_core_class_get_table (MIDGARD_DBOBJECT_CLASS (klass)); if (table == NULL) __view_error (cur, "Can not create proper view. Defined '%s' class has NULL storage", rprop[0]); __get_property_attribute (cur, rprop, &property_name, &rprop_attr, MIDGARD_DBOBJECT_CLASS (klass)); midgard_core_schema_type_property_copy(rprop_attr, type); /* TODO, refactor with some usable TypeAttr related API */ /* Create property attributes copy using original property. Then change name. */ MgdSchemaPropertyAttr *prop_attr = g_hash_table_lookup(type->prophash, property_name); if (!prop_attr) g_warning("Can not find %s.%s in newly registered view", type->name, name); if (prop_attr) { g_free((gchar *)prop_attr->name); prop_attr->name = g_strdup((gchar *)name); /* Free old key and remove new one in hash table */ g_hash_table_remove(type->prophash, (gconstpointer) rprop[1]); gchar *property_name = g_strdup ((gchar *)name); g_hash_table_insert(type->prophash, property_name, prop_attr); /* FIXME * Workaround for properties not being registered in the same order as defined * in view xml file */ type->_properties_list = g_slist_append (type->_properties_list, property_name); } g_strfreev(rprop); xmlFree(name); } } }
static void __get_view_joins(xmlNode *node, MgdSchemaTypeAttr *type) { xmlNode *cur; gchar *property_name = NULL; MgdSchemaPropertyAttr *propright = NULL; MgdSchemaPropertyAttr *propleft = NULL; for (cur = node->children; cur; cur = cur->next) { if (cur->type == XML_ELEMENT_NODE && g_str_equal(cur->name, "join")) { /* FIXME, add join to reserved words constants */ property_name = NULL; propright = NULL; propleft = NULL; xmlChar *jointype = xmlGetProp(cur, (const xmlChar *)"type"); if (!jointype || (jointype && *jointype == '\0')) __view_error(cur, "Can not create join with empty type", NULL); if (!midgard_core_xml_attribute_is_allowed(__allowed_joins, jointype)) __view_error(cur, "%s join type is not allowed", jointype); xmlChar *classname = xmlGetProp(cur, (const xmlChar *)"class"); xmlChar *table = NULL; if (!classname || (classname && *classname == '\0')) { table = xmlGetProp(cur, (const xmlChar *) TYPE_RW_TABLE); if (!table) __view_error(cur, "Can not create join. Empty, not defined class or table", NULL); } MidgardDBObjectClass *klass = NULL; MidgardDBObjectClass *joinklass = NULL; if (classname) joinklass = MIDGARD_DBOBJECT_CLASS(MIDGARD_OBJECT_GET_CLASS_BY_NAME((const gchar *)classname)); if (!joinklass) { g_warning ("%s is not registered in GType system", classname); __view_error (cur, "Invalid classname for defined join"); return; } gchar *left = midgard_core_xml_get_child_attribute_content_by_name(cur, "condition", "left"); if (!left) __view_error(cur, "Condition left is missing", NULL); gchar *right = midgard_core_xml_get_child_attribute_content_by_name(cur, "condition", "right"); if (!right) __view_error(cur, "Condition right is missing", NULL); /* Get left property attribute */ gchar **classprop = g_strsplit_set(left, ":.", -1); if (!classprop || classprop[0] == NULL || classprop[1] == NULL) { __view_error(cur, "Condition left problem", NULL); return; } klass = MIDGARD_DBOBJECT_CLASS(MIDGARD_OBJECT_GET_CLASS_BY_NAME((const gchar *)classprop[0])); if (!klass) { __view_error(cur, "Class %s not registered", classprop[0]); return; } MgdSchemaPropertyAttr *propleft = g_hash_table_lookup(klass->dbpriv->storage_data->prophash, classprop[1]); if (!propleft) __view_error(cur, "Property %s not registered for %s", classprop[1], classprop[0]); /* __get_property_attribute (cur, classprop, &property_name, &propleft, klass); */ g_strfreev(classprop); /* Get right property attribute */ classprop = g_strsplit_set(right, ":.", -1); if (!classprop || classprop[0] == NULL || classprop[1] == NULL) { __view_error(cur, "Condition right problem", NULL); return; } klass = MIDGARD_DBOBJECT_CLASS(MIDGARD_OBJECT_GET_CLASS_BY_NAME((const gchar *)classprop[0])); if (!klass) { __view_error(cur, "Class %s not registered", classprop[0]); return; } MgdSchemaPropertyAttr *propright = g_hash_table_lookup(klass->dbpriv->storage_data->prophash, classprop[1]); if (!propright) __view_error(cur, "Property %s not registered for %s", classprop[1], classprop[0]); /* __get_property_attribute (cur, classprop, &property_name, &propright, klass); */ g_strfreev(classprop); MidgardDBJoin *mdbj = midgard_core_dbjoin_new(); mdbj->type = g_utf8_strup((const gchar *)jointype, strlen((gchar *)jointype)); /* configure table, if there's class, get it's table, in other case, get table directly */ if (classname) mdbj->table = g_strdup(midgard_core_class_get_table(joinklass)); else mdbj->table = g_strdup((gchar *)table); mdbj->left = propleft; mdbj->right = propright; g_free(left); g_free(right); type->joins = g_slist_append(type->joins, (gpointer) mdbj); xmlFree(jointype); xmlFree(classname); if (table) xmlFree(table); } } }
/** * recherche des mots séparés par des jokers "%*" dans une chaine * * \param haystack * \param needle * * \return TRUE si trouvé FALSE autrement */ gboolean gsb_string_is_trouve ( const gchar *payee_name, const gchar *needle ) { gchar **tab_str; gchar *tmpstr; gint i; gboolean is_prefix = FALSE, is_suffix = FALSE; if ( g_strstr_len ( needle, -1, "%" ) == NULL && g_strstr_len ( needle, -1, "*" ) == NULL ) { if ( my_strcasecmp ( payee_name, needle ) == 0 ) return TRUE; else return FALSE; } if ( g_str_has_prefix ( needle, "%" ) == FALSE && g_str_has_prefix ( needle, "*" ) == FALSE ) is_prefix = TRUE; if ( g_str_has_suffix ( needle, "%" ) == FALSE && g_str_has_suffix ( needle, "*" ) == FALSE ) is_suffix = TRUE; if ( is_prefix && is_suffix ) { tab_str = g_strsplit_set ( needle, "%*", 0 ); is_prefix = g_str_has_prefix ( payee_name, tab_str[0] ); is_suffix = g_str_has_suffix ( payee_name, tab_str[1] ); if ( is_prefix && is_suffix ) return TRUE; else return FALSE; } else if ( is_prefix && ! is_suffix ) { tmpstr = gsb_string_supprime_joker ( needle ); is_prefix = g_str_has_prefix (payee_name, tmpstr); g_free (tmpstr); return is_prefix; } else if ( is_suffix && ! is_prefix ) { tmpstr = gsb_string_supprime_joker ( needle ); is_suffix = g_str_has_suffix (payee_name, tmpstr); g_free (tmpstr); return is_suffix; } tab_str = g_strsplit_set ( needle, "%*", 0 ); for (i = 0; tab_str[i] != NULL; i++) { if ( tab_str[i] && strlen (tab_str[i]) > 0) { if ( g_strstr_len (payee_name, -1, tab_str[i])) { g_strfreev ( tab_str ); return TRUE; } } } g_strfreev ( tab_str ); return FALSE; }
/** * fwupd_remote_load_from_filename: * @self: A #FwupdRemote * @filename: A filename * @cancellable: the #GCancellable, or %NULL * @error: the #GError, or %NULL * * Sets up the remote ready for use. Most other methods call this * for you, and do you only need to call this if you are just watching * the self. * * Returns: %TRUE for success * * Since: 0.9.3 **/ gboolean fwupd_remote_load_from_filename (FwupdRemote *self, const gchar *filename, GCancellable *cancellable, GError **error) { FwupdRemotePrivate *priv = GET_PRIVATE (self); const gchar *group = "fwupd Remote"; g_autofree gchar *firmware_base_uri = NULL; g_autofree gchar *id = NULL; g_autofree gchar *keyring_kind = NULL; g_autofree gchar *metadata_uri = NULL; g_autofree gchar *order_after = NULL; g_autofree gchar *order_before = NULL; g_autofree gchar *report_uri = NULL; g_autoptr(GKeyFile) kf = NULL; g_return_val_if_fail (FWUPD_IS_REMOTE (self), FALSE); g_return_val_if_fail (filename != NULL, FALSE); g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); g_return_val_if_fail (error == NULL || *error == NULL, FALSE); /* set ID */ id = g_path_get_basename (filename); fwupd_remote_set_id (self, id); /* load file */ kf = g_key_file_new (); if (!g_key_file_load_from_file (kf, filename, G_KEY_FILE_NONE, error)) return FALSE; /* get verification type, falling back to GPG */ keyring_kind = g_key_file_get_string (kf, group, "Keyring", NULL); if (keyring_kind == NULL) { priv->keyring_kind = FWUPD_KEYRING_KIND_GPG; } else { priv->keyring_kind = fwupd_keyring_kind_from_string (keyring_kind); if (priv->keyring_kind == FWUPD_KEYRING_KIND_UNKNOWN) { g_set_error (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Failed to parse type '%s'", keyring_kind); return FALSE; } } /* all remotes need a URI, even if it's file:// to the cache */ metadata_uri = g_key_file_get_string (kf, group, "MetadataURI", error); if (metadata_uri == NULL) return FALSE; if (g_str_has_prefix (metadata_uri, "file://")) { const gchar *filename_cache = metadata_uri; if (g_str_has_prefix (filename_cache, "file://")) filename_cache += 7; fwupd_remote_set_filename_cache (self, filename_cache); if (g_file_test (filename_cache, G_FILE_TEST_IS_DIR)) priv->kind = FWUPD_REMOTE_KIND_DIRECTORY; else priv->kind = FWUPD_REMOTE_KIND_LOCAL; } else if (g_str_has_prefix (metadata_uri, "http://") || g_str_has_prefix (metadata_uri, "https://")) { priv->kind = FWUPD_REMOTE_KIND_DOWNLOAD; } else { g_set_error (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Failed to parse MetadataURI type '%s'", metadata_uri); return FALSE; } /* extract data */ priv->enabled = g_key_file_get_boolean (kf, group, "Enabled", NULL); priv->approval_required = g_key_file_get_boolean (kf, group, "ApprovalRequired", NULL); priv->title = g_key_file_get_string (kf, group, "Title", NULL); /* reporting is optional */ report_uri = g_key_file_get_string (kf, group, "ReportURI", NULL); if (report_uri != NULL && report_uri[0] != '\0') fwupd_remote_set_report_uri (self, report_uri); /* DOWNLOAD-type remotes */ if (priv->kind == FWUPD_REMOTE_KIND_DOWNLOAD) { g_autofree gchar *filename_cache = NULL; g_autofree gchar *username = NULL; g_autofree gchar *password = NULL; /* the client has to download this and the signature */ fwupd_remote_set_metadata_uri (self, metadata_uri); /* check the URI was valid */ if (priv->metadata_uri == NULL) { g_set_error (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Failed to parse URI '%s' in %s", metadata_uri, filename); return FALSE; } /* username and password are optional */ username = g_key_file_get_string (kf, group, "Username", NULL); if (username != NULL) fwupd_remote_set_username (self, username); password = g_key_file_get_string (kf, group, "Password", NULL); if (password != NULL) fwupd_remote_set_password (self, password); /* set cache to /var/lib... */ filename_cache = g_build_filename (LOCALSTATEDIR, "lib", "fwupd", "remotes.d", priv->id, "metadata.xml.gz", NULL); fwupd_remote_set_filename_cache (self, filename_cache); } /* load the checksum */ if (priv->filename_cache_sig != NULL && g_file_test (priv->filename_cache_sig, G_FILE_TEST_EXISTS)) { gsize sz = 0; g_autofree gchar *buf = NULL; g_autoptr(GChecksum) checksum = g_checksum_new (G_CHECKSUM_SHA256); if (!g_file_get_contents (priv->filename_cache_sig, &buf, &sz, error)) { g_prefix_error (error, "failed to get checksum: "); return FALSE; } g_checksum_update (checksum, (guchar *) buf, (gssize) sz); fwupd_remote_set_checksum (self, g_checksum_get_string (checksum)); } else { fwupd_remote_set_checksum (self, NULL); } /* the base URI is optional */ firmware_base_uri = g_key_file_get_string (kf, group, "FirmwareBaseURI", NULL); if (firmware_base_uri != NULL) fwupd_remote_set_firmware_base_uri (self, firmware_base_uri); /* some validation around DIRECTORY types */ if (priv->kind == FWUPD_REMOTE_KIND_DIRECTORY) { if (priv->keyring_kind != FWUPD_KEYRING_KIND_NONE) { g_set_error (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Keyring kind %s is not supported with directory remote", fwupd_keyring_kind_to_string (priv->keyring_kind)); return FALSE; } if (firmware_base_uri != NULL) { g_set_error_literal (error, FWUPD_ERROR, FWUPD_ERROR_INVALID_FILE, "Directory remotes don't support firmware base URI"); return FALSE; } } /* dep logic */ order_before = g_key_file_get_string (kf, group, "OrderBefore", NULL); if (order_before != NULL) priv->order_before = g_strsplit_set (order_before, ",:;", -1); order_after = g_key_file_get_string (kf, group, "OrderAfter", NULL); if (order_after != NULL) priv->order_after = g_strsplit_set (order_after, ",:;", -1); /* success */ fwupd_remote_set_filename_source (self, filename); return TRUE; }
static void cd_sensor_get_sample_stdout_cb (CdSpawn *spawn, const gchar *line, GTask *task) { CdSensorTaskData *data = g_task_get_task_data (task); CdSensorArgyllPrivate *priv = cd_sensor_argyll_get_private (data->sensor); g_autoptr(GError) error = NULL; g_auto(GStrv) parts = NULL; g_debug ("line='%s'", line); /* ready to go, no measurement */ if (g_str_has_prefix (line, "Place instrument on spot to be measured")) { if (priv->pos_required == CD_SENSOR_ARGYLL_POS_UNKNOWN) cd_spawn_send_stdin (spawn, ""); return; } /* got calibration */ if (g_strcmp0 (line, "Calibration complete") == 0) { priv->pos_required = CD_SENSOR_ARGYLL_POS_UNKNOWN; return; } /* got measurement */ if (g_str_has_prefix (line, " Result is XYZ:")) { CdColorXYZ *sample; parts = g_strsplit_set (line, " ,", -1); sample = cd_color_xyz_new (); sample->X = atof (parts[4]); sample->Y = atof (parts[5]); sample->Z = atof (parts[6]); g_task_return_pointer (task, sample, (GDestroyNotify) cd_color_xyz_free); g_object_unref (task); return; } /* failed */ if (g_str_has_prefix (line, "Instrument initialisation failed")) { g_task_return_new_error (task, CD_SENSOR_ERROR, CD_SENSOR_ERROR_INTERNAL, "failed to contact hardware (replug)"); g_object_unref (task); return; } /* need surface */ if (g_strcmp0 (line, "(Sensor should be in surface position)") == 0) { g_task_return_new_error (task, CD_SENSOR_ERROR, CD_SENSOR_ERROR_REQUIRED_POSITION_SURFACE, "Move to surface position"); g_object_unref (task); return; } /* need calibrate */ if (g_str_has_prefix (line, "Set instrument sensor to calibration position,")) { /* just try to read; argyllcms doesn't detect the * sensor position before it asks the user to move the dial... */ if (priv->pos_required == CD_SENSOR_ARGYLL_POS_UNKNOWN) { cd_spawn_send_stdin (spawn, ""); priv->pos_required = CD_SENSOR_ARGYLL_POS_CALIBRATE; return; } g_task_return_new_error (task, CD_SENSOR_ERROR, CD_SENSOR_ERROR_REQUIRED_POSITION_CALIBRATE, "Move to calibration position"); g_object_unref (task); return; } }
static void magnatune_execute_browse(OperationSpec *os) { MagnatuneBuildMediaFn *build_fn; GrlMedia *media = NULL; const gchar *container_id = NULL; gchar *sql = NULL; gchar **touple = NULL; gchar *box_id = NULL; gchar *category_str_id = NULL; gint id = 0; gint num_medias = 0; static GList *iter = NULL; static GList *list_medias = NULL; GError *err = NULL; GRL_DEBUG("magnatune_execute_browse"); container_id = grl_media_get_id(os->container); if (container_id == NULL) { magnatune_browse_root(os); goto end_browse; } touple = g_strsplit_set(container_id, MAGNATUNE_NAME_ID_SEP, 0); id = g_ascii_strtoll(touple[1], NULL, 10); build_fn = build_media_id_name_from_stmt; if (strcmp(touple[0], "root") == 0) { switch (id) { case MAGNATUNE_ARTIST_CAT: category_str_id = g_strdup("artist"); sql = g_strdup_printf(GRL_SQL_ARTISTS_QUERY_ALL, os->count, os->skip); break; case MAGNATUNE_ALBUM_CAT: category_str_id = g_strdup("album"); sql = g_strdup_printf(GRL_SQL_ALBUMS_QUERY_ALL, os->count, os->skip); break; case MAGNATUNE_GENRE_CAT: category_str_id = g_strdup("genre"); sql = g_strdup_printf(GRL_SQL_GENRES_QUERY_ALL, os->count, os->skip); break; } } else if (strcmp(touple[0], "artist") == 0) { category_str_id = g_strdup("album"); sql = g_strdup_printf(GRL_SQL_ALBUMS_BY_ARTIST, id, os->count, os->skip); } else if (strcmp(touple[0], "album") == 0) { category_str_id = g_strdup("track"); sql = g_strdup_printf(GRL_SQL_SONGS_BY_ALBUM, id, os->count, os->skip); build_fn = build_media_track_from_stmt; } else if (strcmp(touple[0], "genre") == 0) { category_str_id = g_strdup("album"); sql = g_strdup_printf(GRL_SQL_ALBUMS_BY_GENRE, id, os->count, os->skip); } else { err = g_error_new(GRL_CORE_ERROR, GRL_CORE_ERROR_BROWSE_FAILED, _("Invalid container identifier %s"), container_id); } g_strfreev(touple); if (sql == NULL || err != NULL) goto end_browse; /* We have the right sql-query, execute */ list_medias = magnatune_sqlite_execute(os, sql, build_fn, &err); g_free(sql); if (list_medias == NULL) goto end_browse; num_medias = g_list_length(list_medias) - 1;; for (iter = list_medias; iter; iter = iter->next) { media = iter->data; box_id = g_strdup_printf("%s-%s", category_str_id, grl_media_get_id(media)); grl_media_set_id(media, box_id); g_free(box_id); os->callback(os->source, os->operation_id, media, num_medias, os->user_data, NULL); num_medias--; } g_list_free(list_medias); end_browse: if (err != NULL) { os->callback(os->source, os->operation_id, NULL, 0, os->user_data, err); g_error_free(err); } g_clear_pointer (&category_str_id, g_free); g_slice_free(OperationSpec, os); }
/** * parse_output_fields: * @field_str: comma-separated field names to parse * @fields_array: array of allowed fields * @parse_groups: whether the fields can contain group prefix (e.g. general.driver) * @group_fields: (out) (allow-none): array of field names for particular groups * @error: (out) (allow-none): location to store error, or %NULL * * Parses comma separated fields in @fields_str according to @fields_array. * When @parse_groups is %TRUE, fields can be in the form 'group.field'. Then * @group_fields will be filled with the required field for particular group. * @group_fields array corresponds to the returned array. * Examples: * @field_str: "type,name,uuid" | "ip4,general.device" | "ip4.address,ip6" * returned array: 2 0 1 | 7 0 | 7 9 * @group_fields: NULL NULL NULL | NULL "device" | "address" NULL * * Returns: #GArray with indices representing fields in @fields_array. * Caller is responsible for freeing the array. */ GArray * parse_output_fields (const char *fields_str, const NmcOutputField fields_array[], gboolean parse_groups, GPtrArray **group_fields, GError **error) { char **fields, **iter; GArray *array; int i, j; g_return_val_if_fail (error == NULL || *error == NULL, NULL); g_return_val_if_fail (group_fields == NULL || *group_fields == NULL, NULL); array = g_array_new (FALSE, FALSE, sizeof (int)); if (parse_groups && group_fields) *group_fields = g_ptr_array_new_full (20, (GDestroyNotify) g_free); /* Split supplied fields string */ fields = g_strsplit_set (fields_str, ",", -1); for (iter = fields; iter && *iter; iter++) { int idx = -1; g_strstrip (*iter); if (parse_groups) { /* e.g. "general.device,general.driver,ip4,ip6" */ gboolean found = FALSE; char *left = *iter; char *right = strchr (*iter, '.'); if (right) *right++ = '\0'; for (i = 0; fields_array[i].name; i++) { if (strcasecmp (left, fields_array[i].name) == 0) { NmcOutputField *valid_names = fields_array[i].group; idx = i; if (!right && !valid_names) { found = TRUE; break; } for (j = 0; valid_names && valid_names[j].name; j++) { if (!right || strcasecmp (right, valid_names[j].name) == 0) { found = TRUE; break; } } if (found) break; } } if (found) { /* Add index to array, and field name (or NULL) to group_fields array */ g_array_append_val (array, idx); if (group_fields && *group_fields) g_ptr_array_add (*group_fields, g_strdup (right)); } if (right) *(right-1) = '.'; /* Restore the original string */ } else { /* e.g. "general,ip4,ip6" */ for (i = 0; fields_array[i].name; i++) { if (strcasecmp (*iter, fields_array[i].name) == 0) { g_array_append_val (array, i); break; } } } /* Field was not found - error case */ if (fields_array[i].name == NULL) { /* Set GError */ if (!strcasecmp (*iter, "all") || !strcasecmp (*iter, "common")) g_set_error (error, NMCLI_ERROR, 0, _("field '%s' has to be alone"), *iter); else { char *allowed_fields = nmc_get_allowed_fields (fields_array, idx); g_set_error (error, NMCLI_ERROR, 1, _("invalid field '%s'; allowed fields: %s"), *iter, allowed_fields); g_free (allowed_fields); } /* Free arrays on error */ g_array_free (array, TRUE); array = NULL; if (group_fields && *group_fields) { g_ptr_array_free (*group_fields, TRUE); *group_fields = NULL; } goto done; } } done: if (fields) g_strfreev (fields); return array; }
gboolean exchanges_load_config ( void ) { GMappedFile *f; GKeyFile *kf; GError *error = NULL; gsize flen, len_config; gchar *config; gchar *finput; gchar *exch_name_str; gchar **exch_name_str_list; gchar *exch_desc_str; gchar **exch_desc_str_list; gint i; /* read configuration file */ f = g_mapped_file_new ( CONFIG_FILENAME, FALSE, &error ); if ( f == NULL ) { log_print ( "error: exchanges_load_config(): file \'%s\' cannot be read: %s\n", CONFIG_FILENAME, error->message ); g_error_free ( error ); return TRUE; } flen = g_mapped_file_get_length ( f ); len_config = strlen(CONFIG_HEADER) + flen + 1; /* copy configuration in a buffer after prepending a key-file group name to make GLib happy */ config = (gchar *) g_malloc ( sizeof(gchar) * len_config ); strcpy ( config, CONFIG_HEADER ); finput = g_mapped_file_get_contents ( f ); memcpy ( config+strlen(CONFIG_HEADER), finput, flen ); g_mapped_file_unref ( f ); config[len_config-1] = '\0'; /* parse configuration file to get exchanges list */ kf = g_key_file_new ( ); g_key_file_load_from_data ( kf, config, len_config, G_KEY_FILE_NONE, &error ); if ( error != NULL ) { log_print ( "error: exchanges_load_config(): unable to parse config file \'%s\': %s\n", CONFIG_FILENAME, error->message ); g_error_free ( error ); return TRUE; } exch_name_str = g_key_file_get_string ( kf, "markets", "EXCHANGES", &error ); if ( exch_name_str == NULL ) { log_print ( "error: exchanges_load_config(): unable to find \'EXCHANGES\' key\n" ); return TRUE; } if ( exch_name_str[0] == '\"' ) exch_name_str[0] = ' '; /* remove \" characters */ if ( exch_name_str[strlen(exch_name_str)-1] == '\"' ) exch_name_str[strlen(exch_name_str)-1] = ' '; exch_desc_str = g_key_file_get_string ( kf, "markets", "EXCHANGES_DESC", &error ); if ( exch_desc_str == NULL ) { log_print ( "error: exchanges_load_config(): unable to find \'EXCHANGES_DESC\' key\n" ); return TRUE; } if ( exch_desc_str[0] == '\"' ) exch_desc_str[0] = ' '; /* remove \" characters */ if ( exch_desc_str[strlen(exch_desc_str)-1] == '\"' ) exch_desc_str[strlen(exch_desc_str)-1] = ' '; /* build EXCH_DESC array */ exch_name_str_list = g_strsplit_set ( exch_name_str, " ", 0 ); exch_desc_str_list = g_strsplit_set ( exch_desc_str, " ", 0 ); for ( i=0; i<EXCH_NB_MAX; ++i ) { if ( exch_name_str_list[i] == NULL ) break; if ( strlen(exch_name_str_list[i]) == 0 ) continue; /* log_print ( "core: adding exchange \'%s\'\n", exch_name_str_list[i] ); */ EXCH_DESC[nb_exchanges].name = g_strdup ( exch_name_str_list[i] ); if ( ( exch_desc_str_list[i] != NULL ) && ( strlen(exch_desc_str_list[i]) > 0 ) ) EXCH_DESC[nb_exchanges].desc = g_strdup ( exch_desc_str_list[i] ); else EXCH_DESC[nb_exchanges].desc = g_strdup ( exch_name_str_list[i] ); ++nb_exchanges; } /* clean up */ g_key_file_free ( kf ); g_free ( config ); g_free ( exch_name_str ); g_free ( exch_desc_str ); g_strfreev ( exch_name_str_list ); g_strfreev ( exch_desc_str_list ); return FALSE; }
static void process_coords (CallbackData *data) { GIOChannel *output_channel; GError *error = NULL; int use_stdout = 1; /* Open */ if (!data->output_path || !*data->output_path || (data->output_path[0] == '-' && data->output_path[1] == '\0')) output_channel = g_io_channel_unix_new (STDOUT_FILENO); else { use_stdout = 0; output_channel = g_io_channel_new_file (data->output_path, "w", &error); if (error) { g_printerr ("[ERROR] failed to open output file `%s': %s\n", data->output_path, error->message); exit (1); } } if (data->name) { ref_meth_counts_write_segment (data->counts, data->ref, output_channel, data->name, MAX (data->from, 0), MAX (data->to, 0) , data->print_letter, data->print_all, &error); if (error) { g_printerr ("[ERROR] Problem while writing segment: %s\n", error->message); g_error_free (error); } } else { GIOChannel *input_channel; char **fields; char *line; gsize length; gsize endl; /* Open */ input_channel = g_io_channel_new_file (data->input_path, "r", &error); if (error) { g_printerr ("[ERROR] failed to open input file `%s': %s\n", data->input_path, error->message); exit (1); } while (G_IO_STATUS_NORMAL == g_io_channel_read_line (input_channel, &line, &length, &endl, &error)) { int n_fields; line[endl] = '\0'; fields = g_strsplit_set (line, " \t", 0); n_fields = -1; while (fields[++n_fields]); if (n_fields < 3) g_printerr ("[WARNING] Could not parse coordinates line: %s\n", line); else { long from; long to; from = g_ascii_strtoll (fields[1], NULL, 10); to = g_ascii_strtoll (fields[2], NULL, 10); ref_meth_counts_write_segment (data->counts, data->ref, output_channel, fields[0], MAX (from, 0), MAX (to, 0) , data->print_letter, data->print_all, &error); } g_strfreev (fields); g_free (line); } /* Close */ g_io_channel_shutdown (input_channel, TRUE, &error); if (error) { g_printerr ("[ERROR] Closing input file `%s' failed: %s\n", data->input_path, error->message); g_error_free (error); } g_io_channel_unref (input_channel); } /* Close */ if (!use_stdout) { g_io_channel_shutdown (output_channel, TRUE, &error); if (error) { g_printerr ("[ERROR] Closing output file `%s' failed: %s\n", data->output_path, error->message); g_error_free (error); } } g_io_channel_unref (output_channel); }
void read_value(char *name, char *value) { //The *name and *value are derived from sargv which is given one by one through //a loop from conf_init() if (name != NULL && value != NULL) { if (name[0] == '#') return; g_strstrip(name); g_strstrip(value); if (!strcmp("font", name) || !strcmp("-fn", name)) strcpy(_font, value); else if (!strcmp("background", name) || !strcmp("-bg", name)) { if (!parse_hex_color(value, &_bg)) gdk_color_parse("black", &_bg); } else if (!strcmp("foreground", name) || !strcmp("-fg", name)) { if (!parse_hex_color(value, &_fg)) gdk_color_parse("white", &_fg); } else if (!strcmp("scrollbar", name) || !strcmp("-s", name)) { if (!strcmp(value, "true")) _scrollpos = POS_RIGHT; else if (!strcmp(value, "left")) _scrollpos = POS_LEFT; else if (!strcmp(value, "right")) _scrollpos = POS_RIGHT; else _scrollpos = -1; } else if (!strcmp("border", name) || !strcmp("-b", name)) set_border(value); else if (!strcmp("opacity", name) || !strcmp("-o", name)) _opacity = atof(value); else if (!strcmp("bgimage", name) || !strcmp("-bgimg", name)) strcpy(_bgimage, value); else if (!strcmp("width", name) || !strcmp("-w", name)) _width = atoi(value); else if (!strcmp("height", name) || !strcmp("-h", name)) _height = atoi(value); else if (!strcmp("position", name) || !strcmp("-p", name)) set_pos(value); else if (!strcmp("mod", name) || !strcmp("-m", name)) set_mod(value); else if (!strcmp("key", name) || !strcmp("-k", name)) set_key(value); else if (!strcmp("shell", name) || !strcmp("-sh", name)) strcpy(_shell, value); else if (!strcmp("lines", name) || !strcmp("-l", name)) _lines = atoi(value); else if (!strcmp("showtab", name) || !strcmp("-showtab", name)) { if (!strcasecmp(value, "always")) _showtab = TABS_ALWAYS; else if (!strcasecmp(value, "never")) _showtab = TABS_NEVER; } else if (!strcmp("tabpos", name) || !strcmp("-tabpos", name)) _tabpos = read_pos(value); else if (!strcmp("tablabel", name) || !strcmp("-tablabel", name)) strcpy(_termname, value); else if (!strcmp("cursorblink", name) || !strcmp("-cb", name)) set_cursor_blink(value); else if (!strcmp("cursorshape", name) || !strcmp("-cs", name)) set_cursor_shape(value); else if (g_str_has_prefix(name, "color") || g_str_has_prefix(name, "-c")) { g_strcanon(name, "0123456789", ' '); g_strchug(name); parse_hex_color(value, &_palette[atoi(name)]); read_colors++; } else if (!strcmp("tabfill", name) || !strcmp("-tf", name)) _tabfill = parse_bool_str(value, _tabfill); else if (!strcmp("allowbold", name) || !strcmp("-ab", name)) _allowbold = parse_bool_str(value, _allowbold); else if (!strcmp("keymod", name) || !strcmp("-km", name)) { char **list; list = g_strsplit_set(value, "+", -1); GdkModifierType tmp = 0; int i = 0; while (list[i] != NULL) tmp = tmp | parse_mod(list[i++]); g_strfreev(list); if (tmp != 0) _keymod = tmp; } else if (!strcmp("autohide", name) || !strcmp("-ah", name)) _autohide = parse_bool_str(value, _autohide); else if (!strcmp("scroll", name) || !strcmp("-sc", name)) _scrolloutput = parse_bool_str(value, _scrolloutput); else if (!strcmp("bell", name) || !strcmp("-bell", name)) if (!strcasecmp(value, "false")) _bell = FALSE; } }
gboolean nm_logging_setup (const char *level, const char *domains, char **bad_domains, GError **error) { GString *unrecognized = NULL; guint64 new_logging[LOGL_MAX]; guint32 new_log_level = log_level; char **tmp, **iter; int i; for (i = 0; i < LOGL_MAX; i++) new_logging[i] = 0; /* levels */ if (level && *level) { if (!match_log_level (level, &new_log_level, error)) return FALSE; } /* domains */ if (!domains || !*domains) domains = log_domains ? log_domains : "DEFAULT"; tmp = g_strsplit_set (domains, ", ", 0); for (iter = tmp; iter && *iter; iter++) { const LogDesc *diter; guint32 domain_log_level; guint64 bits; char *p; if (!strlen (*iter)) continue; p = strchr (*iter, ':'); if (p) { *p = '\0'; if (!match_log_level (p + 1, &domain_log_level, error)) { g_strfreev (tmp); return FALSE; } } else domain_log_level = new_log_level; bits = 0; /* Check for combined domains */ if (!g_ascii_strcasecmp (*iter, LOGD_ALL_STRING)) bits = LOGD_ALL; else if (!g_ascii_strcasecmp (*iter, LOGD_DEFAULT_STRING)) bits = LOGD_DEFAULT; else if (!g_ascii_strcasecmp (*iter, LOGD_DHCP_STRING)) bits = LOGD_DHCP; else if (!g_ascii_strcasecmp (*iter, LOGD_IP_STRING)) bits = LOGD_IP; /* Check for compatibility domains */ else if (!g_ascii_strcasecmp (*iter, "HW")) bits = LOGD_PLATFORM; else { for (diter = &domain_descs[0]; diter->name; diter++) { if (!g_ascii_strcasecmp (diter->name, *iter)) { bits = diter->num; break; } } } if (!bits) { if (!bad_domains) { g_set_error (error, NM_LOGGING_ERROR, NM_LOGGING_ERROR_UNKNOWN_DOMAIN, _("Unknown log domain '%s'"), *iter); return FALSE; } if (unrecognized) g_string_append (unrecognized, ", "); else unrecognized = g_string_new (NULL); g_string_append (unrecognized, *iter); continue; } for (i = 0; i < domain_log_level; i++) new_logging[i] &= ~bits; for (i = domain_log_level; i < LOGL_MAX; i++) new_logging[i] |= bits; } g_strfreev (tmp); if (log_domains != (char *)domains) { g_free (log_domains); log_domains = g_strdup (domains); } log_level = new_log_level; for (i = 0; i < LOGL_MAX; i++) logging[i] = new_logging[i]; if (unrecognized) *bad_domains = g_string_free (unrecognized, FALSE); return TRUE; }
/* * Create and initialize a new ini_loop structure base on the supplied data. * buf_with_loop - array containing loop instruction and all its parameters. * loop_name - keyword used to identify the type of loop. */ static struct ini_loop * ini_loop_new(char *buf_with_loop, char *loop_name) { struct ini_loop *loop = NULL; long long first, inc, last; int loop_type; char var[128]; gchar *for_raw_list = NULL; gchar **for_values = NULL; int ret; /* Check loop type. Base on that gather up all of it's parameters */ if (!strncmp(loop_name, "SEQ", sizeof("SEQ") - 1)) { loop_type = INI_LOOP_SEQ; ret = sscanf(buf_with_loop, "<SEQ> %s %lli %lli %lli", var, &first, &inc, &last); if (ret != 4) { ret = -EINVAL; fprintf(stderr, "Unrecognized SEQ line\n"); goto err_close; } } else if (!strncmp(loop_name, "FOR", sizeof("FOR") - 1)) { loop_type = INI_LOOP_FOR; ret = sscanf(buf_with_loop, "<FOR> %s in {", var); for_raw_list = g_strstr_len(buf_with_loop, -1, "{"); if (!for_raw_list) { ret = -EINVAL; fprintf(stderr, "Unrecognized FOR line\n"); goto err_close; } char *s = g_strdup(for_raw_list); s = g_strstrip(g_strdelimit(s, "{}\n", ' ')); for_values = g_strsplit_set(s, " {}\n", -1); g_free(s); first = 0; inc = 1; last = g_strv_length(for_values) - 1; } else { ret = -EINVAL; fprintf(stderr, "Unrecognized %s loop keyword\n", loop_name); goto err_close; } /* Store all necessary parameters of a loop */ loop = calloc(sizeof(struct ini_loop), 1); if (!loop) { fprintf(stderr, "%s is %s", strerror(errno), __func__); goto err_close; } loop->type = loop_type; loop->first = first; loop->inc = inc; loop->last = last; snprintf(loop->var, sizeof(loop->var), "<%s>", var); snprintf(loop->end_loop, sizeof(loop->end_loop), "</%s>", loop_name); loop->for_values = for_values; err_close: return loop; }
void read_proc_diskstats() { GError *gerror = NULL; char *contents = NULL; gsize len; int n; gchar **arr_file, **arr_line; char *path = "/proc/diskstats"; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { g_critical("%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } } /* mapping device to mount points char *buf[100]={}; read_lvdisplay(buf); int i=0; while(buf[i]){ //g_message("while loop: i:%d buf:%s:", i, buf[i]); if(!g_strcmp0(buf[i],"")) break; //gchar **mapping_str = g_strsplit_set(buf[i],"/", -1); //g_message("%s", mapping_str[3]); i++; } */ arr_file = g_strsplit_set(contents,"\n", -1); int newlines = g_strv_length(arr_file) - 1; char *all_devices=NULL, *one_device=NULL; for(n=0; n < newlines ; n++) { arr_line = g_strsplit_set(arr_file[n], " ", -1); // cpu0 int k=0, skip=0; int device_index=0; while(arr_line[k]) { if(!g_strcmp0(arr_line[k],"")) { ++k; continue; } if(skip<2) { ++skip; // the initial 2 fields are major and minor numbers. } else { device_index = k; break; } //g_message("%d:%s",k,arr_line[k]); k = k+1; } //g_message("device: %s", arr_line[device_index]); if(g_str_has_prefix(arr_line[device_index],"ram")) { g_strfreev(arr_line); continue; } if(g_str_has_prefix(arr_line[device_index],"loop")) { g_strfreev(arr_line); continue; } if(g_str_has_prefix(arr_line[device_index],"mmcblk0p")) { g_strfreev(arr_line); continue; } //if(g_str_has_prefix(arr_line[device_index],"mmcblk1p")) continue; one_device = g_strdup_printf("%s:r:%s:w:%s:ip:%s", //path, arr_line[device_index], arr_line[device_index + 1], // reads_completed //arr_line[device_index+2], // reads_merged //arr_line[+3], // sectors_read //arr_line[+4], // ms_reading arr_line[device_index + 5], // writes_completed //arr_line[device_index+6], // writes_merged //arr_line[+7], // sectors_written //arr_line[+8], // ms_writing arr_line[device_index + 9] // io_inprogress //arr_line[22] // ms_io //arr_line[8] // ms_weighted_io );//g_strconcat( char* delete_this= all_devices; all_devices = g_strjoin(" ",one_device, all_devices, NULL); g_free(one_device); g_free(delete_this); g_strfreev(arr_line); } g_message("io:%s",all_devices); g_free(all_devices); g_strfreev(arr_file); g_free(contents); }
static void on_open_selected_file(GtkMenuItem *menuitem, gpointer user_data) { GeanyDocument *doc = document_get_current(); gchar *sel = NULL; gchar *filename = NULL; gchar *path = NULL; g_return_if_fail(doc != NULL); sel = get_selection(); if (!sel) return; setptr(sel, utils_get_locale_from_utf8(sel)); if (g_path_is_absolute(sel)) { filename = g_strdup(sel); if (!g_file_test(filename, G_FILE_TEST_EXISTS)) { g_free(filename); filename = NULL; } } if (!filename) { if (doc->file_name) { path = g_path_get_dirname(doc->file_name); setptr(path, utils_get_locale_from_utf8(path)); } if (!path) path = g_get_current_dir(); filename = g_build_path(G_DIR_SEPARATOR_S, path, sel, NULL); if (!g_file_test(filename, G_FILE_TEST_EXISTS)) { g_free(filename); filename = NULL; } g_free(path); } if (!filename && geany_data->app->project != NULL) { gchar **pathv; gint i; path = g_strdup(""); pathv = g_strsplit_set(sel, "/\\", -1); for (i = g_strv_length(pathv) - 1; i >= 0; i--) { if (g_strcmp0(pathv[i], "..") == 0) break; setptr(path, g_build_filename(G_DIR_SEPARATOR_S, pathv[i], path, NULL)); } g_strfreev(pathv); if (g_strcmp0(path, "") != 0) { FindData data; data.subpath = path; data.found_path = NULL; g_hash_table_foreach(g_prj->file_tag_table, (GHFunc)find_name, &data); if (data.found_path) { filename = g_strdup(data.found_path); setptr(filename, utils_get_locale_from_utf8(filename)); if (!g_file_test(filename, G_FILE_TEST_EXISTS)) { g_free(filename); filename = NULL; } } } g_free(path); } #ifdef G_OS_UNIX if (!filename) { filename = g_build_path(G_DIR_SEPARATOR_S, "/usr/local/include", sel, NULL); if (!g_file_test(filename, G_FILE_TEST_EXISTS)) { g_free(filename); filename = NULL; } } if (!filename) { filename = g_build_path(G_DIR_SEPARATOR_S, "/usr/include", sel, NULL); if (!g_file_test(filename, G_FILE_TEST_EXISTS)) { g_free(filename); filename = NULL; } } #endif if (filename) open_file(filename); g_free(filename); g_free(sel); }
void read_proc_meminfo() { GError *gerror = NULL; char *contents = NULL; gsize len; int n; gchar **arr_file, **arr_line; char *path = "/proc/meminfo"; if (!path || !g_file_get_contents(path, &contents, &len, &gerror)) { if (gerror) { g_critical("%s: %s", __FUNCTION__, gerror->message); g_error_free(gerror); } } arr_file = g_strsplit_set(contents,"\n", -1); int newlines = g_strv_length(arr_file) - 1; char* MemTotal=NULL; char* MemFree = NULL; char* SwapTotal=NULL; char* SwapFree = NULL; for(n=0; n < newlines ; n++) { arr_line = g_strsplit_set(arr_file[n], ":", -1); if(!g_strcmp0(arr_line[0],"MemTotal")) { MemTotal = g_strdup(arr_line[1]); } if(!g_strcmp0(arr_line[0],"MemFree")) { MemFree = g_strdup(arr_line[1]); } if(!g_strcmp0(arr_line[0],"SwapTotal")) { SwapTotal = g_strdup(arr_line[1]); } if(!g_strcmp0(arr_line[0],"SwapFree")) { SwapFree = g_strdup(arr_line[1]); } g_strfreev(arr_line); } g_message("mem:mt:%s mf:%s st:%s sf:%s", g_strstrip(MemTotal), g_strstrip(MemFree), g_strstrip(SwapTotal), g_strstrip(SwapFree)); g_free(MemTotal); g_free(MemFree); g_free(SwapTotal); g_free(SwapFree); g_strfreev(arr_file); g_free(contents); }
/** * response: The HKP server response to parse * * Extracts the key data from the HKP server response * * Returns A GList of keys **/ static GList* parse_hkp_index (const gchar *response) { /* Luckily enough, both the HKP server and NAI HKP interface to their * LDAP server are close enough in output so the same function can * parse them both. */ /* pub 2048/<a href="/pks/lookup?op=get&search=0x3CB3B415">3CB3B415</a> 1998/04/03 David M. Shaw <<a href="/pks/lookup?op=get&search=0x3CB3B415">[email protected]</a>> */ g_auto(GStrv) lines = NULL; gchar **l; SeahorsePgpKey *key = NULL; SeahorsePgpSubkey *subkey_with_id = NULL; GList *keys = NULL; GList *subkeys = NULL; GList *uids = NULL; SeahorseFlags flags; lines = g_strsplit (response, "\n", 0); for (l = lines; *l; l++) { gchar *line, *t; line = *l; dehtmlize (line); g_debug ("%s", line); /* Start a new key */ if (g_ascii_strncasecmp (line, "pub ", 4) == 0) { g_auto(GStrv) v = NULL; gchar *fingerprint, *fpr = NULL; const gchar *algo; gboolean has_uid = TRUE; SeahorsePgpSubkey *subkey; t = line + 4; while (*t && g_ascii_isspace (*t)) t++; v = g_strsplit_set (t, " ", 3); if (!v[0] || !v[1] || !v[2]) { g_message ("Invalid key line from server: %s", line); continue; } flags = SEAHORSE_FLAG_EXPORTABLE; /* Cut the length and fingerprint */ fpr = strchr (v[0], '/'); if (fpr == NULL) { g_message ("couldn't find key fingerprint in line from server: %s", line); fpr = ""; } else { *(fpr++) = 0; } /* Check out the key type */ switch (g_ascii_toupper (v[0][strlen (v[0]) - 1])) { case 'D': algo = "DSA"; break; case 'R': algo = "RSA"; break; default: algo = ""; break; }; /* Format the date for our parse function */ g_strdelimit (v[1], "/", '-'); /* Cleanup the UID */ g_strstrip (v[2]); if (g_ascii_strcasecmp (v[2], "*** KEY REVOKED ***") == 0) { flags |= SEAHORSE_FLAG_REVOKED; has_uid = FALSE; } if (key) { seahorse_pgp_key_set_uids (SEAHORSE_PGP_KEY (key), uids); g_list_free_full (uids, g_object_unref); seahorse_pgp_key_set_subkeys (SEAHORSE_PGP_KEY (key), subkeys); g_list_free_full (subkeys, g_object_unref); seahorse_pgp_key_realize (SEAHORSE_PGP_KEY (key)); uids = subkeys = NULL; subkey_with_id = NULL; key = NULL; } key = seahorse_pgp_key_new (); keys = g_list_prepend (keys, key); g_object_set (key, "object-flags", flags, NULL); /* Add all the info to the key */ subkey = seahorse_pgp_subkey_new (); seahorse_pgp_subkey_set_keyid (subkey, fpr); subkey_with_id = subkey; fingerprint = seahorse_pgp_subkey_calc_fingerprint (fpr); seahorse_pgp_subkey_set_fingerprint (subkey, fingerprint); g_free (fingerprint); seahorse_pgp_subkey_set_flags (subkey, flags); seahorse_pgp_subkey_set_created (subkey, parse_hkp_date (v[1])); seahorse_pgp_subkey_set_length (subkey, strtol (v[0], NULL, 10)); seahorse_pgp_subkey_set_algorithm (subkey, algo); subkeys = g_list_prepend (subkeys, subkey); /* And the UID if one was found */ if (has_uid) { SeahorsePgpUid *uid = seahorse_pgp_uid_new (key, v[2]); uids = g_list_prepend (uids, uid); } /* A UID for the key */ } else if (key && g_ascii_strncasecmp (line, " ", 4) == 0) { SeahorsePgpUid *uid; g_strstrip (line); uid = seahorse_pgp_uid_new (key, line); uids = g_list_prepend (uids, uid); /* Signatures */ } else if (key && g_ascii_strncasecmp (line, "sig ", 4) == 0) { /* TODO: Implement signatures */ } else if (key && subkey_with_id) { const char *fingerprint_str; g_autofree gchar *pretty_fingerprint = NULL; fingerprint_str = get_fingerprint_string (line); if (fingerprint_str == NULL) continue; pretty_fingerprint = seahorse_pgp_subkey_calc_fingerprint (fingerprint_str); /* FIXME: we don't check that the fingerprint actually matches * the key's ID. We also don't validate the fingerprint at * all; the keyserver may have returned some garbage and we * don't notice. */ if (pretty_fingerprint[0] != 0) seahorse_pgp_subkey_set_fingerprint (subkey_with_id, pretty_fingerprint); } } if (key) { seahorse_pgp_key_set_uids (SEAHORSE_PGP_KEY (key), g_list_reverse (uids)); g_list_free_full (uids, g_object_unref); seahorse_pgp_key_set_subkeys (SEAHORSE_PGP_KEY (key), g_list_reverse (subkeys)); g_list_free_full (subkeys, g_object_unref); seahorse_pgp_key_realize (SEAHORSE_PGP_KEY (key)); } return keys; }
IdolPlParserResult idol_pl_parser_add_m3u (IdolPlParser *parser, GFile *file, GFile *base_file, IdolPlParseData *parse_data, gpointer data) { IdolPlParserResult retval = IDOL_PL_PARSER_RESULT_UNHANDLED; char *contents, **lines; gsize size; guint i, num_lines; gboolean dos_mode = FALSE; const char *extinfo; if (g_file_load_contents (file, NULL, &contents, &size, NULL, NULL) == FALSE) return IDOL_PL_PARSER_RESULT_ERROR; /* .pls files with a .m3u extension, the nasties */ if (g_str_has_prefix (contents, "[playlist]") != FALSE || g_str_has_prefix (contents, "[Playlist]") != FALSE || g_str_has_prefix (contents, "[PLAYLIST]") != FALSE) { retval = idol_pl_parser_add_pls_with_contents (parser, file, base_file, contents, parse_data); g_free (contents); return retval; } /* Try to use ISO-8859-1 if we don't have valid UTF-8, * try to parse anyway if it's not ISO-8859-1 */ if (g_utf8_validate (contents, -1, NULL) == FALSE) { char *fixed; fixed = g_convert (contents, -1, "UTF-8", "ISO8859-1", NULL, NULL, NULL); if (fixed != NULL) { g_free (contents); contents = fixed; } } /* is non-NULL if there's an EXTINF on a preceding line */ extinfo = NULL; /* figure out whether we're a unix m3u or dos m3u */ if (strstr(contents, "\x0d")) { dos_mode = TRUE; } lines = g_strsplit_set (contents, "\r\n", 0); g_free (contents); num_lines = g_strv_length (lines); /* We don't count the terminating NULL */ num_lines--; for (i = 0; lines[i] != NULL; i++) { const char *line; line = lines[i]; if (line[0] == '\0') continue; retval = IDOL_PL_PARSER_RESULT_SUCCESS; /* Ignore leading spaces */ for (; g_ascii_isspace (line[0]); line++) ; /* Ignore comments, but mark it if we have extra info */ if (line[0] == '#') { if (extinfo == NULL && g_str_has_prefix (line, EXTINF) != FALSE) extinfo = line; continue; } /* Either it's a URI, or it has a proper path ... */ if (strstr(line, "://") != NULL || line[0] == G_DIR_SEPARATOR) { GFile *uri; uri = g_file_new_for_commandline_arg (line); if (idol_pl_parser_parse_internal (parser, uri, NULL, parse_data) != IDOL_PL_PARSER_RESULT_SUCCESS) { idol_pl_parser_add_one_uri (parser, line, idol_pl_parser_get_extinfo_title (extinfo)); } g_object_unref (uri); extinfo = NULL; } else if (g_ascii_isalpha (line[0]) != FALSE && g_str_has_prefix (line + 1, ":\\")) { /* Path relative to a drive on Windows, we need to use * the base that was passed to us */ GFile *uri; lines[i] = g_strdelimit (lines[i], "\\", '/'); /* + 2, skip drive letter */ uri = g_file_get_child (base_file, line + 2); idol_pl_parser_add_one_file (parser, uri, idol_pl_parser_get_extinfo_title (extinfo)); g_object_unref (uri); extinfo = NULL; } else if (line[0] == '\\' && line[1] == '\\') { /* ... Or it's in the windows smb form * (\\machine\share\filename), Note drive names * (C:\ D:\ etc) are unhandled (unknown base for * drive letters) */ char *tmpuri; lines[i] = g_strdelimit (lines[i], "\\", '/'); tmpuri = g_strjoin (NULL, "smb:", line, NULL); idol_pl_parser_add_one_uri (parser, line, idol_pl_parser_get_extinfo_title (extinfo)); extinfo = NULL; g_free (tmpuri); } else { /* Try with a base */ GFile *uri, *_base_file; char sep; _base_file = g_file_get_parent (file); sep = (dos_mode ? '\\' : '/'); if (sep == '\\') lines[i] = g_strdelimit (lines[i], "\\", '/'); uri = g_file_get_child (_base_file, line); g_object_unref (_base_file); idol_pl_parser_add_one_file (parser, uri, idol_pl_parser_get_extinfo_title (extinfo)); g_object_unref (uri); extinfo = NULL; } } g_strfreev (lines); return retval; }
static void construct_list() { g_strfreev(words); words = g_strsplit_set(purple_prefs_get_string("/plugins/gtk/libnotify/triggerMessages"), DELIMS, -1); }