/* This function renders a pixbuf from an SVG file according to vals. */ static GdkPixbuf * load_rsvg_pixbuf (const gchar *filename, SvgLoadVals *vals, GError **error) { GdkPixbuf *pixbuf = NULL; RsvgHandle *handle; GIOChannel *io; gchar *uri; GIOStatus status = G_IO_STATUS_NORMAL; gboolean success = TRUE; io = g_io_channel_new_file (filename, "r", error); if (!io) return NULL; g_io_channel_set_encoding (io, NULL, NULL); handle = rsvg_handle_new (); rsvg_handle_set_dpi (handle, vals->resolution); /* set the base URI so that librsvg can resolve relative paths */ uri = g_filename_to_uri (filename, NULL, NULL); if (uri) { gchar *p = strrchr (uri, '/'); if (p) *p = '\0'; rsvg_handle_set_base_uri (handle, uri); g_free (uri); } rsvg_handle_set_size_callback (handle, load_set_size_callback, vals, NULL); while (success && status != G_IO_STATUS_EOF) { gchar buf[8192]; gsize len; status = g_io_channel_read_chars (io, buf, sizeof (buf), &len, error); switch (status) { case G_IO_STATUS_ERROR: success = FALSE; break; case G_IO_STATUS_EOF: success = rsvg_handle_close (handle, error); break; case G_IO_STATUS_NORMAL: success = rsvg_handle_write (handle, (const guchar *) buf, len, error); break; case G_IO_STATUS_AGAIN: break; } } g_io_channel_unref (io); if (success) pixbuf = rsvg_handle_get_pixbuf (handle); g_object_unref (handle); return pixbuf; }
static int telit_sap_enable(struct ofono_modem *modem, struct ofono_modem *sap_modem, int bt_fd) { struct telit_data *data = ofono_modem_get_data(modem); int fd; DBG("%p", modem); fd = telit_sap_open(); if (fd < 0) goto error; data->hw_io = g_io_channel_unix_new(fd); if (data->hw_io == NULL) { close(fd); goto error; } g_io_channel_set_encoding(data->hw_io, NULL, NULL); g_io_channel_set_buffered(data->hw_io, FALSE); g_io_channel_set_close_on_unref(data->hw_io, TRUE); data->bt_io = g_io_channel_unix_new(bt_fd); if (data->bt_io == NULL) goto error; g_io_channel_set_encoding(data->bt_io, NULL, NULL); g_io_channel_set_buffered(data->bt_io, FALSE); g_io_channel_set_close_on_unref(data->bt_io, TRUE); // DBUS connection to smart card reader daemon connection = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL); dbProxy = g_dbus_proxy_new_sync(connection, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.smart_e.RSAP","/RSAPServer","org.smart_e.RSAPServer", NULL, NULL); data->hw_watch = g_io_add_watch_full(data->hw_io, G_PRIORITY_DEFAULT, G_IO_HUP | G_IO_ERR | G_IO_NVAL | G_IO_IN, hw_event_cb, modem, hw_watch_remove); data->bt_watch = g_io_add_watch_full(data->bt_io, G_PRIORITY_DEFAULT, G_IO_HUP | G_IO_ERR | G_IO_NVAL | G_IO_IN, bt_event_cb, modem, bt_watch_remove); data->sap_modem = sap_modem; g_at_chat_register(data->chat, "#RSEN:", telit_rsen_notify, FALSE, modem, NULL); g_at_chat_send(data->chat, "AT#NOPT=0", NULL, NULL, NULL, NULL); /* Set SAP functionality */ g_at_chat_send(data->chat, "AT#RSEN=1,1,0,2,0", rsen_prefix, rsen_enable_cb, modem, NULL); return -EINPROGRESS; error: shutdown(bt_fd, SHUT_RDWR); close(bt_fd); sap_close_io(modem); return -EINVAL; }
void test_iochannel (void) { GIOChannel *gio_r, *gio_w ; GString *buffer; char *filename; char *srcdir = getenv ("srcdir"); gint rlength = 0; glong wlength = 0; gsize length_out; const gchar encoding[] = "EUC-JP"; GIOStatus status; GError *error = NULL; if (!srcdir) srcdir = "."; filename = g_build_filename (srcdir, "iochannel-test-infile", NULL); gio_r = g_io_channel_new_file (filename, "r", &error); gcut_assert_error (error); gio_w = g_io_channel_new_file ("iochannel-test-outfile", "w", &error); gcut_assert_error (error); g_io_channel_set_encoding (gio_r, encoding, &error); gcut_assert_error (error); g_io_channel_set_buffer_size (gio_r, BUFFER_SIZE); status = g_io_channel_set_flags (gio_r, G_IO_FLAG_NONBLOCK, &error); gcut_assert_error (error); buffer = g_string_sized_new (BUFFER_SIZE); while (TRUE) { do { status = g_io_channel_read_line_string (gio_r, buffer, NULL, &error); gcut_assert_error (error); } while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; rlength += buffer->len; do { status = g_io_channel_write_chars (gio_w, buffer->str, buffer->len, &length_out, &error); gcut_assert_error (error); } while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; wlength += length_out; if (length_out < buffer->len) g_warning ("Only wrote part of the line."); g_string_truncate (buffer, 0); } switch (status) { case G_IO_STATUS_EOF: break; case G_IO_STATUS_ERROR: gcut_assert_error(error); break; default: g_warning ("Abnormal exit from write loop."); break; } do { status = g_io_channel_flush (gio_w, &error); gcut_assert_error (error); } while (status == G_IO_STATUS_AGAIN); cut_assert_equal_int (G_IO_STATUS_NORMAL, status); g_io_channel_unref(gio_r); g_io_channel_unref(gio_w); test_small_writes (); }
static gboolean launch_test_binary (const char *binary, guint skip_tests) { GTestLogBuffer *tlb; GSList *slist, *free_list = NULL; GError *error = NULL; int argc = 0; const gchar **argv; GPid pid = 0; gint report_pipe[2] = { -1, -1 }; guint child_report_cb_id = 0; gboolean loop_pending; gint i = 0; if (!g_unix_open_pipe (report_pipe, FD_CLOEXEC, &error)) { if (subtest_mode_fatal) g_error ("Failed to open pipe for test binary: %s: %s", binary, error->message); else g_warning ("Failed to open pipe for test binary: %s: %s", binary, error->message); g_clear_error (&error); return FALSE; } /* setup argc */ for (slist = subtest_args; slist; slist = slist->next) argc++; /* argc++; */ if (subtest_quiet) argc++; if (subtest_verbose) argc++; if (!subtest_mode_fatal) argc++; /* Either -m=quick or -m=slow is always appended. */ argc++; if (subtest_mode_perf) argc++; if (!subtest_mode_undefined) argc++; if (gtester_list_tests) argc++; if (subtest_seedstr) argc++; argc++; if (skip_tests) argc++; for (slist = subtest_paths; slist; slist = slist->next) argc++; for (slist = skipped_paths; slist; slist = slist->next) argc++; /* setup argv */ argv = g_malloc ((argc + 2) * sizeof(gchar *)); argv[i++] = binary; for (slist = subtest_args; slist; slist = slist->next) argv[i++] = (gchar*) slist->data; /* argv[i++] = "--debug-log"; */ if (subtest_quiet) argv[i++] = "--quiet"; if (subtest_verbose) argv[i++] = "--verbose"; if (!subtest_mode_fatal) argv[i++] = "--keep-going"; if (subtest_mode_quick) argv[i++] = "-m=quick"; else argv[i++] = "-m=slow"; if (subtest_mode_perf) argv[i++] = "-m=perf"; if (!subtest_mode_undefined) argv[i++] = "-m=no-undefined"; if (gtester_list_tests) argv[i++] = "-l"; if (subtest_seedstr) argv[i++] = queue_gfree (&free_list, g_strdup_printf ("--seed=%s", subtest_seedstr)); argv[i++] = queue_gfree (&free_list, g_strdup_printf ("--GTestLogFD=%u", report_pipe[1])); if (skip_tests) argv[i++] = queue_gfree (&free_list, g_strdup_printf ("--GTestSkipCount=%u", skip_tests)); for (slist = subtest_paths; slist; slist = slist->next) argv[i++] = queue_gfree (&free_list, g_strdup_printf ("-p=%s", (gchar*) slist->data)); for (slist = skipped_paths; slist; slist = slist->next) argv[i++] = queue_gfree (&free_list, g_strdup_printf ("-s=%s", (gchar*) slist->data)); argv[i++] = NULL; g_spawn_async_with_pipes (NULL, /* g_get_current_dir() */ (gchar**) argv, NULL, /* envp */ G_SPAWN_DO_NOT_REAP_CHILD, /* G_SPAWN_SEARCH_PATH */ unset_cloexec_fdp, &report_pipe[1], /* pre-exec callback */ &pid, NULL, /* standard_input */ NULL, /* standard_output */ NULL, /* standard_error */ &error); g_slist_foreach (free_list, (void(*)(void*,void*)) g_free, NULL); g_slist_free (free_list); free_list = NULL; close (report_pipe[1]); if (!gtester_quiet) g_print ("(pid=%lu)\n", (unsigned long) pid); if (error) { close (report_pipe[0]); if (subtest_mode_fatal) g_error ("Failed to execute test binary: %s: %s", argv[0], error->message); else g_warning ("Failed to execute test binary: %s: %s", argv[0], error->message); g_clear_error (&error); g_free (argv); return FALSE; } g_free (argv); subtest_running = TRUE; subtest_io_pending = TRUE; tlb = g_test_log_buffer_new(); if (report_pipe[0] >= 0) { ioc_report = g_io_channel_unix_new (report_pipe[0]); g_io_channel_set_flags (ioc_report, G_IO_FLAG_NONBLOCK, NULL); g_io_channel_set_encoding (ioc_report, NULL, NULL); g_io_channel_set_buffered (ioc_report, FALSE); child_report_cb_id = g_io_add_watch_full (ioc_report, G_PRIORITY_DEFAULT - 1, G_IO_IN | G_IO_ERR | G_IO_HUP, child_report_cb, tlb, NULL); g_io_channel_unref (ioc_report); } g_child_watch_add_full (G_PRIORITY_DEFAULT + 1, pid, child_watch_cb, NULL, NULL); loop_pending = g_main_context_pending (NULL); while (subtest_running || /* FALSE once child exits */ subtest_io_pending || /* FALSE once ioc_report closes */ loop_pending) /* TRUE while idler, etc are running */ { /* g_print ("LOOPSTATE: subtest_running=%d subtest_io_pending=%d\n", subtest_running, subtest_io_pending); */ /* check for unexpected hangs that are not signalled on report_pipe */ if (!subtest_running && /* child exited */ subtest_io_pending && /* no EOF detected on report_pipe */ !loop_pending) /* no IO events pending however */ break; g_main_context_iteration (NULL, TRUE); loop_pending = g_main_context_pending (NULL); } if (subtest_io_pending) g_source_remove (child_report_cb_id); close (report_pipe[0]); g_test_log_buffer_free (tlb); return TRUE; }
void osync_trace(OSyncTraceType type, const char *message, ...) { #ifdef OPENSYNC_TRACE va_list arglist; char *buffer = NULL; int tabs = 0; unsigned long int id = 0; #ifdef _WIN32 int pid = 0; char tmp_buf[1024]; #else pid_t pid = 0; #endif char *logfile = NULL; GString *tabstr = NULL; int i = 0; GTimeVal curtime; char *logmessage = NULL; GError *error = NULL; GIOChannel *chan = NULL; gsize writen; const char *endline = NULL; if (!g_thread_supported ()) g_thread_init (NULL); if (!trace_disabled || !g_private_get(trace_disabled)) { _osync_trace_init(); osync_trace_enable(); } if (GPOINTER_TO_INT(g_private_get(trace_disabled))) return; if (!current_tabs) current_tabs = g_private_new (NULL); else tabs = GPOINTER_TO_INT(g_private_get(current_tabs)); #ifdef _WIN32 pid = _getpid(); endline = "\r\n"; #else pid = getpid(); endline = "\n"; #endif id = (unsigned long int)g_thread_self(); logfile = g_strdup_printf("%s%cThread%lu-%i.log", trace, G_DIR_SEPARATOR, id, pid); va_start(arglist, message); #ifdef _WIN32 vsnprintf(tmp_buf, 1024, message, arglist); buffer = g_strdup(tmp_buf); #else buffer = g_strdup_vprintf(message, arglist); #endif tabstr = g_string_new(""); for (i = 0; i < tabs; i++) { tabstr = g_string_append(tabstr, "\t"); } g_get_current_time(&curtime); switch (type) { case TRACE_ENTRY: logmessage = g_strdup_printf("[%li.%06li]\t%s>>>>>>> %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline); tabs++; break; case TRACE_INTERNAL: logmessage = g_strdup_printf("[%li.%06li]\t%s%s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline); break; case TRACE_SENSITIVE: if (GPOINTER_TO_INT(g_private_get(trace_sensitive))) logmessage = g_strdup_printf("[%li.%06li]\t%s[SENSITIVE] %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline); else logmessage = g_strdup_printf("[%li.%06li]\t%s[SENSITIVE CONTENT HIDDEN]%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, endline); break; case TRACE_EXIT: logmessage = g_strdup_printf("[%li.%06li]%s<<<<<<< %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline); tabs--; if (tabs < 0) tabs = 0; break; case TRACE_EXIT_ERROR: logmessage = g_strdup_printf("[%li.%06li]%s<--- ERROR --- %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline); tabs--; if (tabs < 0) tabs = 0; if (print_stderr) fprintf(stderr, "EXIT_ERROR: %s\n", buffer); break; case TRACE_ERROR: logmessage = g_strdup_printf("[%li.%06li]%sERROR: %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline); if (print_stderr) fprintf(stderr, "ERROR: %s\n", buffer); break; } g_free(buffer); g_private_set(current_tabs, GINT_TO_POINTER(tabs)); va_end(arglist); g_string_free(tabstr, TRUE); chan = g_io_channel_new_file(logfile, "a", &error); if (!chan) { printf("unable to open %s for writing: %s\n", logfile, error->message); return; } g_io_channel_set_encoding(chan, NULL, NULL); if (g_io_channel_write_chars(chan, logmessage, strlen(logmessage), &writen, NULL) != G_IO_STATUS_NORMAL) { printf("unable to write trace to %s\n", logfile); } else g_io_channel_flush(chan, NULL); g_io_channel_shutdown(chan, TRUE, NULL); g_io_channel_unref(chan); g_free(logmessage); g_free(logfile); #endif /* OPENSYNC_TRACE */ }
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); }
gboolean process_run (CommandData *command_data, GIOFunc io_callback, ProcessFinishCallback finish_callback, gpointer user_data, GError **error) { ProcessData *data; //struct termios term; struct winsize win = { .ws_col = 80, .ws_row = 24, .ws_xpixel = 480, .ws_ypixel = 192, }; data = g_slice_new0 (ProcessData); data->localwatchdog = FALSE; data->command_data = command_data; data->finish_callback = finish_callback; data->user_data = user_data; data->pid = forkpty (&data->fd, NULL, NULL, &win); if (data->pid < 0) { /* Failed to fork */ g_set_error (error, RESTRAINT_PROCESS_ERROR, RESTRAINT_PROCESS_FORK_ERROR, "Failed to fork: %s", g_strerror (errno)); return FALSE; } else if (data->pid == 0) { /* Child process. */ if (command_data->path && (chdir (command_data->path) == -1)) { /* command_path was supplied and we failed to chdir to it. */ g_warning ("Failed to chdir() to %s: %s\n", command_data->path, g_strerror (errno)); exit (1); } environ = (gchar **) command_data->environ; // Print the command being executed. gchar *command = g_strjoinv (" ", (gchar **) command_data->command); g_print ("%s\n", command); g_free (command); /* Spawn the command */ if (execvp (*command_data->command, (gchar **) command_data->command) == -1) { g_warning ("Failed to exec() %s, %s error:%s\n", *command_data->command, command_data->path, g_strerror (errno)); exit (1); } } /* Parent process. */ // close file descriptors on exec. Should prevent leaking fd's to child processes. fcntl (data->fd, F_SETFD, FD_CLOEXEC); // Localwatchdog handler if (command_data->max_time != 0) { data->timeout_handler_id = g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, command_data->max_time, process_timeout_callback, data, NULL); } // IO handler if (io_callback != NULL) { GIOChannel *io = g_io_channel_unix_new (data->fd); g_io_channel_set_flags (io, G_IO_FLAG_NONBLOCK, NULL); // Set Encoding to NULL to keep g_io_channel from trying to decode it. g_io_channel_set_encoding (io, NULL, NULL); data->io_handler_id = g_io_add_watch_full (io, G_PRIORITY_DEFAULT, G_IO_IN | G_IO_HUP, io_callback, data, process_io_finish); } // Monitor pid for return code data->pid_handler_id = g_child_watch_add_full (G_PRIORITY_DEFAULT, data->pid, process_pid_callback, data, process_pid_finish); return TRUE; } void process_pid_callback (GPid pid, gint status, gpointer user_data) { ProcessData *process_data = (ProcessData *) user_data; process_data->pid_result = status; }
sc_bool sc_fs_storage_write_to_path(sc_segment **segments) { sc_uint32 idx = 0, header_size = 0; const sc_segment *segment = 0; sc_fs_storage_segments_header header; GChecksum * checksum = null_ptr; GIOChannel * output = null_ptr; gchar * tmp_filename = null_ptr; gsize bytes; sc_bool result = SC_TRUE; if (!g_file_test(repo_path, G_FILE_TEST_IS_DIR)) { g_error("%s isn't a directory.", repo_path); return SC_FALSE; } // create temporary file output = _open_tmp_file(&tmp_filename); memset(&header, 0, sizeof(sc_fs_storage_segments_header)); header.segments_num = 0; header.timestamp = g_get_real_time(); header.version = sc_version_to_int(&SC_VERSION); g_io_channel_set_encoding(output, null_ptr, null_ptr); checksum = g_checksum_new(_checksum_type()); g_checksum_reset(checksum); for (idx = 0; idx < SC_ADDR_SEG_MAX; idx++) { segment = segments[idx]; if (segment == null_ptr) break; // stop save, because we allocate segment in order g_checksum_update(checksum, (guchar*)segment->elements, SC_SEG_ELEMENTS_SIZE_BYTE); } header.segments_num = idx; bytes = SC_STORAGE_SEG_CHECKSUM_SIZE; g_checksum_get_digest(checksum, header.checksum, &bytes); header_size = sizeof(header); if (g_io_channel_write_chars(output, (gchar*)&header_size, sizeof(header_size), &bytes, null_ptr) != G_IO_STATUS_NORMAL || bytes != sizeof(header_size)) { g_error("Can't write header size: %s", tmp_filename); result = SC_FALSE; goto clean; } if (g_io_channel_write_chars(output, (gchar*)&header, header_size, &bytes, null_ptr) != G_IO_STATUS_NORMAL || bytes != header_size) { g_error("Can't write header: %s", tmp_filename); result = SC_FALSE; goto clean; } for (idx = 0; idx < header.segments_num; ++idx) { segment = segments[idx]; g_assert(segment != null_ptr); if (g_io_channel_write_chars(output, (gchar*)segment->elements, SC_SEG_ELEMENTS_SIZE_BYTE, &bytes, null_ptr) != G_IO_STATUS_NORMAL || bytes != SC_SEG_ELEMENTS_SIZE_BYTE) { g_error("Can't write segment %d into %s", idx, tmp_filename); result = SC_FALSE; goto clean; } } if (result == SC_TRUE) { // rename main file if (g_file_test(tmp_filename, G_FILE_TEST_IS_REGULAR)) { g_io_channel_shutdown(output, TRUE, NULL); output = null_ptr; if (g_rename(tmp_filename, segments_path) != 0) { g_error("Can't rename %s -> %s", tmp_filename, segments_path); result = SC_FALSE; } } // save file memory g_message("Save file memory state"); if (sc_fm_save(fm_engine) != SC_RESULT_OK) g_critical("Error while saves file memory"); } clean: { if (tmp_filename) g_free(tmp_filename); if (checksum) g_checksum_free(checksum); if (output) g_io_channel_shutdown(output, TRUE, null_ptr); } return result; }
int main(int argc, char *argv[]) #endif { gboolean opt_force_online = FALSE; gboolean opt_help = FALSE; gboolean opt_login = FALSE; gboolean opt_nologin = FALSE; gboolean opt_version = FALSE; gboolean opt_si = TRUE; /* Check for single instance? */ char *opt_config_dir_arg = NULL; char *opt_login_arg = NULL; char *opt_session_arg = NULL; char *search_path; GList *accounts; #ifdef HAVE_SIGNAL_H int sig_indx; /* for setting up signal catching */ sigset_t sigset; char errmsg[BUFSIZ]; GIOChannel *signal_channel; GIOStatus signal_status; guint signal_channel_watcher; #ifndef DEBUG char *segfault_message_tmp; #endif GError *error; #endif int opt; gboolean gui_check; gboolean debug_enabled; gboolean migration_failed = FALSE; GList *active_accounts; struct option long_options[] = { {"config", required_argument, NULL, 'c'}, {"debug", no_argument, NULL, 'd'}, {"force-online", no_argument, NULL, 'f'}, {"help", no_argument, NULL, 'h'}, {"login", optional_argument, NULL, 'l'}, {"multiple", no_argument, NULL, 'm'}, {"nologin", no_argument, NULL, 'n'}, {"session", required_argument, NULL, 's'}, {"version", no_argument, NULL, 'v'}, {"display", required_argument, NULL, 'D'}, {"sync", no_argument, NULL, 'S'}, {0, 0, 0, 0} }; #ifdef DEBUG debug_enabled = TRUE; #else debug_enabled = FALSE; #endif #if !GLIB_CHECK_VERSION(2, 32, 0) /* GLib threading system is automaticaly initialized since 2.32. * For earlier versions, it have to be initialized before calling any * Glib or GTK+ functions. */ g_thread_init(NULL); #endif g_set_prgname("Pidgin"); #ifdef ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); bind_textdomain_codeset(PACKAGE, "UTF-8"); textdomain(PACKAGE); #endif #ifdef HAVE_SETLOCALE /* Locale initialization is not complete here. See gtk_init_check() */ setlocale(LC_ALL, ""); #endif #ifdef HAVE_SIGNAL_H #ifndef DEBUG /* We translate this here in case the crash breaks gettext. */ segfault_message_tmp = g_strdup_printf(_( "%s %s has segfaulted and attempted to dump a core file.\n" "This is a bug in the software and has happened through\n" "no fault of your own.\n\n" "If you can reproduce the crash, please notify the developers\n" "by reporting a bug at:\n" "%ssimpleticket/\n\n" "Please make sure to specify what you were doing at the time\n" "and post the backtrace from the core file. If you do not know\n" "how to get the backtrace, please read the instructions at\n" "%swiki/GetABacktrace\n"), PIDGIN_NAME, DISPLAY_VERSION, PURPLE_DEVEL_WEBSITE, PURPLE_DEVEL_WEBSITE ); /* we have to convert the message (UTF-8 to console charset) early because after a segmentation fault it's not a good practice to allocate memory */ error = NULL; segfault_message = g_locale_from_utf8(segfault_message_tmp, -1, NULL, NULL, &error); if (segfault_message != NULL) { g_free(segfault_message_tmp); } else { /* use 'segfault_message_tmp' (UTF-8) as a fallback */ g_warning("%s\n", error->message); g_error_free(error); segfault_message = segfault_message_tmp; } #else /* Don't mark this for translation. */ segfault_message = g_strdup( "Hi, user. We need to talk.\n" "I think something's gone wrong here. It's probably my fault.\n" "No, really, it's not you... it's me... no no no, I think we get along well\n" "it's just that.... well, I want to see other people. I... what?!? NO! I \n" "haven't been cheating on you!! How many times do you want me to tell you?! And\n" "for the last time, it's just a rash!\n" ); #endif /* * Create a socket pair for receiving unix signals from a signal * handler. */ if (socketpair(AF_UNIX, SOCK_STREAM, 0, signal_sockets) < 0) { perror("Failed to create sockets for GLib signal handling"); exit(1); } signal_channel = g_io_channel_unix_new(signal_sockets[1]); /* * Set the channel encoding to raw binary instead of the default of * UTF-8, because we'll be sending integers across instead of strings. */ error = NULL; signal_status = g_io_channel_set_encoding(signal_channel, NULL, &error); if (signal_status != G_IO_STATUS_NORMAL) { fprintf(stderr, "Failed to set the signal channel to raw " "binary: %s", error->message); exit(1); } signal_channel_watcher = g_io_add_watch(signal_channel, G_IO_IN, mainloop_sighandler, NULL); g_io_channel_unref(signal_channel); /* Let's not violate any PLA's!!!! */ /* jseymour: whatever the fsck that means */ /* Robot101: for some reason things like gdm like to block * * useful signals like SIGCHLD, so we unblock all the ones we * * declare a handler for. thanks JSeymour and Vann. */ if (sigemptyset(&sigset)) { snprintf(errmsg, sizeof(errmsg), "Warning: couldn't initialise empty signal set"); perror(errmsg); } for(sig_indx = 0; catch_sig_list[sig_indx] != -1; ++sig_indx) { if(signal(catch_sig_list[sig_indx], sighandler) == SIG_ERR) { snprintf(errmsg, sizeof(errmsg), "Warning: couldn't set signal %d for catching", catch_sig_list[sig_indx]); perror(errmsg); } if(sigaddset(&sigset, catch_sig_list[sig_indx])) { snprintf(errmsg, sizeof(errmsg), "Warning: couldn't include signal %d for unblocking", catch_sig_list[sig_indx]); perror(errmsg); } } for(sig_indx = 0; ignore_sig_list[sig_indx] != -1; ++sig_indx) { if(signal(ignore_sig_list[sig_indx], SIG_IGN) == SIG_ERR) { snprintf(errmsg, sizeof(errmsg), "Warning: couldn't set signal %d to ignore", ignore_sig_list[sig_indx]); perror(errmsg); } } if (sigprocmask(SIG_UNBLOCK, &sigset, NULL)) { snprintf(errmsg, sizeof(errmsg), "Warning: couldn't unblock signals"); perror(errmsg); } #endif /* scan command-line options */ opterr = 1; while ((opt = getopt_long(argc, argv, #ifndef _WIN32 "c:dfhmnl::s:v", #else "c:dfhmnl::v", #endif long_options, NULL)) != -1) { switch (opt) { case 'c': /* config dir */ g_free(opt_config_dir_arg); opt_config_dir_arg = g_strdup(optarg); break; case 'd': /* debug */ debug_enabled = TRUE; break; case 'f': /* force-online */ opt_force_online = TRUE; break; case 'h': /* help */ opt_help = TRUE; break; case 'n': /* no autologin */ opt_nologin = TRUE; break; case 'l': /* login, option username */ opt_login = TRUE; g_free(opt_login_arg); if (optarg != NULL) opt_login_arg = g_strdup(optarg); break; case 's': /* use existing session ID */ g_free(opt_session_arg); opt_session_arg = g_strdup(optarg); break; case 'v': /* version */ opt_version = TRUE; break; case 'm': /* do not ensure single instance. */ opt_si = FALSE; break; case 'D': /* --display */ case 'S': /* --sync */ /* handled by gtk_init_check below */ break; case '?': /* show terse help */ default: show_usage(argv[0], TRUE); #ifdef HAVE_SIGNAL_H g_free(segfault_message); #endif return 0; break; } } /* show help message */ if (opt_help) { show_usage(argv[0], FALSE); #ifdef HAVE_SIGNAL_H g_free(segfault_message); #endif return 0; } /* show version message */ if (opt_version) { printf("%s %s (libpurple %s)\n", PIDGIN_NAME, DISPLAY_VERSION, purple_core_get_version()); #ifdef HAVE_SIGNAL_H g_free(segfault_message); #endif return 0; } /* set a user-specified config directory */ if (opt_config_dir_arg != NULL) { purple_util_set_user_dir(opt_config_dir_arg); } /* * We're done piddling around with command line arguments. * Fire up this baby. */ purple_debug_set_enabled(debug_enabled); /* If we're using a custom configuration directory, we * do NOT want to migrate, or weird things will happen. */ if (opt_config_dir_arg == NULL) { if (!purple_core_migrate()) { migration_failed = TRUE; } } search_path = g_build_filename(purple_user_dir(), "gtkrc-2.0", NULL); gtk_rc_add_default_file(search_path); g_free(search_path); gui_check = gtk_init_check(&argc, &argv); if (!gui_check) { char *display = gdk_get_display(); printf("%s %s\n", PIDGIN_NAME, DISPLAY_VERSION); g_warning("cannot open display: %s", display ? display : "unset"); g_free(display); #ifdef HAVE_SIGNAL_H g_free(segfault_message); #endif return 1; } g_set_application_name(PIDGIN_NAME); #ifdef _WIN32 winpidgin_init(hint); #endif if (migration_failed) { char *old = g_strconcat(purple_home_dir(), G_DIR_SEPARATOR_S ".gaim", NULL); const char *text = _( "%s encountered errors migrating your settings " "from %s to %s. Please investigate and complete the " "migration by hand. Please report this error at http://developer.pidgin.im"); GtkWidget *dialog; dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, text, PIDGIN_NAME, old, purple_user_dir()); g_free(old); g_signal_connect_swapped(dialog, "response", G_CALLBACK(gtk_main_quit), NULL); gtk_widget_show_all(dialog); gtk_main(); #ifdef HAVE_SIGNAL_H g_free(segfault_message); #endif return 0; } purple_core_set_ui_ops(pidgin_core_get_ui_ops()); purple_eventloop_set_ui_ops(pidgin_eventloop_get_ui_ops()); /* * Set plugin search directories. Give priority to the plugins * in user's home directory. */ search_path = g_build_filename(purple_user_dir(), "plugins", NULL); if (g_mkdir(search_path, S_IRUSR | S_IWUSR | S_IXUSR) != 0 && errno != EEXIST) fprintf(stderr, "Couldn't create plugins dir\n"); purple_plugins_add_search_path(search_path); g_free(search_path); purple_plugins_add_search_path(LIBDIR); if (!purple_core_init(PIDGIN_UI)) { fprintf(stderr, "Initialization of the libpurple core failed. Dumping core.\n" "Please report this!\n"); #ifdef HAVE_SIGNAL_H g_free(segfault_message); #endif abort(); } if (opt_si && !purple_core_ensure_single_instance()) { #ifdef HAVE_DBUS DBusConnection *conn = purple_dbus_get_connection(); DBusMessage *message = dbus_message_new_method_call(DBUS_SERVICE_PURPLE, DBUS_PATH_PURPLE, DBUS_INTERFACE_PURPLE, "PurpleBlistSetVisible"); gboolean tr = TRUE; dbus_message_append_args(message, DBUS_TYPE_INT32, &tr, DBUS_TYPE_INVALID); dbus_connection_send_with_reply_and_block(conn, message, -1, NULL); dbus_message_unref(message); #endif gdk_notify_startup_complete(); purple_core_quit(); g_printerr(_("Exiting because another libpurple client is already running.\n")); #ifdef HAVE_SIGNAL_H g_free(segfault_message); #endif return 0; } /* TODO: Move blist loading into purple_blist_init() */ purple_set_blist(purple_blist_new()); purple_blist_load(); /* load plugins we had when we quit */ purple_plugins_load_saved(PIDGIN_PREFS_ROOT "/plugins/loaded"); /* TODO: Move pounces loading into purple_pounces_init() */ purple_pounces_load(); ui_main(); #ifdef USE_SM pidgin_session_init(argv[0], opt_session_arg, opt_config_dir_arg); #endif if (opt_session_arg != NULL) { g_free(opt_session_arg); opt_session_arg = NULL; } if (opt_config_dir_arg != NULL) { g_free(opt_config_dir_arg); opt_config_dir_arg = NULL; } /* This needs to be before purple_blist_show() so the * statusbox gets the forced online status. */ if (opt_force_online) purple_network_force_online(); /* * We want to show the blist early in the init process so the * user feels warm and fuzzy (not cold and prickley). */ purple_blist_show(); if (purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/debug/enabled")) pidgin_debug_window_show(); if (opt_login) { /* disable all accounts */ for (accounts = purple_accounts_get_all(); accounts != NULL; accounts = accounts->next) { PurpleAccount *account = accounts->data; purple_account_set_enabled(account, PIDGIN_UI, FALSE); } /* honor the startup status preference */ if (!purple_prefs_get_bool("/purple/savedstatus/startup_current_status")) purple_savedstatus_activate(purple_savedstatus_get_startup()); /* now enable the requested ones */ dologin_named(opt_login_arg); if (opt_login_arg != NULL) { g_free(opt_login_arg); opt_login_arg = NULL; } } else if (opt_nologin) { /* Set all accounts to "offline" */ PurpleSavedStatus *saved_status; /* If we've used this type+message before, lookup the transient status */ saved_status = purple_savedstatus_find_transient_by_type_and_message( PURPLE_STATUS_OFFLINE, NULL); /* If this type+message is unique then create a new transient saved status */ if (saved_status == NULL) saved_status = purple_savedstatus_new(NULL, PURPLE_STATUS_OFFLINE); /* Set the status for each account */ purple_savedstatus_activate(saved_status); } else { /* Everything is good to go--sign on already */ if (!purple_prefs_get_bool("/purple/savedstatus/startup_current_status")) purple_savedstatus_activate(purple_savedstatus_get_startup()); purple_accounts_restore_current_statuses(); } if ((active_accounts = purple_accounts_get_all_active()) == NULL) { pidgin_accounts_window_show(); } else { g_list_free(active_accounts); } /* GTK clears the notification for us when opening the first window, * but we may have launched with only a status icon, so clear the it * just in case. */ gdk_notify_startup_complete(); #ifdef _WIN32 winpidgin_post_init(); #endif gtk_main(); #ifdef HAVE_SIGNAL_H g_free(segfault_message); g_source_remove(signal_channel_watcher); close(signal_sockets[0]); close(signal_sockets[1]); #endif #ifdef _WIN32 winpidgin_cleanup(); #endif return 0; }
static EditorFlags editor_command_one(const EditorDescription *editor, GList *list, EditorData *ed) { gchar *command; FileData *fd = (ed->flags & EDITOR_NO_PARAM) ? NULL : list->data;; GPid pid; gint standard_output; gint standard_error; gboolean ok; ed->pid = -1; ed->flags = editor->flags; ed->flags |= editor_command_parse(editor, list, TRUE, &command); ok = !EDITOR_ERRORS(ed->flags); if (ok) { ok = (options->shell.path && *options->shell.path); if (!ok) log_printf("ERROR: empty shell command\n"); if (ok) { ok = (access(options->shell.path, X_OK) == 0); if (!ok) log_printf("ERROR: cannot execute shell command '%s'\n", options->shell.path); } if (!ok) ed->flags |= EDITOR_ERROR_CANT_EXEC; } if (ok) { gchar *working_directory; gchar *args[4]; guint n = 0; working_directory = fd ? remove_level_from_path(fd->path) : g_strdup(ed->working_directory); args[n++] = options->shell.path; if (options->shell.options && *options->shell.options) args[n++] = options->shell.options; args[n++] = command; args[n] = NULL; if ((ed->flags & EDITOR_DEST) && fd->change && fd->change->dest) /* FIXME: error handling */ { g_setenv("GEEQIE_DESTINATION", fd->change->dest, TRUE); } else { g_unsetenv("GEEQIE_DESTINATION"); } ok = g_spawn_async_with_pipes(working_directory, args, NULL, G_SPAWN_DO_NOT_REAP_CHILD, /* GSpawnFlags */ NULL, NULL, &pid, NULL, ed->vd ? &standard_output : NULL, ed->vd ? &standard_error : NULL, NULL); g_free(working_directory); if (!ok) ed->flags |= EDITOR_ERROR_CANT_EXEC; } if (ok) { g_child_watch_add(pid, editor_child_exit_cb, ed); ed->pid = pid; } if (ed->vd) { if (!ok) { gchar *buf; buf = g_strdup_printf(_("Failed to run command:\n%s\n"), editor->file); editor_verbose_window_fill(ed->vd, buf, strlen(buf)); g_free(buf); } else { GIOChannel *channel_output; GIOChannel *channel_error; channel_output = g_io_channel_unix_new(standard_output); g_io_channel_set_flags(channel_output, G_IO_FLAG_NONBLOCK, NULL); g_io_channel_set_encoding(channel_output, NULL, NULL); g_io_add_watch_full(channel_output, G_PRIORITY_HIGH, G_IO_IN | G_IO_ERR | G_IO_HUP, editor_verbose_io_cb, ed, NULL); g_io_channel_unref(channel_output); channel_error = g_io_channel_unix_new(standard_error); g_io_channel_set_flags(channel_error, G_IO_FLAG_NONBLOCK, NULL); g_io_channel_set_encoding(channel_error, NULL, NULL); g_io_add_watch_full(channel_error, G_PRIORITY_HIGH, G_IO_IN | G_IO_ERR | G_IO_HUP, editor_verbose_io_cb, ed, NULL); g_io_channel_unref(channel_error); } } g_free(command); return EDITOR_ERRORS(ed->flags); }
sc_bool sc_fs_storage_read_from_path(sc_segment **segments, sc_uint32 *segments_num) { if (g_file_test(repo_path, G_FILE_TEST_IS_DIR) == FALSE) { g_error("%s isn't a directory.", repo_path); return SC_FALSE; } if (g_file_test(segments_path, G_FILE_TEST_IS_REGULAR) == FALSE) { g_message("There are no segments in %s", segments_path); return SC_FALSE; } // open segments { GIOChannel * in_file = g_io_channel_new_file(segments_path, "r", null_ptr); sc_fs_storage_segments_header header; gsize bytes_num = 0; sc_uint32 i = 0, header_size = 0; GChecksum * checksum = null_ptr; sc_segment * seg = null_ptr; sc_bool is_valid = SC_TRUE; sc_uint8 calculated_checksum[SC_STORAGE_SEG_CHECKSUM_SIZE]; g_assert(_checksum_get_size() == SC_STORAGE_SEG_CHECKSUM_SIZE); if (!in_file) { g_critical("Can't open segments from: %s", segments_path); return SC_FALSE; } if (g_io_channel_set_encoding(in_file, null_ptr, null_ptr) != G_IO_STATUS_NORMAL) { g_critical("Can't setup encoding: %s", segments_path); return SC_FALSE; } if ((g_io_channel_read_chars(in_file, (gchar*)&header_size, sizeof(header_size), &bytes_num, null_ptr) != G_IO_STATUS_NORMAL) || (bytes_num != sizeof(header_size))) { g_critical("Can't read header size"); return SC_FALSE; } if (header_size != sizeof(header)) { g_critical("Invalid header size %d != %d", header_size, (int)sizeof(header)); return SC_FALSE; } if ((g_io_channel_read_chars(in_file, (gchar*)&header, sizeof(header), &bytes_num, null_ptr) != G_IO_STATUS_NORMAL) || (bytes_num != sizeof(header))) { g_critical("Can't read header of segments: %s", segments_path); return SC_FALSE; } *segments_num = header.segments_num; /// TODO: Check version checksum = g_checksum_new(_checksum_type()); g_assert(checksum); g_checksum_reset(checksum); // chek data for (i = 0; i < *segments_num; ++i) { seg = sc_segment_new(i); segments[i] = seg; g_io_channel_read_chars(in_file, (gchar*)seg->elements, SC_SEG_ELEMENTS_SIZE_BYTE, &bytes_num, null_ptr); sc_segment_loaded(seg); if (bytes_num != SC_SEG_ELEMENTS_SIZE_BYTE) { g_error("Error while read data for segment: %d", i); is_valid = SC_FALSE; break; } g_checksum_update(checksum, (guchar*)seg->elements, SC_SEG_ELEMENTS_SIZE_BYTE); } if (is_valid == SC_TRUE) { // compare checksum g_checksum_get_digest(checksum, calculated_checksum, &bytes_num); if (bytes_num != SC_STORAGE_SEG_CHECKSUM_SIZE) is_valid = SC_FALSE; else is_valid = (memcmp(calculated_checksum, header.checksum, SC_STORAGE_SEG_CHECKSUM_SIZE) == 0) ? SC_TRUE : SC_FALSE; } if (is_valid == SC_FALSE) { *segments_num = 0; for (i = 0; i < SC_SEGMENT_MAX; ++i) { if (segments[i]) { sc_segment_free(segments[i]); segments[i] = null_ptr; } } } g_checksum_free(checksum); g_io_channel_shutdown(in_file, FALSE, null_ptr); if (is_valid == SC_FALSE) return SC_FALSE; } g_message("Segments loaded: %u", *segments_num); g_assert(fm_engine != null_ptr); g_message("Check file memory state"); sc_bool r = sc_fm_clean_state(fm_engine) == SC_RESULT_OK; if (r == SC_FALSE) g_error("File memory wasn't check properly"); return r; }
static RemminaFile* remmina_rdp_file_import_channel(GIOChannel* channel) { gchar* p; const gchar* enc; gchar* line = NULL; GError* error = NULL; gsize bytes_read = 0; RemminaFile* remminafile; guchar magic[2] = { 0 }; if (g_io_channel_set_encoding(channel, NULL, &error) != G_IO_STATUS_NORMAL) { g_print("g_io_channel_set_encoding: %s\n", error->message); return NULL; } /* Try to detect the UTF-16 encoding */ if (g_io_channel_read_chars(channel, (gchar*) magic, 2, &bytes_read, &error) != G_IO_STATUS_NORMAL) { g_print("g_io_channel_read_chars: %s\n", error->message); return NULL; } if (magic[0] == 0xFF && magic[1] == 0xFE) { enc = "UTF-16LE"; } else if (magic[0] == 0xFE && magic[1] == 0xFF) { enc = "UTF-16BE"; } else { enc = "UTF-8"; if (g_io_channel_seek(channel, 0, G_SEEK_SET) != G_IO_ERROR_NONE) { g_print("g_io_channel_seek: failed\n"); return NULL; } } if (g_io_channel_set_encoding(channel, enc, &error) != G_IO_STATUS_NORMAL) { g_print("g_io_channel_set_encoding: %s\n", error->message); return NULL; } remminafile = remmina_plugin_service->file_new(); while (g_io_channel_read_line(channel, &line, NULL, &bytes_read, &error) == G_IO_STATUS_NORMAL) { if (line == NULL) break; line[bytes_read] = '\0'; p = strchr(line, ':'); if (p) { *p++ = '\0'; p = strchr (p, ':'); if (p) { p++; remmina_rdp_file_import_field(remminafile, line, p); } } g_free(line); } if (remmina_plugin_service->file_get_int(remminafile, "resolution_width", 0) > 0 && remmina_plugin_service->file_get_int(remminafile, "resolution_height", 0) > 0) { p = g_strdup_printf("%ix%i", remmina_plugin_service->file_get_int(remminafile, "resolution_width", 0), remmina_plugin_service->file_get_int(remminafile, "resolution_height", 0)); remmina_plugin_service->file_set_string(remminafile, "resolution", p); g_free(p); } remmina_plugin_service->file_set_string(remminafile, "name", remmina_plugin_service->file_get_string(remminafile, "server")); remmina_plugin_service->file_set_string(remminafile, "protocol", "RDP"); return remminafile; }
static int _progress(Prefs * prefs, char * argv[]) { Progress p; struct stat st; GtkWidget * vbox; GtkWidget * hbox; GtkSizeGroup * left; GtkSizeGroup * right; GtkWidget * widget; PangoFontDescription * bold; char const * q; unsigned long id; memset(&p, 0, sizeof(p)); p.prefs = prefs; if(prefs->bufsiz == 0) errno = EINVAL; if(prefs->bufsiz == 0 || (p.buf = malloc(prefs->bufsiz)) == NULL) return _progress_error(&p, "malloc", 1); p.bufsiz = prefs->bufsiz; if(pipe(p.fds) != 0) return _progress_error(&p, "pipe", 1); if((p.pid = fork()) == -1) { close(p.fds[0]); close(p.fds[1]); return _progress_error(&p, "fork", 1); } if(p.pid != 0) return _progress_exec(&p, argv); close(p.fds[0]); if(gettimeofday(&p.tv, NULL) != 0) return _progress_error(&p, "gettimeofday", 1); if(prefs->filename == NULL) prefs->filename = _("Standard input"); else if((p.fd = open(prefs->filename, O_RDONLY)) < 0) return _progress_error(&p, prefs->filename, 1); else if(fstat(p.fd, &st) == 0 && S_ISREG(st.st_mode)) prefs->length = st.st_size; p.in_channel = g_io_channel_unix_new(p.fd); g_io_channel_set_encoding(p.in_channel, NULL, NULL); p.in_id = 0; g_idle_add(_progress_idle_in, &p); p.out_channel = g_io_channel_unix_new(p.fds[1]); g_io_channel_set_encoding(p.out_channel, NULL, NULL); p.out_id = 0; /* graphical interface */ if((prefs->flags & PREFS_x) == 0) { p.window = gtk_window_new(GTK_WINDOW_TOPLEVEL); #if GTK_CHECK_VERSION(3, 0, 0) && !GTK_CHECK_VERSION(3, 14, 0) gtk_window_set_has_resize_grip(GTK_WINDOW(p.window), FALSE); #endif gtk_window_set_title(GTK_WINDOW(p.window), prefs->title != NULL ? prefs->title : _("Progress")); g_signal_connect_swapped(p.window, "delete-event", G_CALLBACK( _progress_closex), p.window); } else { p.window = gtk_plug_new(0); g_signal_connect_swapped(p.window, "embedded", G_CALLBACK( _progress_embedded), &p); } #if GTK_CHECK_VERSION(3, 0, 0) vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); #else vbox = gtk_vbox_new(FALSE, 0); hbox = gtk_hbox_new(FALSE, 0); #endif left = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL); right = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL); /* file */ widget = gtk_label_new(_("File: ")); bold = pango_font_description_new(); pango_font_description_set_weight(bold, PANGO_WEIGHT_BOLD); #if GTK_CHECK_VERSION(3, 0, 0) gtk_widget_override_font(widget, bold); g_object_set(widget, "halign", GTK_ALIGN_START, NULL); #else gtk_widget_modify_font(widget, bold); gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5); #endif gtk_size_group_add_widget(left, widget); gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0); if((q = g_filename_to_utf8(prefs->filename, -1, NULL, NULL, NULL)) == NULL) q = prefs->filename; widget = gtk_label_new(q); gtk_label_set_ellipsize(GTK_LABEL(widget), PANGO_ELLIPSIZE_MIDDLE); #if GTK_CHECK_VERSION(3, 0, 0) g_object_set(widget, "halign", GTK_ALIGN_START, NULL); #else gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5); #endif gtk_size_group_add_widget(right, widget); gtk_box_pack_start(GTK_BOX(hbox), widget, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 0); /* done */ #if GTK_CHECK_VERSION(3, 0, 0) hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); #else hbox = gtk_hbox_new(FALSE, 0); #endif widget = gtk_label_new(_("Done: ")); #if GTK_CHECK_VERSION(3, 0, 0) gtk_widget_override_font(widget, bold); g_object_set(widget, "halign", GTK_ALIGN_START, NULL); #else gtk_widget_modify_font(widget, bold); gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5); #endif gtk_size_group_add_widget(left, widget); gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0); p.done = gtk_label_new(_("0.0 kB")); #if GTK_CHECK_VERSION(3, 0, 0) g_object_set(p.done, "halign", GTK_ALIGN_START, NULL); #else gtk_misc_set_alignment(GTK_MISC(p.done), 0.0, 0.5); #endif gtk_size_group_add_widget(right, p.done); gtk_box_pack_start(GTK_BOX(hbox), p.done, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 4); /* remaining */ #if GTK_CHECK_VERSION(3, 0, 0) hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); #else hbox = gtk_hbox_new(FALSE, 0); #endif widget = gtk_label_new(_("Remaining: ")); #if GTK_CHECK_VERSION(3, 0, 0) gtk_widget_override_font(widget, bold); g_object_set(widget, "halign", GTK_ALIGN_START, NULL); #else gtk_widget_modify_font(widget, bold); gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5); #endif gtk_size_group_add_widget(left, widget); gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0); p.remaining = gtk_label_new(""); g_timeout_add(250, _progress_timeout, &p); #if GTK_CHECK_VERSION(3, 0, 0) g_object_set(p.remaining, "halign", GTK_ALIGN_START, NULL); #else gtk_misc_set_alignment(GTK_MISC(p.remaining), 0.0, 0.5); #endif gtk_size_group_add_widget(right, p.remaining); gtk_box_pack_start(GTK_BOX(hbox), p.remaining, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 4); /* progress */ p.progress = gtk_progress_bar_new(); p.pulse = 0; if(prefs->prefix != NULL) { #if GTK_CHECK_VERSION(3, 0, 0) hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); #else hbox = gtk_hbox_new(FALSE, 0); #endif widget = gtk_label_new(prefs->prefix); #if GTK_CHECK_VERSION(3, 0, 0) g_object_set(widget, "halign", GTK_ALIGN_START, NULL); #else gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5); #endif gtk_size_group_add_widget(left, widget); gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0); gtk_size_group_add_widget(right, p.progress); gtk_box_pack_start(GTK_BOX(hbox), p.progress, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 4); } else gtk_box_pack_start(GTK_BOX(vbox), p.progress, TRUE, TRUE, 4); /* cancel */ #if GTK_CHECK_VERSION(3, 0, 0) hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); #else hbox = gtk_hbox_new(FALSE, 0); #endif #if GTK_CHECK_VERSION(3, 10, 0) widget = gtk_button_new_with_label(_("Cancel")); gtk_button_set_image(GTK_BUTTON(widget), gtk_image_new_from_icon_name(GTK_STOCK_CANCEL, GTK_ICON_SIZE_BUTTON)); #else widget = gtk_button_new_from_stock(GTK_STOCK_CANCEL); #endif g_signal_connect(G_OBJECT(widget), "clicked", G_CALLBACK( _progress_cancel), NULL); gtk_box_pack_end(GTK_BOX(hbox), widget, FALSE, TRUE, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, TRUE, 0); gtk_container_add(GTK_CONTAINER(p.window), vbox); gtk_container_set_border_width(GTK_CONTAINER(p.window), 4); gtk_widget_show_all(vbox); if((prefs->flags & PREFS_x) == 0) /* show the window */ gtk_widget_show(p.window); else { /* print the window ID and force a flush */ id = gtk_plug_get_id(GTK_PLUG(p.window)); printf("%lu\n", id); fclose(stdout); } gtk_main(); close(p.fd); close(p.fds[1]); return p.ret; }
void CWatcher::Add(int fd, int type, void *callback, intptr_t param) { WATCH *data = NULL; WATCH **pwatch; int i; for (i = 0; i < count(); i++) { if (watch[i]->fd == fd) { data = watch[i]; break; } } if (!data) { if (type == GB_WATCH_NONE || !callback) return; pwatch = (WATCH **)GB.Add(&watch); GB.Alloc(POINTER(pwatch), sizeof(WATCH)); data = *pwatch; data->fd = fd; data->channel_read = data->channel_write = 0; data->callback_read = data->callback_write = 0; } if (data->callback_read && (type == GB_WATCH_NONE || type == GB_WATCH_READ)) { g_source_remove(data->id_read); g_io_channel_unref(data->channel_read); data->callback_read = 0; data->channel_read = 0; } if (data->callback_write && (type == GB_WATCH_NONE || type == GB_WATCH_WRITE)) { g_source_remove(data->id_write); g_io_channel_unref(data->channel_write); data->callback_write = 0; data->channel_write = 0; } if (callback) { if (type == GB_WATCH_READ) { data->callback_read = (WATCH_CALLBACK)callback; data->param_read = param; data->channel_read = g_io_channel_unix_new(fd); g_io_channel_set_encoding(data->channel_read, NULL, NULL); data->id_read = g_io_add_watch_full(data->channel_read, G_PRIORITY_LOW, G_IO_IN, watch_adaptor, (void*)data, NULL); } else if (type == GB_WATCH_WRITE) { data->callback_write = (WATCH_CALLBACK)callback; data->param_write = param; data->channel_write = g_io_channel_unix_new(fd); g_io_channel_set_encoding(data->channel_write, NULL, NULL); data->id_write = g_io_add_watch_full(data->channel_write, G_PRIORITY_LOW, G_IO_OUT, watch_adaptor, (void*)data, NULL); } } if (!data->callback_read && !data->callback_write) { GB.Free(POINTER(&data)); GB.Remove(&watch, i, 1); MAIN_check_quit(); } }
static void start_ntp(char *server) { GIOChannel *channel; struct sockaddr_in addr; int tos = IPTOS_LOWDELAY, timestamp = 1; if (!server) return; DBG("server %s", server); if (channel_watch > 0) goto send; transmit_fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (transmit_fd < 0) { connman_error("Failed to open time server socket"); return; } memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; if (bind(transmit_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { connman_error("Failed to bind time server socket"); close(transmit_fd); return; } if (setsockopt(transmit_fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0) { connman_error("Failed to set type of service option"); close(transmit_fd); return; } if (setsockopt(transmit_fd, SOL_SOCKET, SO_TIMESTAMP, ×tamp, sizeof(timestamp)) < 0) { connman_error("Failed to enable timestamp support"); close(transmit_fd); return; } channel = g_io_channel_unix_new(transmit_fd); if (!channel) { close(transmit_fd); return; } g_io_channel_set_encoding(channel, NULL, NULL); g_io_channel_set_buffered(channel, FALSE); g_io_channel_set_close_on_unref(channel, TRUE); channel_watch = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, received_data, NULL, NULL); g_io_channel_unref(channel); send: send_packet(transmit_fd, server); }
gboolean gimp_plug_in_open (GimpPlugIn *plug_in, GimpPlugInCallMode call_mode, gboolean synchronous) { gchar *progname; gint my_read[2]; gint my_write[2]; gchar **envp; const gchar *args[9]; gchar **argv; gint argc; gchar *interp, *interp_arg; gchar *read_fd, *write_fd; const gchar *mode; gchar *stm; GError *error = NULL; gboolean debug; guint debug_flag; guint spawn_flags; g_return_val_if_fail (GIMP_IS_PLUG_IN (plug_in), FALSE); g_return_val_if_fail (plug_in->call_mode == GIMP_PLUG_IN_CALL_NONE, FALSE); /* Open two pipes. (Bidirectional communication). */ if ((pipe (my_read) == -1) || (pipe (my_write) == -1)) { gimp_message (plug_in->manager->gimp, NULL, GIMP_MESSAGE_ERROR, "Unable to run plug-in \"%s\"\n(%s)\n\npipe() failed: %s", gimp_object_get_name (plug_in), gimp_file_get_utf8_name (plug_in->file), g_strerror (errno)); return FALSE; } #if defined(G_WITH_CYGWIN) /* Set to binary mode */ setmode (my_read[0], _O_BINARY); setmode (my_write[0], _O_BINARY); setmode (my_read[1], _O_BINARY); setmode (my_write[1], _O_BINARY); #endif #ifdef G_OS_WIN32 /* Prevent the plug-in from inheriting our ends of the pipes */ SetHandleInformation ((HANDLE) _get_osfhandle (my_read[0]), HANDLE_FLAG_INHERIT, 0); SetHandleInformation ((HANDLE) _get_osfhandle (my_write[1]), HANDLE_FLAG_INHERIT, 0); #endif plug_in->my_read = g_io_channel_unix_new (my_read[0]); plug_in->my_write = g_io_channel_unix_new (my_write[1]); plug_in->his_read = g_io_channel_unix_new (my_write[0]); plug_in->his_write = g_io_channel_unix_new (my_read[1]); g_io_channel_set_encoding (plug_in->my_read, NULL, NULL); g_io_channel_set_encoding (plug_in->my_write, NULL, NULL); g_io_channel_set_encoding (plug_in->his_read, NULL, NULL); g_io_channel_set_encoding (plug_in->his_write, NULL, NULL); g_io_channel_set_buffered (plug_in->my_read, FALSE); g_io_channel_set_buffered (plug_in->my_write, FALSE); g_io_channel_set_buffered (plug_in->his_read, FALSE); g_io_channel_set_buffered (plug_in->his_write, FALSE); g_io_channel_set_close_on_unref (plug_in->my_read, TRUE); g_io_channel_set_close_on_unref (plug_in->my_write, TRUE); g_io_channel_set_close_on_unref (plug_in->his_read, TRUE); g_io_channel_set_close_on_unref (plug_in->his_write, TRUE); /* Remember the file descriptors for the pipes. */ read_fd = g_strdup_printf ("%d", g_io_channel_unix_get_fd (plug_in->his_read)); write_fd = g_strdup_printf ("%d", g_io_channel_unix_get_fd (plug_in->his_write)); switch (call_mode) { case GIMP_PLUG_IN_CALL_QUERY: mode = "-query"; debug_flag = GIMP_DEBUG_WRAP_QUERY; break; case GIMP_PLUG_IN_CALL_INIT: mode = "-init"; debug_flag = GIMP_DEBUG_WRAP_INIT; break; case GIMP_PLUG_IN_CALL_RUN: mode = "-run"; debug_flag = GIMP_DEBUG_WRAP_RUN; break; default: g_assert_not_reached (); } stm = g_strdup_printf ("%d", plug_in->manager->gimp->stack_trace_mode); progname = g_file_get_path (plug_in->file); interp = gimp_interpreter_db_resolve (plug_in->manager->interpreter_db, progname, &interp_arg); argc = 0; if (interp) args[argc++] = interp; if (interp_arg) args[argc++] = interp_arg; args[argc++] = progname; args[argc++] = "-gimp"; args[argc++] = read_fd; args[argc++] = write_fd; args[argc++] = mode; args[argc++] = stm; args[argc++] = NULL; argv = (gchar **) args; envp = gimp_environ_table_get_envp (plug_in->manager->environ_table); spawn_flags = (G_SPAWN_LEAVE_DESCRIPTORS_OPEN | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_CHILD_INHERITS_STDIN); debug = FALSE; if (plug_in->manager->debug) { gchar **debug_argv = gimp_plug_in_debug_argv (plug_in->manager->debug, progname, debug_flag, args); if (debug_argv) { debug = TRUE; argv = debug_argv; spawn_flags |= G_SPAWN_SEARCH_PATH; } } /* Fork another process. We'll remember the process id so that we * can later use it to kill the filter if necessary. */ if (! g_spawn_async (NULL, argv, envp, spawn_flags, gimp_plug_in_prep_for_exec, plug_in, &plug_in->pid, &error)) { gimp_message (plug_in->manager->gimp, NULL, GIMP_MESSAGE_ERROR, "Unable to run plug-in \"%s\"\n(%s)\n\n%s", gimp_object_get_name (plug_in), gimp_file_get_utf8_name (plug_in->file), error->message); g_clear_error (&error); g_free (progname); goto cleanup; } g_io_channel_unref (plug_in->his_read); plug_in->his_read = NULL; g_io_channel_unref (plug_in->his_write); plug_in->his_write = NULL; if (! synchronous) { GSource *source; source = g_io_create_watch (plug_in->my_read, G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP); g_source_set_callback (source, (GSourceFunc) gimp_plug_in_recv_message, plug_in, NULL); g_source_set_can_recurse (source, TRUE); plug_in->input_id = g_source_attach (source, NULL); g_source_unref (source); } plug_in->open = TRUE; plug_in->call_mode = call_mode; gimp_plug_in_manager_add_open_plug_in (plug_in->manager, plug_in); cleanup: if (debug) g_free (argv); g_free (read_fd); g_free (write_fd); g_free (stm); g_free (interp); g_free (interp_arg); g_free (progname); return plug_in->open; }
static GstStateChangeReturn theora_enc_change_state (GstElement * element, GstStateChange transition) { GstTheoraEnc *enc; GstStateChangeReturn ret; enc = GST_THEORA_ENC (element); switch (transition) { case GST_STATE_CHANGE_NULL_TO_READY: break; case GST_STATE_CHANGE_READY_TO_PAUSED: GST_DEBUG_OBJECT (enc, "READY->PAUSED Initing theora state"); th_info_init (&enc->info); th_comment_init (&enc->comment); enc->packetno = 0; enc->force_keyframe = FALSE; if (enc->multipass_mode >= MULTIPASS_MODE_FIRST_PASS) { GError *err = NULL; if (!enc->multipass_cache_file) { ret = GST_STATE_CHANGE_FAILURE; GST_ELEMENT_ERROR (enc, LIBRARY, SETTINGS, (NULL), (NULL)); return ret; } enc->multipass_cache_fd = g_io_channel_new_file (enc->multipass_cache_file, (enc->multipass_mode == MULTIPASS_MODE_FIRST_PASS ? "w" : "r"), &err); if (enc->multipass_mode == MULTIPASS_MODE_SECOND_PASS) enc->multipass_cache_adapter = gst_adapter_new (); if (!enc->multipass_cache_fd) { ret = GST_STATE_CHANGE_FAILURE; GST_ELEMENT_ERROR (enc, RESOURCE, OPEN_READ, (NULL), ("Failed to open multipass cache file: %s", err->message)); g_error_free (err); return ret; } g_io_channel_set_encoding (enc->multipass_cache_fd, NULL, NULL); } break; case GST_STATE_CHANGE_PAUSED_TO_PLAYING: break; default: break; } ret = parent_class->change_state (element, transition); switch (transition) { case GST_STATE_CHANGE_PLAYING_TO_PAUSED: break; case GST_STATE_CHANGE_PAUSED_TO_READY: GST_DEBUG_OBJECT (enc, "PAUSED->READY Clearing theora state"); if (enc->encoder) { th_encode_free (enc->encoder); enc->encoder = NULL; } th_comment_clear (&enc->comment); th_info_clear (&enc->info); theora_enc_clear (enc); enc->initialised = FALSE; break; case GST_STATE_CHANGE_READY_TO_NULL: break; default: break; } return ret; }
/** * Register an I/O monitor; reads and returns a chunk of specified size * * @param fd File Descriptor; this takes priority over file; -1 if not used * @param file Path to the file * @param error_policy MCE_IO_ERROR_POLICY_EXIT to exit on error, * MCE_IO_ERROR_POLICY_WARN to warn about errors * but ignore them, * MCE_IO_ERROR_POLICY_IGNORE to silently ignore errors * @param monitored_conditions The GIOConditions to monitor * @param rewind_policy TRUE to seek to the beginning, * FALSE to stay at current position * @param callback Function to call with result * @param chunk_size The number of bytes to read in each chunk * @return An I/O monitor cookie on success, NULL on failure */ gconstpointer mce_register_io_monitor_chunk(const gint fd, const gchar *const file, error_policy_t error_policy, GIOCondition monitored_conditions, gboolean rewind_policy, iomon_cb callback, gulong chunk_size) { iomon_struct *iomon = NULL; GError *error = NULL; iomon = mce_register_io_monitor(fd, file, error_policy, monitored_conditions, callback); if (iomon == NULL) goto EXIT; /* Set the read chunk size */ iomon->chunk_size = chunk_size; /* Verify that the rewind policy is sane */ if (iomon->seekable) { /* Set the rewind policy */ iomon->rewind = rewind_policy; } else if (rewind_policy == TRUE) { mce_log(LL_ERR, "Attempting to set rewind policy to TRUE " "on non-seekable I/O channel `%s'", file); iomon->rewind = FALSE; } /* We only read this file in binary form */ (void)g_io_channel_set_encoding(iomon->iochan, NULL, &error); /* No buffering since we're using this for reading data from * device drivers and need to keep the i/o state in sync * between kernel and user space for the automatic suspend * prevention via wakelocks to work */ g_io_channel_set_buffered(iomon->iochan, FALSE); /* Reset errno, * to avoid false positives down the line */ errno = 0; g_clear_error(&error); /* Don't block */ (void)g_io_channel_set_flags(iomon->iochan, G_IO_FLAG_NONBLOCK, &error); /* Reset errno, * to avoid false positives down the line */ errno = 0; g_clear_error(&error); /* Set the I/O monitor type and call resume to add an I/O watch */ iomon->type = IOMON_CHUNK; mce_resume_io_monitor(iomon); EXIT: return iomon; }
gboolean netinfo_io_text_buffer_dialog (GIOChannel * channel, GIOCondition condition, gpointer data) { gchar *text = NULL; gsize len; Netinfo *netinfo = (Netinfo *) data; GError *err = NULL; const gchar *encoding; g_return_val_if_fail (channel != NULL, FALSE); g_return_val_if_fail (netinfo != NULL, FALSE); g_return_val_if_fail (netinfo->output != NULL, FALSE); #ifdef DEBUG switch (condition) { case G_IO_IN: g_print ("G_IO_IN\n"); break; case G_IO_HUP: g_print ("G_IO_HUP\n"); break; case G_IO_ERR: g_print ("G_IO_ERR\n"); break; case G_IO_NVAL: g_print ("G_IO_NVAL\n"); break; default: g_print ("Nothing\n"); break; } #endif /* DEBUG */ if (condition & G_IO_IN) { GIOStatus status; status = g_io_channel_read_line (channel, &text, &len, NULL, &err); if (status == G_IO_STATUS_NORMAL) { if (netinfo->command_output) { g_string_append (netinfo->command_output, text); g_free (text); text = g_string_free (netinfo->command_output, FALSE); netinfo->command_output = NULL; } if (netinfo->process_line != NULL) { (netinfo->process_line) ((gpointer) netinfo, text, len, NULL); } } else if (status == G_IO_STATUS_AGAIN) { char buf[1]; /* A non-terminated line was read, read the data into the buffer. */ status = g_io_channel_read_chars (channel, buf, 1, NULL, NULL); if (status == G_IO_STATUS_NORMAL) { if (netinfo->command_output == NULL) { netinfo->command_output = g_string_new (NULL); } g_string_append_c (netinfo->command_output, buf[0]); } } else if (status == G_IO_STATUS_EOF) { } else if (status == G_IO_STATUS_ERROR) { encoding = g_io_channel_get_encoding (channel); if (err->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE) { g_warning ("Warning: change of encoding: %s. The encoding " "was changed from %s to ISO-8859-1 only " "for this string\n", err->message, encoding); g_io_channel_set_encoding (channel, "ISO-8859-1", NULL); g_io_channel_read_line (channel, &text, &len, NULL, NULL); } else { g_warning ("Error: %s\n", err->message); g_free (text); g_free (err); } } g_free (text); return TRUE; } /* The condition is not G_IO_HUP | G_IO_ERR | G_IO_NVAL, so we are ready to receive a new request from the user */ close (netinfo->pipe_out); /*close (netinfo->pipe_err); */ if (condition & G_IO_HUP) { if (netinfo->child_pid > 0) waitpid (netinfo->child_pid, NULL, WNOHANG); netinfo_toggle_state (netinfo, ACTIVE, NULL); } if (condition & G_IO_NVAL) { gchar *msg_nval = _("Information not available"); int len_nval; len_nval = strlen (msg_nval); (netinfo->process_line) ((gpointer) netinfo, msg_nval, len_nval, NULL); } return FALSE; }
gint main (gint argc, gchar * argv[]) { GIOChannel *gio_r, *gio_w ; GError *gerr = NULL; GString *buffer; char *filename; char *srcdir = getenv ("srcdir"); gint rlength = 0; glong wlength = 0; gsize length_out; const gchar encoding[] = "EUC-JP"; GIOStatus status; GIOFlags flags; if (!srcdir) srcdir = "."; filename = g_strconcat (srcdir, G_DIR_SEPARATOR_S, "iochannel-test-infile", NULL); setbuf (stdout, NULL); /* For debugging */ gio_r = g_io_channel_new_file (filename, "r", &gerr); if (gerr) { g_warning ("Unable to open file %s: %s", filename, gerr->message); g_error_free (gerr); return 1; } gio_w = g_io_channel_new_file ("iochannel-test-outfile", "w", &gerr); if (gerr) { g_warning ("Unable to open file %s: %s", "iochannel-test-outfile", gerr->message); g_error_free (gerr); return 1; } g_io_channel_set_encoding (gio_r, encoding, &gerr); if (gerr) { g_warning (gerr->message); g_error_free (gerr); return 1; } g_io_channel_set_buffer_size (gio_r, BUFFER_SIZE); status = g_io_channel_set_flags (gio_r, G_IO_FLAG_NONBLOCK, &gerr); if (status == G_IO_STATUS_ERROR) { g_warning (gerr->message); g_error_free (gerr); gerr = NULL; } flags = g_io_channel_get_flags (gio_r); buffer = g_string_sized_new (BUFFER_SIZE); while (TRUE) { do status = g_io_channel_read_line_string (gio_r, buffer, NULL, &gerr); while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; rlength += buffer->len; do status = g_io_channel_write_chars (gio_w, buffer->str, buffer->len, &length_out, &gerr); while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; wlength += length_out; if (length_out < buffer->len) g_warning ("Only wrote part of the line."); #ifdef VERBOSE g_print ("%s", buffer->str); #endif g_string_truncate (buffer, 0); } switch (status) { case G_IO_STATUS_EOF: break; case G_IO_STATUS_ERROR: g_warning (gerr->message); g_error_free (gerr); gerr = NULL; break; default: g_warning ("Abnormal exit from write loop."); break; } do status = g_io_channel_flush (gio_w, &gerr); while (status == G_IO_STATUS_AGAIN); if (status == G_IO_STATUS_ERROR) { g_warning (gerr->message); g_error_free (gerr); gerr = NULL; } #ifdef VERBOSE g_print ("read %d bytes, wrote %ld bytes\n", rlength, wlength); #endif g_io_channel_unref(gio_r); g_io_channel_unref(gio_w); test_small_writes (); return 0; }
gboolean dates_import_calendar_data_from_file (ECal *cal, gchar *filename, GError **error) { GError *tmp_error = NULL; GIOChannel *channel = NULL; gchar *line; gsize length; gint num_comp_imported = 0; channel = g_io_channel_new_file (filename, "r", &tmp_error); if (tmp_error != NULL) { g_warning ("Error when opening file: %s", tmp_error->message); g_propagate_error (error, tmp_error); return FALSE; } else { GIOStatus status; icalparser *parser = icalparser_new (); /* set the channel as binary mode and let icalparser_add_line * handle encoding */ g_io_channel_set_encoding (channel, NULL, &tmp_error); if (tmp_error != NULL) { g_warning ("Error when set encoding: %s", tmp_error->message); g_propagate_error (error, tmp_error); g_io_channel_unref (channel); return FALSE; } /* Read the from the file line by line and until EOF */ while ((status = g_io_channel_read_line (channel, &line, &length, NULL, &tmp_error)) == G_IO_STATUS_NORMAL) { icalcomponent *icomp = NULL; /* The parser returns an icalcomponent when it has one */ icomp = icalparser_add_line (parser, line); g_free (line); if (icomp) { gchar *uid = NULL; icalcompiter iter; icalcomponent *subcomp; /* The component is a top-level one and e_cal_create_object only * accepts VEVENTs. Iterate through the VEVENTS. */ iter = icalcomponent_begin_component (icomp, ICAL_VEVENT_COMPONENT); while ((subcomp = icalcompiter_deref (&iter)) != NULL) { if (!e_cal_create_object (cal, subcomp, &uid, &tmp_error)) { g_warning ("Creation of imported event failed: %s", tmp_error->message); g_propagate_error (error, tmp_error); if (parser) icalparser_free (parser); if (icomp) icalcomponent_free (icomp); if (channel) g_io_channel_unref (channel); g_free (uid); return FALSE; } num_comp_imported ++; icalcompiter_next (&iter); g_free (uid); } icalcomponent_free (icomp); } } if (parser) icalparser_free (parser); if (tmp_error != NULL) { g_warning ("Error when reading from file: %s", tmp_error->message); g_propagate_error (error, tmp_error); g_io_channel_unref (channel); return FALSE; } } if (channel) g_io_channel_unref (channel); if (num_comp_imported > 0) { return TRUE; } else { *error = g_error_new_literal (g_quark_from_string ("Dates"), 1, _("No calendar events found.")); return FALSE; } }
static gboolean user_input(const char *label, gboolean hidden, user_input_cb func, gpointer user_data) { struct user_input_data *data; struct termios new_termios; GIOChannel *channel; guint watch; ssize_t len; data = g_try_new0(struct user_input_data, 1); if (data == NULL) return FALSE; data->str = g_string_sized_new(32); data->cb = func; data->user_data = user_data; data->hidden = hidden; data->fd = open("/dev/tty", O_RDWR | O_NOCTTY | O_CLOEXEC); if (data->fd < 0) goto error; if (tcgetattr(data->fd, &data->saved_termios) < 0) { close(data->fd); goto error; } new_termios = data->saved_termios; if (data->hidden == TRUE) new_termios.c_lflag &= ~(ICANON|ECHO); else new_termios.c_lflag &= ~ICANON; new_termios.c_cc[VMIN] = 1; new_termios.c_cc[VTIME] = 0; tcsetattr(data->fd, TCSADRAIN, &new_termios); channel = g_io_channel_unix_new(data->fd); g_io_channel_set_encoding(channel, NULL, NULL); g_io_channel_set_buffered(channel, FALSE); watch = g_io_add_watch(channel, G_IO_IN, keyboard_input, data); g_io_channel_unref(channel); if (watch == 0) goto error; len = write(data->fd, label, strlen(label)); if (len < 0) goto error; len = write(data->fd, ": ", 2); if (len < 0) goto error; return TRUE; error: g_string_free(data->str, TRUE); g_free(data); return FALSE; }
/* This function retrieves the pixel size from an SVG file. Parsing * stops after the first chunk that provided the parser with enough * information to determine the size. This is usally the opening * <svg> element and should thus be in the first chunk (1024 bytes). */ static gboolean load_rsvg_size (const gchar *filename, SvgLoadVals *vals, GError **error) { RsvgHandle *handle; GIOChannel *io; GIOStatus status = G_IO_STATUS_NORMAL; gboolean success = TRUE; gboolean done = FALSE; io = g_io_channel_new_file (filename, "r", error); if (!io) return FALSE; g_io_channel_set_encoding (io, NULL, NULL); handle = rsvg_handle_new (); rsvg_handle_set_dpi (handle, vals->resolution); vals->width = SVG_DEFAULT_SIZE; vals->height = SVG_DEFAULT_SIZE; while (success && status != G_IO_STATUS_EOF && (! done)) { gchar buf[1024]; gsize len; RsvgDimensionData dim = { 0, 0, 0.0, 0.0 }; status = g_io_channel_read_chars (io, buf, sizeof (buf), &len, error); switch (status) { case G_IO_STATUS_ERROR: success = FALSE; break; case G_IO_STATUS_EOF: success = rsvg_handle_close (handle, error); break; case G_IO_STATUS_NORMAL: success = rsvg_handle_write (handle, (const guchar *) buf, len, error); rsvg_handle_get_dimensions (handle, &dim); if (dim.width > 0 && dim.height > 0) { vals->width = dim.width; vals->height = dim.height; done = TRUE; } break; case G_IO_STATUS_AGAIN: break; } } if (size_label) { if (done) { gchar *text = g_strdup_printf (_("%d × %d"), vals->width, vals->height); gtk_label_set_text (GTK_LABEL (size_label), text); g_free (text); } else { gtk_label_set_text (GTK_LABEL (size_label), _("SVG file does not\nspecify a size!")); } } g_io_channel_unref (io); g_object_unref (handle); if (vals->width < 1) vals->width = 1; if (vals->height < 1) vals->height = 1; return success; }
GObex *g_obex_new(GIOChannel *io, GObexTransportType transport_type, gssize io_rx_mtu, gssize io_tx_mtu) { GObex *obex; GIOCondition cond; if (gobex_debug == 0) { const char *env = g_getenv("GOBEX_DEBUG"); if (env) { gobex_debug = g_parse_debug_string(env, keys, 7); g_setenv("G_MESSAGES_DEBUG", "gobex", FALSE); } else gobex_debug = G_OBEX_DEBUG_NONE; } g_obex_debug(G_OBEX_DEBUG_COMMAND, ""); if (io == NULL) return NULL; if (io_rx_mtu >= 0 && io_rx_mtu < G_OBEX_MINIMUM_MTU) return NULL; if (io_tx_mtu >= 0 && io_tx_mtu < G_OBEX_MINIMUM_MTU) return NULL; obex = g_new0(GObex, 1); obex->io = g_io_channel_ref(io); obex->ref_count = 1; obex->conn_id = CONNID_INVALID; obex->rx_last_op = G_OBEX_OP_NONE; obex->io_rx_mtu = io_rx_mtu; obex->io_tx_mtu = io_tx_mtu; if (io_rx_mtu > G_OBEX_MAXIMUM_MTU) obex->rx_mtu = G_OBEX_MAXIMUM_MTU; else if (io_rx_mtu < G_OBEX_MINIMUM_MTU) obex->rx_mtu = G_OBEX_DEFAULT_MTU; else obex->rx_mtu = io_rx_mtu; obex->tx_mtu = G_OBEX_MINIMUM_MTU; obex->tx_queue = g_queue_new(); obex->rx_buf = g_malloc(obex->rx_mtu); obex->tx_buf = g_malloc(obex->tx_mtu); switch (transport_type) { case G_OBEX_TRANSPORT_STREAM: obex->read = read_stream; obex->write = write_stream; break; case G_OBEX_TRANSPORT_PACKET: obex->use_srm = TRUE; obex->read = read_packet; obex->write = write_packet; break; default: g_obex_unref(obex); return NULL; } g_io_channel_set_encoding(io, NULL, NULL); g_io_channel_set_buffered(io, FALSE); cond = G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL; obex->io_source = g_io_add_watch(io, cond, incoming_data, obex); return obex; }
GtkWidget * html_create_widget (GtkWidget * dlg) { GtkWidget *sw; WebKitSettings *settings; SoupSession *sess; sw = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), options.hscroll_policy, options.vscroll_policy); view = WEBKIT_WEB_VIEW (webkit_web_view_new ()); gtk_container_add (GTK_CONTAINER (sw), GTK_WIDGET (view)); settings = webkit_web_view_get_settings (view); g_object_set (G_OBJECT(settings), "user-agent", "YAD3/" VERSION " (KHTML, like Gecko)", NULL); g_object_set (G_OBJECT(settings), "default-charset", "utf-8", NULL); g_object_set (G_OBJECT(settings), "enable-fullscreen", options.data.fullscreen, NULL); g_signal_connect (view, "decide-policy", G_CALLBACK (policy_cb), NULL); if (options.html_data.browser) { g_signal_connect (view, "context-menu", G_CALLBACK (menu_cb), NULL); if (!options.data.dialog_title) g_signal_connect (view, "notify::title", G_CALLBACK (title_cb), dlg); if (strcmp (options.data.window_icon, "yad") == 0) g_signal_connect (view, "notify::favicon", G_CALLBACK (icon_cb), dlg); } else { g_object_set (G_OBJECT(settings), "enable-caret-browsing", FALSE, NULL); g_object_set (G_OBJECT(settings), "enable-developer-extras", FALSE, NULL); g_object_set (G_OBJECT(settings), "enable-html5-database", FALSE, NULL); g_object_set (G_OBJECT(settings), "enable-html5-local-storage", FALSE, NULL); g_object_set (G_OBJECT(settings), "enable-offline-web-application-cache", FALSE, NULL); g_object_set (G_OBJECT(settings), "enable-page-cache", FALSE, NULL); g_object_set (G_OBJECT(settings), "enable-plugins", FALSE, NULL); g_object_set (G_OBJECT (settings), "enable-private-browsing", TRUE, NULL); g_signal_connect (view, "load-changed", G_CALLBACK (loaded_cb), NULL); } #if 0 sess = webkit_get_default_session (); soup_session_add_feature_by_type (sess, SOUP_TYPE_PROXY_RESOLVER_DEFAULT); g_object_set (G_OBJECT (sess), SOUP_SESSION_ACCEPT_LANGUAGE_AUTO, TRUE, NULL); #endif gtk_widget_show_all (sw); gtk_widget_grab_focus (GTK_WIDGET (view)); if (options.html_data.uri) load_uri (options.html_data.uri); else if (!options.html_data.browser) { GIOChannel *ch; inbuf = g_string_new (NULL); ch = g_io_channel_unix_new (0); g_io_channel_set_encoding (ch, NULL, NULL); g_io_channel_set_flags (ch, G_IO_FLAG_NONBLOCK, NULL); g_io_add_watch (ch, G_IO_IN | G_IO_HUP, handle_stdin, NULL); } return sw; }
/* Spawn passwd backend * Returns: TRUE on success, FALSE otherwise and sets error appropriately */ static gboolean spawn_passwd (PasswdHandler *passwd_handler, GError **error) { gchar *argv[2]; gchar *envp[1]; gint my_stdin, my_stdout, my_stderr; argv[0] = "/usr/bin/passwd"; /* Is it safe to rely on a hard-coded path? */ argv[1] = NULL; envp[0] = NULL; /* If we pass an empty array as the environment, * will the childs environment be empty, and the * locales set to the C default? From the manual: * "If envp is NULL, the child inherits its * parent'senvironment." * If I'm wrong here, we somehow have to set * the locales here. */ if (!g_spawn_async_with_pipes (NULL, /* Working directory */ argv, /* Argument vector */ envp, /* Environment */ G_SPAWN_DO_NOT_REAP_CHILD, /* Flags */ ignore_sigpipe, /* Child setup */ NULL, /* Data to child setup */ &passwd_handler->backend_pid, /* PID */ &my_stdin, /* Stdin */ &my_stdout, /* Stdout */ &my_stderr, /* Stderr */ error)) { /* GError */ /* An error occured */ free_passwd_resources (passwd_handler); return FALSE; } /* 2>&1 */ if (dup2 (my_stderr, my_stdout) == -1) { /* Failed! */ g_set_error_literal (error, PASSWD_ERROR, PASSWD_ERROR_BACKEND, strerror (errno)); /* Clean up */ stop_passwd (passwd_handler); return FALSE; } /* Open IO Channels */ passwd_handler->backend_stdin = g_io_channel_unix_new (my_stdin); passwd_handler->backend_stdout = g_io_channel_unix_new (my_stdout); /* Set raw encoding */ /* Set nonblocking mode */ if (g_io_channel_set_encoding (passwd_handler->backend_stdin, NULL, error) != G_IO_STATUS_NORMAL || g_io_channel_set_encoding (passwd_handler->backend_stdout, NULL, error) != G_IO_STATUS_NORMAL || g_io_channel_set_flags (passwd_handler->backend_stdin, G_IO_FLAG_NONBLOCK, error) != G_IO_STATUS_NORMAL || g_io_channel_set_flags (passwd_handler->backend_stdout, G_IO_FLAG_NONBLOCK, error) != G_IO_STATUS_NORMAL ) { /* Clean up */ stop_passwd (passwd_handler); return FALSE; } /* Turn off buffering */ g_io_channel_set_buffered (passwd_handler->backend_stdin, FALSE); g_io_channel_set_buffered (passwd_handler->backend_stdout, FALSE); /* Add IO Channel watcher */ passwd_handler->backend_stdout_watch_id = g_io_add_watch (passwd_handler->backend_stdout, G_IO_IN | G_IO_PRI, (GIOFunc) io_watch_stdout, passwd_handler); /* Add child watcher */ passwd_handler->backend_child_watch_id = g_child_watch_add (passwd_handler->backend_pid, (GChildWatchFunc) child_watch_cb, passwd_handler); /* Success! */ return TRUE; }
static void connect_confirm_cb(GIOChannel *io, gpointer data) { struct sap_connection *conn = server->conn; GError *gerr = NULL; bdaddr_t src, dst; char srcaddr[18], dstaddr[18]; int err; DBG("io %p data %p ", io, data); if (!io) return; if (conn) { g_io_channel_shutdown(io, TRUE, NULL); return; } conn = g_try_new0(struct sap_connection, 1); if (!conn) { error("Can't allocate memory for incomming SAP connection."); g_io_channel_shutdown(io, TRUE, NULL); return; } g_io_channel_set_encoding(io, NULL, NULL); g_io_channel_set_buffered(io, FALSE); server->conn = conn; conn->io = g_io_channel_ref(io); conn->state = SAP_STATE_DISCONNECTED; bt_io_get(io, BT_IO_RFCOMM, &gerr, BT_IO_OPT_SOURCE_BDADDR, &src, BT_IO_OPT_DEST_BDADDR, &dst, BT_IO_OPT_INVALID); if (gerr) { error("%s", gerr->message); g_error_free(gerr); sap_conn_remove(conn); return; } //client_to_be_authorized = &dst; ba2str(&dst, dstaddr); ba2str(&src, srcaddr); if(sap_check_weak_linkkey(srcaddr, dstaddr) == TRUE) { DBG("SAP weak_key was detected."); sap_connect_rsp(conn, SAP_STATUS_CONNECTION_FAILED, SAP_BUF_SIZE); sap_conn_remove(conn); return; } err = btd_request_authorization(&src, &dst, SAP_UUID, connect_auth_cb, conn); if (err < 0) { DBG("Authorization denied: %d %s", err, strerror(err)); sap_conn_remove(conn); return; } DBG("SAP incoming connection (sock %d) authorization.", g_io_channel_unix_get_fd(io)); }
/* cvs_add_task */ static int _cvs_add_task(CVS * cvs, char const * title, char const * directory, char * argv[]) { BrowserPluginHelper * helper = cvs->helper; CVSTask ** p; CVSTask * task; GSpawnFlags flags = G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD; gboolean res; GError * error = NULL; PangoFontDescription * font; char buf[256]; GtkWidget * vbox; GtkWidget * widget; if((p = realloc(cvs->tasks, sizeof(*p) * (cvs->tasks_cnt + 1))) == NULL) return -helper->error(helper->browser, strerror(errno), 1); cvs->tasks = p; if((task = object_new(sizeof(*task))) == NULL) return -helper->error(helper->browser, error_get(), 1); task->cvs = cvs; #ifdef DEBUG argv[0] = "echo"; #endif res = g_spawn_async_with_pipes(directory, argv, NULL, flags, NULL, NULL, &task->pid, NULL, &task->o_fd, &task->e_fd, &error); if(res != TRUE) { helper->error(helper->browser, error->message, 1); g_error_free(error); object_delete(task); return -1; } cvs->tasks[cvs->tasks_cnt++] = task; /* widgets */ font = pango_font_description_new(); pango_font_description_set_family(font, "monospace"); task->window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size(GTK_WINDOW(task->window), 600, 400); #if GTK_CHECK_VERSION(2, 6, 0) gtk_window_set_icon_name(GTK_WINDOW(task->window), plugin.icon); #endif snprintf(buf, sizeof(buf), "%s - %s (%s)", _("CVS"), title, directory); gtk_window_set_title(GTK_WINDOW(task->window), buf); g_signal_connect_swapped(task->window, "delete-event", G_CALLBACK( _cvs_task_on_closex), task); vbox = gtk_vbox_new(FALSE, 0); widget = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(widget), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); task->view = gtk_text_view_new(); gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(task->view), FALSE); gtk_text_view_set_editable(GTK_TEXT_VIEW(task->view), FALSE); gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(task->view), GTK_WRAP_WORD_CHAR); gtk_widget_modify_font(task->view, font); gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(widget), task->view); gtk_box_pack_start(GTK_BOX(vbox), widget, TRUE, TRUE, 0); task->statusbar = gtk_statusbar_new(); task->statusbar_id = 0; gtk_box_pack_start(GTK_BOX(vbox), task->statusbar, FALSE, TRUE, 0); gtk_container_add(GTK_CONTAINER(task->window), vbox); gtk_widget_show_all(task->window); pango_font_description_free(font); /* events */ task->source = g_child_watch_add(task->pid, _cvs_task_on_child_watch, task); task->o_channel = g_io_channel_unix_new(task->o_fd); if((g_io_channel_set_encoding(task->o_channel, NULL, &error)) != G_IO_STATUS_NORMAL) { helper->error(helper->browser, error->message, 1); g_error_free(error); } task->o_source = g_io_add_watch(task->o_channel, G_IO_IN, _cvs_task_on_io_can_read, task); task->e_channel = g_io_channel_unix_new(task->e_fd); if((g_io_channel_set_encoding(task->e_channel, NULL, &error)) != G_IO_STATUS_NORMAL) { helper->error(helper->browser, error->message, 1); g_error_free(error); } task->e_source = g_io_add_watch(task->e_channel, G_IO_IN, _cvs_task_on_io_can_read, task); _cvs_task_set_status(task, _("Running command...")); return 0; }
static int install_ldisc(GIOChannel *channel, gboolean install) { int uart_fd, err; struct speed_change_cmd cmd; GIOFlags flags; DBG("%d %p", install, uart_channel); if (install == FALSE) { g_atomic_int_set(&install_count, 0); if (uart_channel == NULL) { DBG("UART channel is NULL"); return 0; } g_io_channel_shutdown(uart_channel, TRUE, NULL); g_io_channel_unref(uart_channel); uart_channel = NULL; return 0; } if (uart_channel != NULL) { g_io_channel_shutdown(uart_channel, TRUE, NULL); g_io_channel_unref(uart_channel); uart_channel = NULL; } DBG("opening %s custom baud %lu", uart_dev_name, baud_rate); uart_fd = open(uart_dev_name, O_RDWR); if (uart_fd < 0) return -EIO; uart_channel = g_io_channel_unix_new(uart_fd); g_io_channel_set_close_on_unref(uart_channel, TRUE); g_io_channel_set_encoding(uart_channel, NULL, NULL); g_io_channel_set_buffered(uart_channel, FALSE); flags = g_io_channel_get_flags(uart_channel); flags |= G_IO_FLAG_NONBLOCK; g_io_channel_set_flags(uart_channel, flags, NULL); err = set_default_baud_rate(uart_fd); if (err < 0) { g_io_channel_shutdown(uart_channel, TRUE, NULL); g_io_channel_unref(uart_channel); uart_channel = NULL; return err; } if (baud_rate == 115200) { int ldisc; ldisc = N_TI_WL; if (ioctl(uart_fd, TIOCSETD, &ldisc) < 0) { g_io_channel_shutdown(uart_channel, TRUE, NULL); g_io_channel_unref(uart_channel); uart_channel = NULL; } g_atomic_int_set(&install_count, 0); return 0; } cmd.uart_prefix = HCI_COMMAND_PKT; cmd.opcode = HCI_HDR_OPCODE; cmd.plen = sizeof(unsigned long); cmd.speed = baud_rate; uart_watch = g_io_add_watch(uart_channel, G_IO_IN | G_IO_NVAL | G_IO_HUP | G_IO_ERR, uart_event, NULL); err = write(uart_fd, &cmd, sizeof(cmd)); if (err < 0) { connman_error("Write failed %d", err); g_io_channel_shutdown(uart_channel, TRUE, NULL); g_io_channel_unref(uart_channel); uart_channel = NULL; } return err; }
GPid storage_daemon_spawn_for_variant (StorageDaemon *daemon, const gchar **argv, const GVariantType *type, void (*callback) (GPid, GVariant *, GError *, gpointer), gpointer user_data) { GError *error = NULL; struct VariantReaderData *data; gchar *prog = NULL; GPid pid; gint output_fd; gchar *cmd; /* * This is so we can override the location of storaged-lvm-helper * during testing. */ if (!strchr (argv[0], '/')) { prog = storage_daemon_get_resource_path (daemon, TRUE, argv[0]); argv[0] = prog; } cmd = g_strjoinv (" ", (gchar **)argv); g_debug ("spawning for variant: %s", cmd); g_free (cmd); if (!g_spawn_async_with_pipes (NULL, (gchar **)argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, NULL, &output_fd, NULL, &error)) { callback (0, NULL, error, user_data); g_error_free (error); return 0; } data = g_new0 (struct VariantReaderData, 1); data->type = type; data->callback = callback; data->user_data = user_data; data->pid = pid; data->output = g_byte_array_new (); data->output_channel = g_io_channel_unix_new (output_fd); g_io_channel_set_encoding (data->output_channel, NULL, NULL); g_io_channel_set_flags (data->output_channel, G_IO_FLAG_NONBLOCK, NULL); data->output_watch = g_io_add_watch (data->output_channel, G_IO_IN, variant_reader_child_output, data); g_child_watch_add_full (G_PRIORITY_DEFAULT_IDLE, pid, variant_reader_watch_child, data, variant_reader_destroy); g_free (prog); return pid; }