Remove obsolete GTK compatibility code
[geany-mirror.git] / src / socket.c
blob4543eaa95ccc0d2db1cd8d00000c95db541ac519
1 /*
2 * socket.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2006-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
6 * Copyright 2006 Hiroyuki Yamamoto (author of Sylpheed)
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * Socket setup and messages handling.
25 * The socket allows detection and messages to be sent to the first running instance of Geany.
26 * Only the first instance loads session files at startup, and opens files from the command-line.
30 * Little dev doc:
31 * Each command which is sent between two instances (see send_open_command and
32 * socket_lock_input_cb) should have the following scheme:
33 * command name\n
34 * data\n
35 * data\n
36 * ...
37 * .\n
38 * The first thing should be the command name followed by the data belonging to the command and
39 * to mark the end of data send a single '.'. Each message should be ended with \n.
40 * The command window is only available on Windows and takes no additional data, instead it
41 * writes back a Windows handle (HWND) for the main window to set it to the foreground (focus).
43 * At the moment the commands window, doclist, open, openro, line and column are available.
45 * About the socket files on Unix-like systems:
46 * Geany creates a socket in /tmp (or any other directory returned by g_get_tmp_dir()) and
47 * a symlink in the current configuration to the created socket file. The symlink is named
48 * geany_socket_<hostname>_<displayname> (displayname is the name of the active X display).
49 * If the socket file cannot be created in the temporary directory, Geany creates the socket file
50 * directly in the configuration directory as a fallback.
54 #ifdef HAVE_CONFIG_H
55 # include "config.h"
56 #endif
58 #ifdef HAVE_SOCKET
60 #include "win32defines.h" /* should always come before any system headers */
62 #include "socket.h"
64 #include "app.h"
65 #include "dialogs.h"
66 #include "document.h"
67 #include "encodings.h"
68 #include "main.h"
69 #include "support.h"
70 #include "utils.h"
71 #include "win32.h"
73 #include "gtkcompat.h"
76 #ifndef G_OS_WIN32
77 # include <sys/time.h>
78 # include <sys/types.h>
79 # include <sys/socket.h>
80 # include <sys/un.h>
81 # include <netinet/in.h>
82 # include <glib/gstdio.h>
83 #else
84 # include <winsock2.h>
85 # include <windows.h>
86 # include <gdk/gdkwin32.h>
87 # include <ws2tcpip.h>
88 #endif
89 #include <string.h>
90 #include <stdlib.h>
91 #include <unistd.h>
92 #include <fcntl.h>
94 #ifdef GDK_WINDOWING_X11
95 #include <gdk/gdkx.h>
96 #endif
99 #ifdef G_OS_WIN32
100 #define REMOTE_CMD_PORT 49876
101 #define SOCKET_IS_VALID(s) ((s) != INVALID_SOCKET)
102 #else
103 #define SOCKET_IS_VALID(s) ((s) >= 0)
104 #define INVALID_SOCKET (-1)
105 #endif
106 #define BUFFER_LENGTH 4096
108 struct socket_info_struct socket_info;
111 #ifdef G_OS_WIN32
112 static gint socket_fd_connect_inet (gushort port);
113 static gint socket_fd_open_inet (gushort port);
114 static void socket_init_win32 (void);
115 #else
116 static gint socket_fd_connect_unix (const gchar *path);
117 static gint socket_fd_open_unix (const gchar *path);
118 #endif
120 static gint socket_fd_write (gint sock, const gchar *buf, gint len);
121 static gint socket_fd_write_all (gint sock, const gchar *buf, gint len);
122 static gint socket_fd_gets (gint sock, gchar *buf, gint len);
123 static gint socket_fd_check_io (gint fd, GIOCondition cond);
124 static gint socket_fd_read (gint sock, gchar *buf, gint len);
125 static gint socket_fd_recv (gint fd, gchar *buf, gint len, gint flags);
126 static gint socket_fd_close (gint sock);
130 static void send_open_command(gint sock, gint argc, gchar **argv)
132 gint i;
133 gchar *filename;
135 g_return_if_fail(argc > 1);
136 geany_debug("using running instance of Geany");
138 if (cl_options.goto_line >= 0)
140 gchar *line = g_strdup_printf("%d\n", cl_options.goto_line);
141 socket_fd_write_all(sock, "line\n", 5);
142 socket_fd_write_all(sock, line, strlen(line));
143 socket_fd_write_all(sock, ".\n", 2);
144 g_free(line);
147 if (cl_options.goto_column >= 0)
149 gchar *col = g_strdup_printf("%d\n", cl_options.goto_column);
150 socket_fd_write_all(sock, "column\n", 7);
151 socket_fd_write_all(sock, col, strlen(col));
152 socket_fd_write_all(sock, ".\n", 2);
153 g_free(col);
156 if (cl_options.readonly) /* append "ro" to denote readonly status for new docs */
157 socket_fd_write_all(sock, "openro\n", 7);
158 else
159 socket_fd_write_all(sock, "open\n", 5);
161 for (i = 1; i < argc && argv[i] != NULL; i++)
163 filename = main_get_argv_filename(argv[i]);
165 /* if the filename is valid or if a new file should be opened is check on the other side */
166 if (filename != NULL)
168 socket_fd_write_all(sock, filename, strlen(filename));
169 socket_fd_write_all(sock, "\n", 1);
171 else
173 g_printerr(_("Could not find file '%s'."), filename);
174 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
176 g_free(filename);
178 socket_fd_write_all(sock, ".\n", 2);
182 #ifndef G_OS_WIN32
183 static void remove_socket_link_full(void)
185 gchar real_path[512];
186 gsize len;
188 real_path[0] = '\0';
190 /* read the contents of the symbolic link socket_info.file_name and delete it
191 * readlink should return something like "/tmp/geany_socket.499602d2" */
192 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
193 if ((gint) len > 0)
195 real_path[len] = '\0';
196 g_unlink(real_path);
198 g_unlink(socket_info.file_name);
200 #endif
203 static void socket_get_document_list(gint sock)
205 gchar buf[BUFFER_LENGTH];
206 gint n_read;
208 if (sock < 0)
209 return;
211 socket_fd_write_all(sock, "doclist\n", 8);
215 n_read = socket_fd_read(sock, buf, BUFFER_LENGTH);
216 /* if we received ETX (end-of-text), there is nothing else to read, so cut that
217 * byte not to output it and to be sure not to validate the loop condition */
218 if (n_read > 0 && buf[n_read - 1] == '\3')
219 n_read--;
220 if (n_read > 0)
221 fwrite(buf, 1, n_read, stdout);
223 while (n_read >= BUFFER_LENGTH);
227 #ifndef G_OS_WIN32
228 static void check_socket_permissions(void)
230 struct stat socket_stat;
232 if (g_lstat(socket_info.file_name, &socket_stat) == 0)
233 { /* If the user id of the process is not the same as the owner of the socket
234 * file, then ignore this socket and start a new session. */
235 if (socket_stat.st_uid != getuid())
237 const gchar *msg = _(
238 /* TODO maybe this message needs a rewording */
239 "Geany tried to access the Unix Domain socket of another instance running as another user.\n"
240 "This is a fatal error and Geany will now quit.");
241 g_warning("%s", msg);
242 dialogs_show_msgbox(GTK_MESSAGE_ERROR, "%s", msg);
243 exit(1);
247 #endif
250 /* (Unix domain) socket support to replace the old FIFO code
251 * (taken from Sylpheed, thanks)
252 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
253 * were sent to it. */
254 gint socket_init(gint argc, gchar **argv)
256 gint sock;
257 #ifdef G_OS_WIN32
258 HANDLE hmutex;
259 HWND hwnd;
260 socket_init_win32();
261 hmutex = CreateMutexA(NULL, FALSE, "Geany");
262 if (! hmutex)
264 geany_debug("cannot create Mutex\n");
265 return -1;
267 if (GetLastError() != ERROR_ALREADY_EXISTS)
269 /* To support multiple instances with different configuration directories (as we do on
270 * non-Windows systems) we would need to use different port number s but it might be
271 * difficult to get a port number which is unique for a configuration directory (path)
272 * and which is unused. This port number has to be guessed by the first and new instance
273 * and the only data is the configuration directory path.
274 * For now we use one port number, that is we support only one instance at all. */
275 sock = socket_fd_open_inet(REMOTE_CMD_PORT);
276 if (sock < 0)
277 return 0;
278 return sock;
281 sock = socket_fd_connect_inet(REMOTE_CMD_PORT);
282 if (sock < 0)
283 return -1;
284 #else
285 gchar *display_name = NULL;
286 const gchar *hostname = g_get_host_name();
287 GdkDisplay *display = gdk_display_get_default();
288 gchar *p;
290 if (display != NULL)
291 display_name = g_strdup(gdk_display_get_name(display));
292 if (display_name == NULL)
293 display_name = g_strdup("NODISPLAY");
295 /* these lines are taken from dcopc.c in kdelibs */
296 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
297 *p = '\0';
298 /* remove characters that may not be acceptable in a filename */
299 for (p = display_name; *p; p++)
301 if (*p == ':' || *p == '/')
302 *p = '_';
305 if (socket_info.file_name == NULL)
306 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
307 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
309 g_free(display_name);
311 /* check whether the real user id is the same as this of the socket file */
312 check_socket_permissions();
314 sock = socket_fd_connect_unix(socket_info.file_name);
315 if (sock < 0)
317 remove_socket_link_full(); /* deletes the socket file and the symlink */
318 return socket_fd_open_unix(socket_info.file_name);
320 #endif
322 /* remote command mode, here we have another running instance and want to use it */
324 #ifdef G_OS_WIN32
325 /* first we send a request to retrieve the window handle and focus the window */
326 socket_fd_write_all(sock, "window\n", 7);
327 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
328 SetForegroundWindow(hwnd);
329 #endif
330 /* now we send the command line args */
331 if (argc > 1)
333 send_open_command(sock, argc, argv);
336 if (cl_options.list_documents)
338 socket_get_document_list(sock);
341 socket_fd_close(sock);
342 return -2;
346 gint socket_finalize(void)
348 if (socket_info.lock_socket < 0)
349 return -1;
351 if (socket_info.lock_socket_tag > 0)
352 g_source_remove(socket_info.lock_socket_tag);
353 if (socket_info.read_ioc)
355 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
356 g_io_channel_unref(socket_info.read_ioc);
357 socket_info.read_ioc = NULL;
360 #ifdef G_OS_WIN32
361 WSACleanup();
362 #else
363 if (socket_info.file_name != NULL)
365 remove_socket_link_full(); /* deletes the socket file and the symlink */
366 g_free(socket_info.file_name);
368 #endif
370 return 0;
374 #ifdef G_OS_UNIX
375 static gint socket_fd_connect_unix(const gchar *path)
377 gint sock;
378 struct sockaddr_un addr;
380 sock = socket(PF_UNIX, SOCK_STREAM, 0);
381 if (sock < 0)
383 perror("fd_connect_unix(): socket");
384 return -1;
387 memset(&addr, 0, sizeof(addr));
388 addr.sun_family = AF_UNIX;
389 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
391 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
393 socket_fd_close(sock);
394 return -1;
397 return sock;
401 static gint socket_fd_open_unix(const gchar *path)
403 gint sock;
404 struct sockaddr_un addr;
405 gint val;
406 gchar *real_path;
408 sock = socket(PF_UNIX, SOCK_STREAM, 0);
410 if (sock < 0)
412 perror("sock_open_unix(): socket");
413 return -1;
416 val = 1;
417 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
419 perror("setsockopt");
420 socket_fd_close(sock);
421 return -1;
424 /* fix for #1888561:
425 * in case the configuration directory is located on a network file system or any other
426 * file system which doesn't support sockets, we just link the socket there and create the
427 * real socket in the system's tmp directory assuming it supports sockets */
428 real_path = g_strdup_printf("%s%cgeany_socket.%08x",
429 g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());
431 if (utils_is_file_writable(real_path) != 0)
432 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
433 /* instead of creating a symlink and print a warning */
434 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
435 SETPTR(real_path, g_strdup(path));
437 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
438 else if (symlink(real_path, path) != 0)
440 perror("symlink");
441 socket_fd_close(sock);
442 return -1;
445 memset(&addr, 0, sizeof(addr));
446 addr.sun_family = AF_UNIX;
447 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
449 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
451 perror("bind");
452 socket_fd_close(sock);
453 return -1;
456 if (listen(sock, 1) < 0)
458 perror("listen");
459 socket_fd_close(sock);
460 return -1;
463 g_chmod(real_path, 0600);
465 g_free(real_path);
467 return sock;
469 #endif
471 static gint socket_fd_close(gint fd)
473 #ifdef G_OS_WIN32
474 return closesocket(fd);
475 #else
476 return close(fd);
477 #endif
481 #ifdef G_OS_WIN32
482 static gint socket_fd_open_inet(gushort port)
484 SOCKET sock;
485 struct sockaddr_in addr;
486 gchar val;
488 sock = socket(AF_INET, SOCK_STREAM, 0);
489 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
491 geany_debug("fd_open_inet(): socket() failed: %d\n", WSAGetLastError());
492 return -1;
495 val = 1;
496 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
498 perror("setsockopt");
499 socket_fd_close(sock);
500 return -1;
503 memset(&addr, 0, sizeof(addr));
504 addr.sin_family = AF_INET;
505 addr.sin_port = htons(port);
506 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
508 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
510 perror("bind");
511 socket_fd_close(sock);
512 return -1;
515 if (listen(sock, 1) < 0)
517 perror("listen");
518 socket_fd_close(sock);
519 return -1;
522 return sock;
526 static gint socket_fd_connect_inet(gushort port)
528 SOCKET sock;
529 struct sockaddr_in addr;
531 sock = socket(AF_INET, SOCK_STREAM, 0);
532 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
534 geany_debug("fd_connect_inet(): socket() failed: %d\n", WSAGetLastError());
535 return -1;
538 memset(&addr, 0, sizeof(addr));
539 addr.sin_family = AF_INET;
540 addr.sin_port = htons(port);
541 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
543 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
545 socket_fd_close(sock);
546 return -1;
549 return sock;
553 static void socket_init_win32(void)
555 WSADATA wsadata;
557 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
558 geany_debug("WSAStartup() failed\n");
560 return;
562 #endif
565 static void handle_input_filename(const gchar *buf)
567 gchar *utf8_filename, *locale_filename;
569 /* we never know how the input is encoded, so do the best auto detection we can */
570 if (! g_utf8_validate(buf, -1, NULL))
571 utf8_filename = encodings_convert_to_utf8(buf, -1, NULL);
572 else
573 utf8_filename = g_strdup(buf);
575 locale_filename = utils_get_locale_from_utf8(utf8_filename);
576 if (locale_filename)
578 if (g_str_has_suffix(locale_filename, ".geany"))
580 if (project_ask_close())
581 main_load_project_from_command_line(locale_filename, TRUE);
583 else
584 main_handle_filename(locale_filename);
586 g_free(utf8_filename);
587 g_free(locale_filename);
591 static gchar *build_document_list(void)
593 GString *doc_list = g_string_new(NULL);
594 guint i;
595 const gchar *filename;
597 foreach_document(i)
599 filename = DOC_FILENAME(documents[i]);
600 g_string_append(doc_list, filename);
601 g_string_append_c(doc_list, '\n');
603 return g_string_free(doc_list, FALSE);
607 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
609 gint fd, sock;
610 gchar buf[BUFFER_LENGTH];
611 struct sockaddr_in caddr;
612 socklen_t caddr_len = sizeof(caddr);
613 GtkWidget *window = data;
614 gboolean popup = FALSE;
616 fd = g_io_channel_unix_get_fd(source);
617 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
619 /* first get the command */
620 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
622 if (strncmp(buf, "open", 4) == 0)
624 cl_options.readonly = strncmp(buf+4, "ro", 2) == 0; /* open in readonly? */
625 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
627 gsize buf_len = strlen(buf);
629 /* remove trailing newline */
630 if (buf_len > 0 && buf[buf_len - 1] == '\n')
631 buf[buf_len - 1] = '\0';
633 handle_input_filename(buf);
635 popup = TRUE;
637 else if (strncmp(buf, "doclist", 7) == 0)
639 gchar *doc_list = build_document_list();
640 if (!EMPTY(doc_list))
641 socket_fd_write_all(sock, doc_list, strlen(doc_list));
642 /* send ETX (end-of-text) so reader knows to stop reading */
643 socket_fd_write_all(sock, "\3", 1);
644 g_free(doc_list);
646 else if (strncmp(buf, "line", 4) == 0)
648 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
650 g_strstrip(buf); /* remove \n char */
651 /* on any error we get 0 which should be safe enough as fallback */
652 cl_options.goto_line = atoi(buf);
655 else if (strncmp(buf, "column", 6) == 0)
657 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
659 g_strstrip(buf); /* remove \n char */
660 /* on any error we get 0 which should be safe enough as fallback */
661 cl_options.goto_column = atoi(buf);
664 #ifdef G_OS_WIN32
665 else if (strncmp(buf, "window", 6) == 0)
667 # if GTK_CHECK_VERSION(3, 0, 0)
668 HWND hwnd = (HWND) gdk_win32_window_get_handle(gtk_widget_get_window(window));
669 # else
670 HWND hwnd = (HWND) gdk_win32_drawable_get_handle(
671 GDK_DRAWABLE(gtk_widget_get_window(window)));
672 # endif
673 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
675 #endif
678 if (popup)
680 #ifdef GDK_WINDOWING_X11
681 GdkWindow *x11_window = gtk_widget_get_window(window);
683 /* Set the proper interaction time on the window. This seems necessary to make
684 * gtk_window_present() really bring the main window into the foreground on some
685 * window managers like Gnome's metacity.
686 * Code taken from Gedit. */
687 # if GTK_CHECK_VERSION(3, 0, 0)
688 if (GDK_IS_X11_WINDOW(x11_window))
689 # endif
691 gdk_x11_window_set_user_time(x11_window, gdk_x11_get_server_time(x11_window));
693 #endif
694 gtk_window_present(GTK_WINDOW(window));
695 #ifdef G_OS_WIN32
696 gdk_window_show(gtk_widget_get_window(window));
697 #endif
700 socket_fd_close(sock);
702 return TRUE;
706 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
708 gchar *newline, *bp = buf;
709 gint n;
711 if (--len < 1)
712 return -1;
715 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
716 return -1;
717 if ((newline = memchr(bp, '\n', n)) != NULL)
718 n = newline - bp + 1;
719 if ((n = socket_fd_read(fd, bp, n)) < 0)
720 return -1;
721 bp += n;
722 len -= n;
723 } while (! newline && len);
725 *bp = '\0';
726 return bp - buf;
730 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
732 if (socket_fd_check_io(fd, G_IO_IN) < 0)
733 return -1;
735 return recv(fd, buf, len, flags);
739 static gint socket_fd_read(gint fd, gchar *buf, gint len)
741 if (socket_fd_check_io(fd, G_IO_IN) < 0)
742 return -1;
744 #ifdef G_OS_WIN32
745 return recv(fd, buf, len, 0);
746 #else
747 return read(fd, buf, len);
748 #endif
752 static gint socket_fd_check_io(gint fd, GIOCondition cond)
754 struct timeval timeout;
755 fd_set fds;
756 #ifdef G_OS_UNIX
757 gint flags;
758 #endif
760 timeout.tv_sec = 60;
761 timeout.tv_usec = 0;
763 #ifdef G_OS_UNIX
764 /* checking for non-blocking mode */
765 flags = fcntl(fd, F_GETFL, 0);
766 if (flags < 0)
768 perror("fcntl");
769 return 0;
771 if ((flags & O_NONBLOCK) != 0)
772 return 0;
773 #endif
775 FD_ZERO(&fds);
776 #ifdef G_OS_WIN32
777 FD_SET((SOCKET)fd, &fds);
778 #else
779 FD_SET(fd, &fds);
780 #endif
782 if (cond == G_IO_IN)
784 select(fd + 1, &fds, NULL, NULL, &timeout);
786 else
788 select(fd + 1, NULL, &fds, NULL, &timeout);
791 if (FD_ISSET(fd, &fds))
793 return 0;
795 else
797 geany_debug("Socket IO timeout");
798 return -1;
803 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
805 gint n, wrlen = 0;
807 while (len)
809 n = socket_fd_write(fd, buf, len);
810 if (n <= 0)
811 return -1;
812 len -= n;
813 wrlen += n;
814 buf += n;
817 return wrlen;
821 gint socket_fd_write(gint fd, const gchar *buf, gint len)
823 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
824 return -1;
826 #ifdef G_OS_WIN32
827 return send(fd, buf, len, 0);
828 #else
829 return write(fd, buf, len);
830 #endif
834 #endif