Minor improvements related to the search entry
[geany-mirror.git] / src / socket.c
blob451cc926e5cc02f49a3be518177470b979a6525d
1 /*
2 * socket.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2006 The Geany contributors
5 * Copyright 2006 Hiroyuki Yamamoto (author of Sylpheed)
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 * Socket setup and messages handling.
24 * The socket allows detection and messages to be sent to the first running instance of Geany.
25 * Only the first instance loads session files at startup, and opens files from the command-line.
29 * Little dev doc:
30 * Each command which is sent between two instances (see send_open_command and
31 * socket_lock_input_cb) should have the following scheme:
32 * command name\n
33 * data\n
34 * data\n
35 * ...
36 * .\n
37 * The first thing should be the command name followed by the data belonging to the command and
38 * to mark the end of data send a single '.'. Each message should be ended with \n.
39 * The command window is only available on Windows and takes no additional data, instead it
40 * writes back a Windows handle (HWND) for the main window to set it to the foreground (focus).
42 * At the moment the commands window, doclist, open, openro, line and column are available.
44 * About the socket files on Unix-like systems:
45 * Geany creates a socket in /tmp (or any other directory returned by g_get_tmp_dir()) and
46 * a symlink in the current configuration to the created socket file. The symlink is named
47 * geany_socket_<hostname>_<displayname> (displayname is the name of the active X display).
48 * If the socket file cannot be created in the temporary directory, Geany creates the socket file
49 * directly in the configuration directory as a fallback.
53 #ifdef HAVE_CONFIG_H
54 # include "config.h"
55 #endif
57 #ifdef HAVE_SOCKET
59 #include "socket.h"
61 #include "app.h"
62 #include "dialogs.h"
63 #include "document.h"
64 #include "encodings.h"
65 #include "main.h"
66 #include "support.h"
67 #include "utils.h"
68 #include "win32.h"
70 #include <gtk/gtk.h>
73 #ifndef G_OS_WIN32
74 # include <sys/time.h>
75 # include <sys/types.h>
76 # include <sys/socket.h>
77 # include <sys/un.h>
78 # include <netinet/in.h>
79 # include <glib/gstdio.h>
80 #else
81 # include <winsock2.h>
82 # include <windows.h>
83 # include <gdk/gdkwin32.h>
84 # include <ws2tcpip.h>
85 #endif
86 #include <string.h>
87 #include <errno.h>
88 #include <stdlib.h>
89 #include <unistd.h>
90 #include <fcntl.h>
92 #ifdef GDK_WINDOWING_X11
93 #include <gdk/gdkx.h>
94 #endif
97 #ifdef G_OS_WIN32
98 #define SOCKET_IS_VALID(s) ((s) != INVALID_SOCKET)
99 #else
100 #define SOCKET_IS_VALID(s) ((s) >= 0)
101 #define INVALID_SOCKET (-1)
102 #endif
103 #define BUFFER_LENGTH 4096
105 struct SocketInfo socket_info;
108 #ifdef G_OS_WIN32
109 static gint socket_fd_connect_inet (gushort port);
110 static gint socket_fd_open_inet (gushort port);
111 static void socket_init_win32 (void);
112 #else
113 static gint socket_fd_connect_unix (const gchar *path);
114 static gint socket_fd_open_unix (const gchar *path);
115 #endif
117 static gint socket_fd_write (gint sock, const gchar *buf, gint len);
118 static gint socket_fd_write_all (gint sock, const gchar *buf, gint len);
119 static gint socket_fd_gets (gint sock, gchar *buf, gint len);
120 static gint socket_fd_check_io (gint fd, GIOCondition cond);
121 static gint socket_fd_read (gint sock, gchar *buf, gint len);
122 static gint socket_fd_recv (gint fd, gchar *buf, gint len, gint flags);
123 static gint socket_fd_close (gint sock);
127 static void send_open_command(gint sock, gint argc, gchar **argv)
129 gint i;
131 g_return_if_fail(argc > 1);
132 geany_debug("using running instance of Geany");
134 if (cl_options.goto_line >= 0)
136 gchar *line = g_strdup_printf("%d\n", cl_options.goto_line);
137 socket_fd_write_all(sock, "line\n", 5);
138 socket_fd_write_all(sock, line, strlen(line));
139 socket_fd_write_all(sock, ".\n", 2);
140 g_free(line);
143 if (cl_options.goto_column >= 0)
145 gchar *col = g_strdup_printf("%d\n", cl_options.goto_column);
146 socket_fd_write_all(sock, "column\n", 7);
147 socket_fd_write_all(sock, col, strlen(col));
148 socket_fd_write_all(sock, ".\n", 2);
149 g_free(col);
152 if (cl_options.readonly) /* append "ro" to denote readonly status for new docs */
153 socket_fd_write_all(sock, "openro\n", 7);
154 else
155 socket_fd_write_all(sock, "open\n", 5);
157 for (i = 1; i < argc && argv[i] != NULL; i++)
159 gchar *filename = main_get_argv_filename(argv[i]);
161 /* if the filename is valid or if a new file should be opened is check on the other side */
162 if (filename != NULL)
164 socket_fd_write_all(sock, filename, strlen(filename));
165 socket_fd_write_all(sock, "\n", 1);
167 else
169 g_printerr(_("Could not find file '%s'."), filename);
170 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
172 g_free(filename);
174 socket_fd_write_all(sock, ".\n", 2);
178 #ifndef G_OS_WIN32
179 static void remove_socket_link_full(void)
181 gchar real_path[512];
182 gsize len;
184 real_path[0] = '\0';
186 /* read the contents of the symbolic link socket_info.file_name and delete it
187 * readlink should return something like "/tmp/geany_socket.499602d2" */
188 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
189 if ((gint) len > 0)
191 real_path[len] = '\0';
192 g_unlink(real_path);
194 g_unlink(socket_info.file_name);
196 #endif
199 static void socket_get_document_list(gint sock)
201 gchar buf[BUFFER_LENGTH];
202 gint n_read;
204 if (sock < 0)
205 return;
207 socket_fd_write_all(sock, "doclist\n", 8);
211 n_read = socket_fd_read(sock, buf, BUFFER_LENGTH);
212 /* if we received ETX (end-of-text), there is nothing else to read, so cut that
213 * byte not to output it and to be sure not to validate the loop condition */
214 if (n_read > 0 && buf[n_read - 1] == '\3')
215 n_read--;
216 if (n_read > 0)
217 fwrite(buf, 1, n_read, stdout);
219 while (n_read >= BUFFER_LENGTH);
223 #ifndef G_OS_WIN32
224 static void check_socket_permissions(void)
226 GStatBuf socket_stat;
228 if (g_lstat(socket_info.file_name, &socket_stat) == 0)
229 { /* If the user id of the process is not the same as the owner of the socket
230 * file, then ignore this socket and start a new session. */
231 if (socket_stat.st_uid != getuid())
233 const gchar *msg = _(
234 /* TODO maybe this message needs a rewording */
235 "Geany tried to access the Unix Domain socket of another instance running as another user.\n"
236 "This is a fatal error and Geany will now quit.");
237 g_warning("%s", msg);
238 dialogs_show_msgbox(GTK_MESSAGE_ERROR, "%s", msg);
239 exit(1);
243 #endif
246 /* (Unix domain) socket support to replace the old FIFO code
247 * (taken from Sylpheed, thanks)
248 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
249 * were sent to it. */
250 gint socket_init(gint argc, gchar **argv, G_GNUC_UNUSED gushort socket_port)
252 gint sock;
253 #ifdef G_OS_WIN32
254 HANDLE hmutex;
255 HWND hwnd;
256 socket_init_win32();
257 hmutex = CreateMutexA(NULL, FALSE, "Geany");
258 if (! hmutex)
260 geany_debug("cannot create Mutex\n");
261 return -1;
263 if (GetLastError() != ERROR_ALREADY_EXISTS)
265 /* To support multiple instances with different configuration directories (as we do on
266 * non-Windows systems) we would need to use different port number s but it might be
267 * difficult to get a port number which is unique for a configuration directory (path)
268 * and which is unused. This port number has to be guessed by the first and new instance
269 * and the only data is the configuration directory path.
270 * For now we use one port number, that is we support only one instance at all. */
271 sock = socket_fd_open_inet(socket_port);
272 if (sock < 0)
273 return -1;
274 return sock;
277 sock = socket_fd_connect_inet(socket_port);
278 if (sock < 0)
279 return -1;
280 #else
281 gchar *display_name = NULL;
282 const gchar *hostname = g_get_host_name();
283 GdkDisplay *display = gdk_display_get_default();
284 gchar *p;
286 /* On OS X with quartz backend gdk_display_get_name() returns hostname
287 * using [NSHost currentHost] (it could return more or less whatever string
288 * as display name is a X11 specific thing). This call can lead to network
289 * query and block for several seconds so better skip it. */
290 #ifndef GDK_WINDOWING_QUARTZ
291 if (display != NULL)
292 display_name = g_strdup(gdk_display_get_name(display));
293 #endif
295 if (display_name == NULL)
296 display_name = g_strdup("NODISPLAY");
298 /* these lines are taken from dcopc.c in kdelibs */
299 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
300 *p = '\0';
301 /* remove characters that may not be acceptable in a filename */
302 for (p = display_name; *p; p++)
304 if (*p == ':' || *p == '/')
305 *p = '_';
308 if (socket_info.file_name == NULL)
309 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
310 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
312 g_free(display_name);
314 /* check whether the real user id is the same as this of the socket file */
315 check_socket_permissions();
317 sock = socket_fd_connect_unix(socket_info.file_name);
318 if (sock < 0)
320 remove_socket_link_full(); /* deletes the socket file and the symlink */
321 return socket_fd_open_unix(socket_info.file_name);
323 #endif
325 /* remote command mode, here we have another running instance and want to use it */
327 /* now we send the command line args */
328 if (argc > 1)
330 #ifdef G_OS_WIN32
331 /* first we send a request to retrieve the window handle and focus the window */
332 socket_fd_write_all(sock, "window\n", 7);
333 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
334 SetForegroundWindow(hwnd);
335 #endif
337 send_open_command(sock, argc, argv);
340 if (cl_options.list_documents)
342 socket_get_document_list(sock);
345 socket_fd_close(sock);
346 return -2;
350 gint socket_finalize(void)
352 if (socket_info.lock_socket < 0)
353 return -1;
355 if (socket_info.lock_socket_tag > 0)
356 g_source_remove(socket_info.lock_socket_tag);
357 if (socket_info.read_ioc)
359 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
360 g_io_channel_unref(socket_info.read_ioc);
361 socket_info.read_ioc = NULL;
364 #ifdef G_OS_WIN32
365 WSACleanup();
366 #else
367 if (socket_info.file_name != NULL)
369 remove_socket_link_full(); /* deletes the socket file and the symlink */
370 g_free(socket_info.file_name);
372 #endif
374 return 0;
378 static void log_error(const gchar *message_prefix, gint error_code)
380 #ifdef G_OS_WIN32
381 error_code = error_code == -1 ? WSAGetLastError(): error_code;
382 gchar *error_message = g_win32_error_message(error_code);
383 #else
384 error_code = error_code == -1 ? errno: error_code;
385 gchar *error_message = g_strdup(g_strerror(error_code));
386 #endif
387 g_warning("%s: %d: %s", message_prefix, error_code, error_message);
388 g_free(error_message);
392 #ifdef G_OS_UNIX
393 static gint socket_fd_connect_unix(const gchar *path)
395 gint sock;
396 struct sockaddr_un addr;
398 sock = socket(PF_UNIX, SOCK_STREAM, 0);
399 if (sock < 0)
401 log_error("Failed to create IPC socket", errno);
402 return -1;
405 memset(&addr, 0, sizeof(addr));
406 addr.sun_family = AF_UNIX;
407 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
409 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
411 socket_fd_close(sock);
412 return -1;
415 return sock;
419 static gint socket_fd_open_unix(const gchar *path)
421 gint sock;
422 struct sockaddr_un addr;
423 gint val, err;
424 gchar *real_dir;
425 gchar *real_path;
426 gchar *basename;
428 sock = socket(PF_UNIX, SOCK_STREAM, 0);
429 if (sock < 0)
431 log_error("Failed to create IPC socket", errno);
432 return -1;
435 val = 1;
436 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
438 log_error("Failed to set IPC socket option", errno);
439 socket_fd_close(sock);
440 return -1;
443 /* Try to place the socket in XDG_RUNTIME_DIR, according to XDG Base
444 * Directory Specification, see
445 * https://specifications.freedesktop.org/basedir-spec/latest.
446 * If that fails, we try to use /tmp as a fallback. The last resort
447 * is the configuration directory. But the other directories
448 * are preferred in case the configuration directory is located on
449 * a network file system or any other file system which doesn't
450 * support sockets (see #1888561). Append a random int to
451 * prevent clashes with other instances on the system. */
452 real_dir = g_build_filename(g_get_user_runtime_dir(), "geany", NULL);
453 err = utils_mkdir(real_dir, FALSE);
454 basename = g_strdup_printf("geany_socket.%08x", g_random_int());
455 if (err == 0 || err == EEXIST)
456 real_path = g_build_filename(real_dir, basename, NULL);
457 else
458 real_path = g_build_filename(g_get_tmp_dir(), basename, NULL);
459 g_free(basename);
460 g_free(real_dir);
462 if (utils_is_file_writable(real_path) != 0)
463 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
464 /* instead of creating a symlink and print a warning */
465 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
466 SETPTR(real_path, g_strdup(path));
468 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to
469 * /var/run/user/1000/geany/geany_socket.* */
470 else if (symlink(real_path, path) != 0)
472 gint saved_errno = errno;
473 gchar* message = g_strdup_printf(
474 "Failed to create IPC socket symlink %s -> %s)",
475 real_path,
476 path);
477 log_error(message, saved_errno);
478 g_free(message);
479 socket_fd_close(sock);
480 return -1;
483 memset(&addr, 0, sizeof(addr));
484 addr.sun_family = AF_UNIX;
485 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
487 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
489 gint saved_errno = errno;
490 gchar* message = g_strdup_printf("Failed to bind IPC socket (%s)", real_path);
491 log_error(message, saved_errno);
492 g_free(message);
493 socket_fd_close(sock);
494 return -1;
497 if (listen(sock, 1) < 0)
499 gint saved_errno = errno;
500 gchar* message = g_strdup_printf("Failed to listen on IPC socket (%s)", real_path);
501 log_error(message, saved_errno);
502 g_free(message);
503 socket_fd_close(sock);
504 return -1;
507 g_chmod(real_path, 0600);
509 g_free(real_path);
511 return sock;
513 #endif
515 static gint socket_fd_close(gint fd)
517 #ifdef G_OS_WIN32
518 return closesocket(fd);
519 #else
520 return close(fd);
521 #endif
525 #ifdef G_OS_WIN32
526 static gint socket_fd_open_inet(gushort port)
528 SOCKET sock;
529 struct sockaddr_in addr;
530 gchar val;
532 sock = socket(AF_INET, SOCK_STREAM, 0);
533 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
535 log_error("Failed to create IPC socket", -1);
536 return -1;
539 val = 1;
540 if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, &val, sizeof(val)) < 0)
542 log_error("Failed to set IPC socket exclusive option", -1);
543 socket_fd_close(sock);
544 return -1;
547 memset(&addr, 0, sizeof(addr));
548 addr.sin_family = AF_INET;
549 addr.sin_port = htons(port);
550 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
552 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
554 gint saved_errno = WSAGetLastError();
555 gchar* message = g_strdup_printf("Failed to bind IPC socket (127.0.0.1:%d)", port);
556 log_error(message, saved_errno);
557 g_free(message);
558 socket_fd_close(sock);
559 return -1;
562 if (listen(sock, 1) < 0)
564 gint saved_errno = WSAGetLastError();
565 gchar* message = g_strdup_printf("Failed to listen on IPC socket (127.0.0.1:%d)", port);
566 log_error(message, saved_errno);
567 g_free(message);
568 socket_fd_close(sock);
569 return -1;
572 return sock;
576 static gint socket_fd_connect_inet(gushort port)
578 SOCKET sock;
579 struct sockaddr_in addr;
581 sock = socket(AF_INET, SOCK_STREAM, 0);
582 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
584 log_error("Failed to create IPC socket", -1);
585 return -1;
588 memset(&addr, 0, sizeof(addr));
589 addr.sin_family = AF_INET;
590 addr.sin_port = htons(port);
591 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
593 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
595 gint saved_errno = WSAGetLastError();
596 gchar* message = g_strdup_printf("Failed to connect to IPC socket (127.0.0.1:%d)", port);
597 log_error(message, saved_errno);
598 g_free(message);
599 socket_fd_close(sock);
600 return -1;
603 return sock;
607 static void socket_init_win32(void)
609 WSADATA wsadata;
611 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
612 geany_debug("WSAStartup() failed\n");
614 return;
616 #endif
619 static void handle_input_filename(const gchar *buf)
621 gchar *utf8_filename, *locale_filename;
623 /* we never know how the input is encoded, so do the best auto detection we can */
624 if (! g_utf8_validate(buf, -1, NULL))
625 utf8_filename = encodings_convert_to_utf8(buf, -1, NULL);
626 else
627 utf8_filename = g_strdup(buf);
629 locale_filename = utils_get_locale_from_utf8(utf8_filename);
630 if (locale_filename)
632 if (g_str_has_suffix(locale_filename, ".geany"))
634 if (project_ask_close())
635 main_load_project_from_command_line(locale_filename, TRUE);
637 else
638 main_handle_filename(locale_filename);
640 g_free(utf8_filename);
641 g_free(locale_filename);
645 static gchar *build_document_list(void)
647 GString *doc_list = g_string_new(NULL);
648 guint i;
649 const gchar *filename;
651 foreach_document(i)
653 filename = DOC_FILENAME(documents[i]);
654 g_string_append(doc_list, filename);
655 g_string_append_c(doc_list, '\n');
657 return g_string_free(doc_list, FALSE);
661 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
663 gint fd, sock;
664 gchar buf[BUFFER_LENGTH];
665 gchar *command = NULL;
666 struct sockaddr_in caddr;
667 socklen_t caddr_len = sizeof(caddr);
668 GtkWidget *window = data;
669 gboolean popup = FALSE;
671 fd = g_io_channel_unix_get_fd(source);
672 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
674 /* first get the command */
675 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
677 command = g_strdup(buf);
678 geany_debug("Received IPC command from remote instance: %s", g_strstrip(command));
679 g_free(command);
680 if (strncmp(buf, "open", 4) == 0)
682 cl_options.readonly = strncmp(buf+4, "ro", 2) == 0; /* open in readonly? */
683 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
685 gsize buf_len = strlen(buf);
687 /* remove trailing newline */
688 if (buf_len > 0 && buf[buf_len - 1] == '\n')
689 buf[buf_len - 1] = '\0';
691 handle_input_filename(buf);
693 popup = TRUE;
695 else if (strncmp(buf, "doclist", 7) == 0)
697 gchar *doc_list = build_document_list();
698 if (!EMPTY(doc_list))
699 socket_fd_write_all(sock, doc_list, strlen(doc_list));
700 /* send ETX (end-of-text) so reader knows to stop reading */
701 socket_fd_write_all(sock, "\3", 1);
702 g_free(doc_list);
704 else if (strncmp(buf, "line", 4) == 0)
706 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
708 g_strstrip(buf); /* remove \n char */
709 /* on any error we get 0 which should be safe enough as fallback */
710 cl_options.goto_line = atoi(buf);
713 else if (strncmp(buf, "column", 6) == 0)
715 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
717 g_strstrip(buf); /* remove \n char */
718 /* on any error we get 0 which should be safe enough as fallback */
719 cl_options.goto_column = atoi(buf);
722 #ifdef G_OS_WIN32
723 else if (strncmp(buf, "window", 6) == 0)
725 HWND hwnd = (HWND) gdk_win32_window_get_handle(gtk_widget_get_window(window));
726 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
728 #endif
731 if (popup)
733 #ifdef GDK_WINDOWING_X11
734 GdkWindow *x11_window = gtk_widget_get_window(window);
736 /* Set the proper interaction time on the window. This seems necessary to make
737 * gtk_window_present() really bring the main window into the foreground on some
738 * window managers like Gnome's metacity.
739 * Code taken from Gedit. */
740 if (GDK_IS_X11_WINDOW(x11_window))
742 gdk_x11_window_set_user_time(x11_window, gdk_x11_get_server_time(x11_window));
744 #endif
745 gtk_window_present(GTK_WINDOW(window));
746 #ifdef G_OS_WIN32
747 gdk_window_show(gtk_widget_get_window(window));
748 #endif
751 socket_fd_close(sock);
753 return TRUE;
757 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
759 gchar *newline, *bp = buf;
760 gint n;
762 if (--len < 1)
763 return -1;
766 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
767 return -1;
768 if ((newline = memchr(bp, '\n', n)) != NULL)
769 n = newline - bp + 1;
770 if ((n = socket_fd_read(fd, bp, n)) < 0)
771 return -1;
772 bp += n;
773 len -= n;
774 } while (! newline && len);
776 *bp = '\0';
777 return bp - buf;
781 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
783 if (socket_fd_check_io(fd, G_IO_IN) < 0)
784 return -1;
786 return recv(fd, buf, len, flags);
790 static gint socket_fd_read(gint fd, gchar *buf, gint len)
792 if (socket_fd_check_io(fd, G_IO_IN) < 0)
793 return -1;
795 #ifdef G_OS_WIN32
796 return recv(fd, buf, len, 0);
797 #else
798 return read(fd, buf, len);
799 #endif
803 static gint socket_fd_check_io(gint fd, GIOCondition cond)
805 struct timeval timeout;
806 fd_set fds;
807 #ifdef G_OS_UNIX
808 gint flags;
809 #endif
811 timeout.tv_sec = 60;
812 timeout.tv_usec = 0;
814 #ifdef G_OS_UNIX
815 /* checking for non-blocking mode */
816 flags = fcntl(fd, F_GETFL, 0);
817 if (flags < 0)
819 log_error("fcntl() failed", errno);
820 return 0;
822 if ((flags & O_NONBLOCK) != 0)
823 return 0;
824 #endif
826 FD_ZERO(&fds);
827 #ifdef G_OS_WIN32
828 FD_SET((SOCKET)fd, &fds);
829 #else
830 FD_SET(fd, &fds);
831 #endif
833 if (cond == G_IO_IN)
835 select(fd + 1, &fds, NULL, NULL, &timeout);
837 else
839 select(fd + 1, NULL, &fds, NULL, &timeout);
842 if (FD_ISSET(fd, &fds))
844 return 0;
846 else
848 geany_debug("Socket IO timeout");
849 return -1;
854 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
856 gint n, wrlen = 0;
858 while (len)
860 n = socket_fd_write(fd, buf, len);
861 if (n <= 0)
862 return -1;
863 len -= n;
864 wrlen += n;
865 buf += n;
868 return wrlen;
872 gint socket_fd_write(gint fd, const gchar *buf, gint len)
874 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
875 return -1;
877 #ifdef G_OS_WIN32
878 return send(fd, buf, len, 0);
879 #else
880 return write(fd, buf, len);
881 #endif
885 #endif