Don't use deprecated gdk_get_display()
[geany-mirror.git] / src / socket.c
blob47e51e1d69cac79f8927ed182cf1c3b74e300268
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.
55 #include "geany.h"
57 #ifdef HAVE_SOCKET
59 #ifndef G_OS_WIN32
60 # include <sys/time.h>
61 # include <sys/types.h>
62 # include <sys/socket.h>
63 # include <sys/un.h>
64 # include <netinet/in.h>
65 # include <glib/gstdio.h>
66 #else
67 # include <winsock2.h>
68 # include <windows.h>
69 # include <gdk/gdkwin32.h>
70 # include <ws2tcpip.h>
71 #endif
72 #include <string.h>
73 #include <stdlib.h>
74 #include <unistd.h>
75 #include <fcntl.h>
77 #ifdef GDK_WINDOWING_X11
78 #include <gdk/gdkx.h>
79 #endif
81 #include "main.h"
82 #include "socket.h"
83 #include "document.h"
84 #include "support.h"
85 #include "ui_utils.h"
86 #include "utils.h"
87 #include "dialogs.h"
88 #include "encodings.h"
89 #include "project.h"
92 #ifdef G_OS_WIN32
93 #define REMOTE_CMD_PORT 49876
94 #define SOCKET_IS_VALID(s) ((s) != INVALID_SOCKET)
95 #else
96 #define SOCKET_IS_VALID(s) ((s) >= 0)
97 #define INVALID_SOCKET (-1)
98 #endif
99 #define BUFFER_LENGTH 4096
101 struct socket_info_struct socket_info;
104 #ifdef G_OS_WIN32
105 static gint socket_fd_connect_inet (gushort port);
106 static gint socket_fd_open_inet (gushort port);
107 static void socket_init_win32 (void);
108 #else
109 static gint socket_fd_connect_unix (const gchar *path);
110 static gint socket_fd_open_unix (const gchar *path);
111 #endif
113 static gint socket_fd_write (gint sock, const gchar *buf, gint len);
114 static gint socket_fd_write_all (gint sock, const gchar *buf, gint len);
115 static gint socket_fd_gets (gint sock, gchar *buf, gint len);
116 static gint socket_fd_check_io (gint fd, GIOCondition cond);
117 static gint socket_fd_read (gint sock, gchar *buf, gint len);
118 static gint socket_fd_recv (gint fd, gchar *buf, gint len, gint flags);
119 static gint socket_fd_close (gint sock);
123 static void send_open_command(gint sock, gint argc, gchar **argv)
125 gint i;
126 gchar *filename;
128 g_return_if_fail(argc > 1);
129 geany_debug("using running instance of Geany");
131 if (cl_options.goto_line >= 0)
133 gchar *line = g_strdup_printf("%d\n", cl_options.goto_line);
134 socket_fd_write_all(sock, "line\n", 5);
135 socket_fd_write_all(sock, line, strlen(line));
136 socket_fd_write_all(sock, ".\n", 2);
137 g_free(line);
140 if (cl_options.goto_column >= 0)
142 gchar *col = g_strdup_printf("%d\n", cl_options.goto_column);
143 socket_fd_write_all(sock, "column\n", 7);
144 socket_fd_write_all(sock, col, strlen(col));
145 socket_fd_write_all(sock, ".\n", 2);
146 g_free(col);
149 if (cl_options.readonly) /* append "ro" to denote readonly status for new docs */
150 socket_fd_write_all(sock, "openro\n", 7);
151 else
152 socket_fd_write_all(sock, "open\n", 5);
154 for (i = 1; i < argc && argv[i] != NULL; i++)
156 filename = main_get_argv_filename(argv[i]);
158 /* if the filename is valid or if a new file should be opened is check on the other side */
159 if (filename != NULL)
161 socket_fd_write_all(sock, filename, strlen(filename));
162 socket_fd_write_all(sock, "\n", 1);
164 else
166 g_printerr(_("Could not find file '%s'."), filename);
167 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
169 g_free(filename);
171 socket_fd_write_all(sock, ".\n", 2);
175 #ifndef G_OS_WIN32
176 static void remove_socket_link_full(void)
178 gchar real_path[512];
179 gsize len;
181 real_path[0] = '\0';
183 /* read the contents of the symbolic link socket_info.file_name and delete it
184 * readlink should return something like "/tmp/geany_socket.499602d2" */
185 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
186 if ((gint) len > 0)
188 real_path[len] = '\0';
189 g_unlink(real_path);
191 g_unlink(socket_info.file_name);
193 #endif
196 static void socket_get_document_list(gint sock)
198 gchar buf[BUFFER_LENGTH];
199 gint n_read;
201 if (sock < 0)
202 return;
204 socket_fd_write_all(sock, "doclist\n", 8);
208 n_read = socket_fd_read(sock, buf, sizeof(buf));
209 /* if we received ETX (end-of-text), there is nothing else to read, so cut that
210 * byte not to output it and to be sure not to validate the loop condition */
211 if (n_read > 0 && buf[n_read - 1] == '\3')
212 n_read--;
213 if (n_read > 0)
214 fwrite(buf, 1, n_read, stdout);
216 while (n_read >= sizeof(buf));
220 #ifndef G_OS_WIN32
221 static void check_socket_permissions(void)
223 struct stat socket_stat;
225 if (g_lstat(socket_info.file_name, &socket_stat) == 0)
226 { /* If the user id of the process is not the same as the owner of the socket
227 * file, then ignore this socket and start a new session. */
228 if (socket_stat.st_uid != getuid())
230 const gchar *msg = _(
231 /* TODO maybe this message needs a rewording */
232 "Geany tried to access the Unix Domain socket of another instance running as another user.\n"
233 "This is a fatal error and Geany will now quit.");
234 g_warning("%s", msg);
235 dialogs_show_msgbox(GTK_MESSAGE_ERROR, "%s", msg);
236 exit(1);
240 #endif
243 /* (Unix domain) socket support to replace the old FIFO code
244 * (taken from Sylpheed, thanks)
245 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
246 * were sent to it. */
247 gint socket_init(gint argc, gchar **argv)
249 gint sock;
250 #ifdef G_OS_WIN32
251 HANDLE hmutex;
252 HWND hwnd;
253 socket_init_win32();
254 hmutex = CreateMutexA(NULL, FALSE, "Geany");
255 if (! hmutex)
257 geany_debug("cannot create Mutex\n");
258 return -1;
260 if (GetLastError() != ERROR_ALREADY_EXISTS)
262 /* To support multiple instances with different configuration directories (as we do on
263 * non-Windows systems) we would need to use different port number s but it might be
264 * difficult to get a port number which is unique for a configuration directory (path)
265 * and which is unused. This port number has to be guessed by the first and new instance
266 * and the only data is the configuration directory path.
267 * For now we use one port number, that is we support only one instance at all. */
268 sock = socket_fd_open_inet(REMOTE_CMD_PORT);
269 if (sock < 0)
270 return 0;
271 return sock;
274 sock = socket_fd_connect_inet(REMOTE_CMD_PORT);
275 if (sock < 0)
276 return -1;
277 #else
278 gchar *display_name = NULL;
279 const gchar *hostname = g_get_host_name();
280 GdkDisplay *display = gdk_display_get_default();
281 gchar *p;
283 if (display != NULL)
284 display_name = g_strdup(gdk_display_get_name(display));
285 if (display_name == NULL)
286 display_name = g_strdup("NODISPLAY");
288 /* these lines are taken from dcopc.c in kdelibs */
289 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
290 *p = '\0';
291 /* remove characters that may not be acceptable in a filename */
292 for (p = display_name; *p; p++)
294 if (*p == ':' || *p == '/')
295 *p = '_';
298 if (socket_info.file_name == NULL)
299 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
300 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
302 g_free(display_name);
304 /* check whether the real user id is the same as this of the socket file */
305 check_socket_permissions();
307 sock = socket_fd_connect_unix(socket_info.file_name);
308 if (sock < 0)
310 remove_socket_link_full(); /* deletes the socket file and the symlink */
311 return socket_fd_open_unix(socket_info.file_name);
313 #endif
315 /* remote command mode, here we have another running instance and want to use it */
317 #ifdef G_OS_WIN32
318 /* first we send a request to retrieve the window handle and focus the window */
319 socket_fd_write_all(sock, "window\n", 7);
320 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
321 SetForegroundWindow(hwnd);
322 #endif
323 /* now we send the command line args */
324 if (argc > 1)
326 send_open_command(sock, argc, argv);
329 if (cl_options.list_documents)
331 socket_get_document_list(sock);
334 socket_fd_close(sock);
335 return -2;
339 gint socket_finalize(void)
341 if (socket_info.lock_socket < 0)
342 return -1;
344 if (socket_info.lock_socket_tag > 0)
345 g_source_remove(socket_info.lock_socket_tag);
346 if (socket_info.read_ioc)
348 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
349 g_io_channel_unref(socket_info.read_ioc);
350 socket_info.read_ioc = NULL;
353 #ifdef G_OS_WIN32
354 WSACleanup();
355 #else
356 if (socket_info.file_name != NULL)
358 remove_socket_link_full(); /* deletes the socket file and the symlink */
359 g_free(socket_info.file_name);
361 #endif
363 return 0;
367 #ifdef G_OS_UNIX
368 static gint socket_fd_connect_unix(const gchar *path)
370 gint sock;
371 struct sockaddr_un addr;
373 sock = socket(PF_UNIX, SOCK_STREAM, 0);
374 if (sock < 0)
376 perror("fd_connect_unix(): socket");
377 return -1;
380 memset(&addr, 0, sizeof(addr));
381 addr.sun_family = AF_UNIX;
382 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
384 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
386 socket_fd_close(sock);
387 return -1;
390 return sock;
394 static gint socket_fd_open_unix(const gchar *path)
396 gint sock;
397 struct sockaddr_un addr;
398 gint val;
399 gchar *real_path;
401 sock = socket(PF_UNIX, SOCK_STREAM, 0);
403 if (sock < 0)
405 perror("sock_open_unix(): socket");
406 return -1;
409 val = 1;
410 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
412 perror("setsockopt");
413 socket_fd_close(sock);
414 return -1;
417 /* fix for #1888561:
418 * in case the configuration directory is located on a network file system or any other
419 * file system which doesn't support sockets, we just link the socket there and create the
420 * real socket in the system's tmp directory assuming it supports sockets */
421 real_path = g_strdup_printf("%s%cgeany_socket.%08x",
422 g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());
424 if (utils_is_file_writable(real_path) != 0)
425 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
426 /* instead of creating a symlink and print a warning */
427 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
428 SETPTR(real_path, g_strdup(path));
430 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
431 else if (symlink(real_path, path) != 0)
433 perror("symlink");
434 socket_fd_close(sock);
435 return -1;
438 memset(&addr, 0, sizeof(addr));
439 addr.sun_family = AF_UNIX;
440 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
442 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
444 perror("bind");
445 socket_fd_close(sock);
446 return -1;
449 if (listen(sock, 1) < 0)
451 perror("listen");
452 socket_fd_close(sock);
453 return -1;
456 g_chmod(real_path, 0600);
458 g_free(real_path);
460 return sock;
462 #endif
464 static gint socket_fd_close(gint fd)
466 #ifdef G_OS_WIN32
467 return closesocket(fd);
468 #else
469 return close(fd);
470 #endif
474 #ifdef G_OS_WIN32
475 static gint socket_fd_open_inet(gushort port)
477 SOCKET sock;
478 struct sockaddr_in addr;
479 gchar val;
481 sock = socket(AF_INET, SOCK_STREAM, 0);
482 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
484 geany_debug("fd_open_inet(): socket() failed: %d\n", WSAGetLastError());
485 return -1;
488 val = 1;
489 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
491 perror("setsockopt");
492 socket_fd_close(sock);
493 return -1;
496 memset(&addr, 0, sizeof(addr));
497 addr.sin_family = AF_INET;
498 addr.sin_port = htons(port);
499 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
501 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
503 perror("bind");
504 socket_fd_close(sock);
505 return -1;
508 if (listen(sock, 1) < 0)
510 perror("listen");
511 socket_fd_close(sock);
512 return -1;
515 return sock;
519 static gint socket_fd_connect_inet(gushort port)
521 SOCKET sock;
522 struct sockaddr_in addr;
524 sock = socket(AF_INET, SOCK_STREAM, 0);
525 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
527 geany_debug("fd_connect_inet(): socket() failed: %d\n", WSAGetLastError());
528 return -1;
531 memset(&addr, 0, sizeof(addr));
532 addr.sin_family = AF_INET;
533 addr.sin_port = htons(port);
534 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
536 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
538 socket_fd_close(sock);
539 return -1;
542 return sock;
546 static void socket_init_win32(void)
548 WSADATA wsadata;
550 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
551 geany_debug("WSAStartup() failed\n");
553 return;
555 #endif
558 static void handle_input_filename(const gchar *buf)
560 gchar *utf8_filename, *locale_filename;
562 /* we never know how the input is encoded, so do the best auto detection we can */
563 if (! g_utf8_validate(buf, -1, NULL))
564 utf8_filename = encodings_convert_to_utf8(buf, -1, NULL);
565 else
566 utf8_filename = g_strdup(buf);
568 locale_filename = utils_get_locale_from_utf8(utf8_filename);
569 if (locale_filename)
571 if (g_str_has_suffix(locale_filename, ".geany"))
573 if (project_ask_close())
574 main_load_project_from_command_line(locale_filename, TRUE);
576 else
577 main_handle_filename(locale_filename);
579 g_free(utf8_filename);
580 g_free(locale_filename);
584 static gchar *build_document_list(void)
586 GString *doc_list = g_string_new(NULL);
587 guint i;
588 const gchar *filename;
590 foreach_document(i)
592 filename = DOC_FILENAME(documents[i]);
593 g_string_append(doc_list, filename);
594 g_string_append_c(doc_list, '\n');
596 return g_string_free(doc_list, FALSE);
600 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
602 gint fd, sock;
603 gchar buf[BUFFER_LENGTH];
604 struct sockaddr_in caddr;
605 socklen_t caddr_len = sizeof(caddr);
606 GtkWidget *window = data;
607 gboolean popup = FALSE;
609 fd = g_io_channel_unix_get_fd(source);
610 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
612 /* first get the command */
613 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
615 if (strncmp(buf, "open", 4) == 0)
617 cl_options.readonly = strncmp(buf+4, "ro", 2) == 0; /* open in readonly? */
618 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
620 gsize buf_len = strlen(buf);
622 /* remove trailing newline */
623 if (buf_len > 0 && buf[buf_len - 1] == '\n')
624 buf[buf_len - 1] = '\0';
626 handle_input_filename(buf);
628 popup = TRUE;
630 else if (strncmp(buf, "doclist", 7) == 0)
632 gchar *doc_list = build_document_list();
633 if (!EMPTY(doc_list))
634 socket_fd_write_all(sock, doc_list, strlen(doc_list));
635 /* send ETX (end-of-text) so reader knows to stop reading */
636 socket_fd_write_all(sock, "\3", 1);
637 g_free(doc_list);
639 else if (strncmp(buf, "line", 4) == 0)
641 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
643 g_strstrip(buf); /* remove \n char */
644 /* on any error we get 0 which should be safe enough as fallback */
645 cl_options.goto_line = atoi(buf);
648 else if (strncmp(buf, "column", 6) == 0)
650 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
652 g_strstrip(buf); /* remove \n char */
653 /* on any error we get 0 which should be safe enough as fallback */
654 cl_options.goto_column = atoi(buf);
657 #ifdef G_OS_WIN32
658 else if (strncmp(buf, "window", 6) == 0)
660 # if GTK_CHECK_VERSION(3, 0, 0)
661 HWND hwnd = (HWND) gdk_win32_window_get_handle(gtk_widget_get_window(window));
662 # else
663 HWND hwnd = (HWND) gdk_win32_drawable_get_handle(
664 GDK_DRAWABLE(gtk_widget_get_window(window)));
665 # endif
666 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
668 #endif
671 if (popup)
673 #ifdef GDK_WINDOWING_X11
674 GdkWindow *x11_window = gtk_widget_get_window(window);
676 /* Set the proper interaction time on the window. This seems necessary to make
677 * gtk_window_present() really bring the main window into the foreground on some
678 * window managers like Gnome's metacity.
679 * Code taken from Gedit. */
680 # if GTK_CHECK_VERSION(3, 0, 0)
681 if (GDK_IS_X11_WINDOW(x11_window))
682 # endif
684 gdk_x11_window_set_user_time(x11_window, gdk_x11_get_server_time(x11_window));
686 #endif
687 gtk_window_present(GTK_WINDOW(window));
688 #ifdef G_OS_WIN32
689 gdk_window_show(gtk_widget_get_window(window));
690 #endif
693 socket_fd_close(sock);
695 return TRUE;
699 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
701 gchar *newline, *bp = buf;
702 gint n;
704 if (--len < 1)
705 return -1;
708 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
709 return -1;
710 if ((newline = memchr(bp, '\n', n)) != NULL)
711 n = newline - bp + 1;
712 if ((n = socket_fd_read(fd, bp, n)) < 0)
713 return -1;
714 bp += n;
715 len -= n;
716 } while (! newline && len);
718 *bp = '\0';
719 return bp - buf;
723 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
725 if (socket_fd_check_io(fd, G_IO_IN) < 0)
726 return -1;
728 return recv(fd, buf, len, flags);
732 static gint socket_fd_read(gint fd, gchar *buf, gint len)
734 if (socket_fd_check_io(fd, G_IO_IN) < 0)
735 return -1;
737 #ifdef G_OS_WIN32
738 return recv(fd, buf, len, 0);
739 #else
740 return read(fd, buf, len);
741 #endif
745 static gint socket_fd_check_io(gint fd, GIOCondition cond)
747 struct timeval timeout;
748 fd_set fds;
749 #ifdef G_OS_UNIX
750 gint flags;
751 #endif
753 timeout.tv_sec = 60;
754 timeout.tv_usec = 0;
756 #ifdef G_OS_UNIX
757 /* checking for non-blocking mode */
758 flags = fcntl(fd, F_GETFL, 0);
759 if (flags < 0)
761 perror("fcntl");
762 return 0;
764 if ((flags & O_NONBLOCK) != 0)
765 return 0;
766 #endif
768 FD_ZERO(&fds);
769 #ifdef G_OS_WIN32
770 FD_SET((SOCKET)fd, &fds);
771 #else
772 FD_SET(fd, &fds);
773 #endif
775 if (cond == G_IO_IN)
777 select(fd + 1, &fds, NULL, NULL, &timeout);
779 else
781 select(fd + 1, NULL, &fds, NULL, &timeout);
784 if (FD_ISSET(fd, &fds))
786 return 0;
788 else
790 geany_debug("Socket IO timeout");
791 return -1;
796 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
798 gint n, wrlen = 0;
800 while (len)
802 n = socket_fd_write(fd, buf, len);
803 if (n <= 0)
804 return -1;
805 len -= n;
806 wrlen += n;
807 buf += n;
810 return wrlen;
814 gint socket_fd_write(gint fd, const gchar *buf, gint len)
816 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
817 return -1;
819 #ifdef G_OS_WIN32
820 return send(fd, buf, len, 0);
821 #else
822 return write(fd, buf, len);
823 #endif
827 #endif