Version bump.
[geany-mirror.git] / src / socket.c
blobf4ccd04e1ba5f78af2f78e8ff3129da11cc17c53
1 /*
2 * socket.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2006-2010 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2010 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
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * $Id$
26 * Socket setup and messages handling.
27 * The socket allows detection and messages to be sent to the first running instance of Geany.
28 * Only the first instance loads session files at startup, and opens files from the command-line.
32 * Little dev doc:
33 * Each command which is sent between two instances (see send_open_command and
34 * socket_lock_input_cb) should have the following scheme:
35 * command name\n
36 * data\n
37 * data\n
38 * ...
39 * .\n
40 * The first thing should be the command name followed by the data belonging to the command and
41 * to mark the end of data send a single '.'. Each message should be ended with \n.
42 * The command window is only available on Windows and takes no additional data, instead it
43 * writes back a Windows handle (HWND) for the main window to set it to the foreground (focus).
45 * At the moment the commands window, doclist, open, line and column are available.
47 * About the socket files on Unix-like systems:
48 * Geany creates a socket in /tmp (or any other directory returned by g_get_tmp_dir()) and
49 * a symlink in the current configuration to the created socket file. The symlink is named
50 * geany_socket_<hostname>_<displayname> (displayname is the name of the active X display).
51 * If the socket file cannot be created in the temporary directory, Geany creates the socket file
52 * directly in the configuration directory as a fallback.
57 #include "geany.h"
59 #ifdef HAVE_SOCKET
61 #ifndef G_OS_WIN32
62 # include <sys/time.h>
63 # include <sys/types.h>
64 # include <sys/socket.h>
65 # include <sys/un.h>
66 # include <netinet/in.h>
67 # include <glib/gstdio.h>
68 #else
69 # include <gdk/gdkwin32.h>
70 # include <windows.h>
71 # include <winsock2.h>
72 # include <ws2tcpip.h>
73 #endif
74 #include <string.h>
75 #include <stdlib.h>
76 #include <unistd.h>
77 #include <fcntl.h>
79 #ifdef GDK_WINDOWING_X11
80 #include <gdk/gdkx.h>
81 #endif
83 #include "main.h"
84 #include "socket.h"
85 #include "document.h"
86 #include "support.h"
87 #include "ui_utils.h"
88 #include "utils.h"
89 #include "dialogs.h"
90 #include "encodings.h"
94 #ifdef G_OS_WIN32
95 #define REMOTE_CMD_PORT 49876
96 #define SOCKET_IS_VALID(s) (G_LIKELY((s) != INVALID_SOCKET))
97 #else
98 #define SOCKET_IS_VALID(s) (G_LIKELY((s) >= 0))
99 #define INVALID_SOCKET (-1)
100 #endif
101 #define BUFFER_LENGTH 4096
103 struct socket_info_struct socket_info;
106 #ifdef G_OS_WIN32
107 static gint socket_fd_connect_inet (gushort port);
108 static gint socket_fd_open_inet (gushort port);
109 static void socket_init_win32 (void);
110 #else
111 static gint socket_fd_connect_unix (const gchar *path);
112 static gint socket_fd_open_unix (const gchar *path);
113 #endif
115 static gint socket_fd_write (gint sock, const gchar *buf, gint len);
116 static gint socket_fd_write_all (gint sock, const gchar *buf, gint len);
117 static gint socket_fd_gets (gint sock, gchar *buf, gint len);
118 static gint socket_fd_check_io (gint fd, GIOCondition cond);
119 static gint socket_fd_read (gint sock, gchar *buf, gint len);
120 static gint socket_fd_recv (gint fd, gchar *buf, gint len, gint flags);
121 static gint socket_fd_close (gint sock);
125 static void send_open_command(gint sock, gint argc, gchar **argv)
127 gint i;
128 gchar *filename;
130 g_return_if_fail(argc > 1);
131 geany_debug("using running instance of Geany");
133 if (cl_options.goto_line >= 0)
135 gchar *line = g_strdup_printf("%d\n", cl_options.goto_line);
136 socket_fd_write_all(sock, "line\n", 5);
137 socket_fd_write_all(sock, line, strlen(line));
138 socket_fd_write_all(sock, ".\n", 2);
139 g_free(line);
142 if (cl_options.goto_column >= 0)
144 gchar *col = g_strdup_printf("%d\n", cl_options.goto_column);
145 socket_fd_write_all(sock, "column\n", 7);
146 socket_fd_write_all(sock, col, strlen(col));
147 socket_fd_write_all(sock, ".\n", 2);
148 g_free(col);
151 socket_fd_write_all(sock, "open\n", 5);
153 for (i = 1; i < argc && argv[i] != NULL; i++)
155 filename = main_get_argv_filename(argv[i]);
157 /* if the filename is valid or if a new file should be opened is check on the other side */
158 if (filename != NULL)
160 socket_fd_write_all(sock, filename, strlen(filename));
161 socket_fd_write_all(sock, "\n", 1);
163 else
165 g_printerr(_("Could not find file '%s'."), filename);
166 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
168 g_free(filename);
170 socket_fd_write_all(sock, ".\n", 2);
174 #ifndef G_OS_WIN32
175 static void remove_socket_link_full(void)
177 gchar real_path[512];
178 gsize len;
180 real_path[0] = '\0';
182 /* read the contents of the symbolic link socket_info.file_name and delete it
183 * readlink should return something like "/tmp/geany_socket.499602d2" */
184 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
185 if ((gint) len > 0)
187 real_path[len] = '\0';
188 g_unlink(real_path);
190 g_unlink(socket_info.file_name);
192 #endif
195 static void socket_get_document_list(gint sock)
197 gchar doc_list[BUFFER_LENGTH];
198 gint doc_list_len;
200 if (sock < 0)
201 return;
203 socket_fd_write_all(sock, "doclist\n", 8);
205 doc_list_len = socket_fd_read(sock, doc_list, sizeof(doc_list));
206 if (doc_list_len >= BUFFER_LENGTH)
207 doc_list_len = BUFFER_LENGTH -1;
208 doc_list[doc_list_len] = '\0';
209 /* if we received ETX (end-of-text), there were no open files, so print only otherwise */
210 if (! utils_str_equal(doc_list, "\3"))
211 printf("%s", doc_list);
215 #ifndef G_OS_WIN32
216 static void check_socket_permissions(void)
218 struct stat socket_stat;
220 if (g_lstat(socket_info.file_name, &socket_stat) == 0)
221 { /* If the user id of the process is not the same as the owner of the socket
222 * file, then ignore this socket and start a new session. */
223 if (socket_stat.st_uid != getuid())
225 const gchar *msg = _(
226 /* TODO maybe this message needs a rewording */
227 "Geany tried to access the Unix Domain socket of another instance running as another user.\n"
228 "This is a fatal error and Geany will now quit.");
229 g_warning("%s", msg);
230 dialogs_show_msgbox(GTK_MESSAGE_ERROR, "%s", msg);
231 exit(1);
235 #endif
238 /* (Unix domain) socket support to replace the old FIFO code
239 * (taken from Sylpheed, thanks)
240 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
241 * were sent to it. */
242 gint socket_init(gint argc, gchar **argv)
244 gint sock;
245 #ifdef G_OS_WIN32
246 HANDLE hmutex;
247 HWND hwnd;
248 socket_init_win32();
249 hmutex = CreateMutexA(NULL, FALSE, "Geany");
250 if (! hmutex)
252 geany_debug("cannot create Mutex\n");
253 return -1;
255 if (GetLastError() != ERROR_ALREADY_EXISTS)
257 /* To support multiple instances with different configuration directories (as we do on
258 * non-Windows systems) we would need to use different port number s but it might be
259 * difficult to get a port number which is unique for a configuration directory (path)
260 * and which is unused. This port number has to be guessed by the first and new instance
261 * and the only data is the configuration directory path.
262 * For now we use one port number, that is we support only one instance at all. */
263 sock = socket_fd_open_inet(REMOTE_CMD_PORT);
264 if (sock < 0)
265 return 0;
266 return sock;
269 sock = socket_fd_connect_inet(REMOTE_CMD_PORT);
270 if (sock < 0)
271 return -1;
272 #else
273 gchar *display_name = gdk_get_display();
274 gchar *hostname = utils_get_hostname();
275 gchar *p;
277 if (display_name == NULL)
278 display_name = g_strdup("NODISPLAY");
280 /* these lines are taken from dcopc.c in kdelibs */
281 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
282 *p = '\0';
283 while ((p = strchr(display_name, ':')) != NULL)
284 *p = '_';
286 if (socket_info.file_name == NULL)
287 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
288 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
290 g_free(display_name);
291 g_free(hostname);
293 /* check whether the real user id is the same as this of the socket file */
294 check_socket_permissions();
296 sock = socket_fd_connect_unix(socket_info.file_name);
297 if (sock < 0)
299 remove_socket_link_full(); /* deletes the socket file and the symlink */
300 return socket_fd_open_unix(socket_info.file_name);
302 #endif
304 /* remote command mode, here we have another running instance and want to use it */
306 #ifdef G_OS_WIN32
307 /* first we send a request to retrieve the window handle and focus the window */
308 socket_fd_write_all(sock, "window\n", 7);
309 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
310 SetForegroundWindow(hwnd);
311 #endif
312 /* now we send the command line args */
313 if (argc > 1)
315 send_open_command(sock, argc, argv);
318 if (cl_options.list_documents)
320 socket_get_document_list(sock);
323 socket_fd_close(sock);
324 return -2;
328 gint socket_finalize(void)
330 if (socket_info.lock_socket < 0)
331 return -1;
333 if (socket_info.lock_socket_tag > 0)
334 g_source_remove(socket_info.lock_socket_tag);
335 if (socket_info.read_ioc)
337 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
338 g_io_channel_unref(socket_info.read_ioc);
339 socket_info.read_ioc = NULL;
342 #ifdef G_OS_WIN32
343 WSACleanup();
344 #else
345 if (socket_info.file_name != NULL)
347 remove_socket_link_full(); /* deletes the socket file and the symlink */
348 g_free(socket_info.file_name);
350 #endif
352 return 0;
356 #ifdef G_OS_UNIX
357 static gint socket_fd_connect_unix(const gchar *path)
359 gint sock;
360 struct sockaddr_un addr;
362 sock = socket(PF_UNIX, SOCK_STREAM, 0);
363 if (sock < 0)
365 perror("fd_connect_unix(): socket");
366 return -1;
369 memset(&addr, 0, sizeof(addr));
370 addr.sun_family = AF_UNIX;
371 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
373 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
375 socket_fd_close(sock);
376 return -1;
379 return sock;
383 static gint socket_fd_open_unix(const gchar *path)
385 gint sock;
386 struct sockaddr_un addr;
387 gint val;
388 gchar *real_path;
390 sock = socket(PF_UNIX, SOCK_STREAM, 0);
392 if (sock < 0)
394 perror("sock_open_unix(): socket");
395 return -1;
398 val = 1;
399 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
401 perror("setsockopt");
402 socket_fd_close(sock);
403 return -1;
406 /* fix for #1888561:
407 * in case the configuration directory is located on a network file system or any other
408 * file system which doesn't support sockets, we just link the socket there and create the
409 * real socket in the system's tmp directory assuming it supports sockets */
410 real_path = g_strdup_printf("%s%cgeany_socket.%08x",
411 g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());
413 if (utils_is_file_writeable(real_path) != 0)
414 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
415 /* instead of creating a symlink and print a warning */
416 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
417 setptr(real_path, g_strdup(path));
419 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
420 else if (symlink(real_path, path) != 0)
422 perror("symlink");
423 socket_fd_close(sock);
424 return -1;
427 memset(&addr, 0, sizeof(addr));
428 addr.sun_family = AF_UNIX;
429 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
431 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
433 perror("bind");
434 socket_fd_close(sock);
435 return -1;
438 if (listen(sock, 1) < 0)
440 perror("listen");
441 socket_fd_close(sock);
442 return -1;
445 g_chmod(real_path, 0600);
447 g_free(real_path);
449 return sock;
451 #endif
453 static gint socket_fd_close(gint fd)
455 #ifdef G_OS_WIN32
456 return closesocket(fd);
457 #else
458 return close(fd);
459 #endif
463 #ifdef G_OS_WIN32
464 static gint socket_fd_open_inet(gushort port)
466 SOCKET sock;
467 struct sockaddr_in addr;
468 gchar val;
470 sock = socket(AF_INET, SOCK_STREAM, 0);
471 if (! SOCKET_IS_VALID(sock))
473 geany_debug("fd_open_inet(): socket() failed: %d\n", WSAGetLastError());
474 return -1;
477 val = 1;
478 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
480 perror("setsockopt");
481 socket_fd_close(sock);
482 return -1;
485 memset(&addr, 0, sizeof(addr));
486 addr.sin_family = AF_INET;
487 addr.sin_port = htons(port);
488 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
490 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
492 perror("bind");
493 socket_fd_close(sock);
494 return -1;
497 if (listen(sock, 1) < 0)
499 perror("listen");
500 socket_fd_close(sock);
501 return -1;
504 return sock;
508 static gint socket_fd_connect_inet(gushort port)
510 SOCKET sock;
511 struct sockaddr_in addr;
513 sock = socket(AF_INET, SOCK_STREAM, 0);
514 if (! SOCKET_IS_VALID(sock))
516 geany_debug("fd_connect_inet(): socket() failed: %d\n", WSAGetLastError());
517 return -1;
520 memset(&addr, 0, sizeof(addr));
521 addr.sin_family = AF_INET;
522 addr.sin_port = htons(port);
523 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
525 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
527 socket_fd_close(sock);
528 return -1;
531 return sock;
535 static void socket_init_win32(void)
537 WSADATA wsadata;
539 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
540 geany_debug("WSAStartup() failed\n");
542 return;
544 #endif
547 static void handle_input_filename(const gchar *buf)
549 gchar *utf8_filename, *locale_filename;
551 /* we never know how the input is encoded, so do the best auto detection we can */
552 if (! g_utf8_validate(buf, -1, NULL))
553 utf8_filename = encodings_convert_to_utf8(buf, (gsize) -1, NULL);
554 else
555 utf8_filename = g_strdup(buf);
557 locale_filename = utils_get_locale_from_utf8(utf8_filename);
558 if (locale_filename)
560 if (g_str_has_suffix(locale_filename, ".geany"))
561 main_load_project_from_command_line(locale_filename, TRUE);
562 else
563 main_handle_filename(locale_filename);
565 g_free(utf8_filename);
566 g_free(locale_filename);
570 static gchar *build_document_list(void)
572 GString *doc_list = g_string_new(NULL);
573 guint i;
574 const gchar *filename;
576 foreach_document(i)
578 filename = DOC_FILENAME(documents[i]);
579 g_string_append(doc_list, filename);
580 g_string_append_c(doc_list, '\n');
582 return g_string_free(doc_list, FALSE);
586 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
588 gint fd, sock;
589 gchar buf[BUFFER_LENGTH];
590 struct sockaddr_in caddr;
591 guint caddr_len = sizeof(caddr);
592 GtkWidget *window = data;
593 gboolean popup = FALSE;
595 fd = g_io_channel_unix_get_fd(source);
596 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
598 /* first get the command */
599 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
601 if (strncmp(buf, "open", 4) == 0)
603 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
605 handle_input_filename(g_strstrip(buf));
607 popup = TRUE;
609 else if (strncmp(buf, "doclist", 7) == 0)
611 gchar *doc_list = build_document_list();
612 if (NZV(doc_list))
613 socket_fd_write_all(sock, doc_list, strlen(doc_list));
614 else
615 /* send ETX (end-of-text) in case we have no open files, we must send anything
616 * otherwise the client would hang on reading */
617 socket_fd_write_all(sock, "\3", 1);
618 g_free(doc_list);
620 else if (strncmp(buf, "line", 4) == 0)
622 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
624 g_strstrip(buf); /* remove \n char */
625 /* on any error we get 0 which should be safe enough as fallback */
626 cl_options.goto_line = atoi(buf);
629 else if (strncmp(buf, "column", 6) == 0)
631 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
633 g_strstrip(buf); /* remove \n char */
634 /* on any error we get 0 which should be safe enough as fallback */
635 cl_options.goto_column = atoi(buf);
638 #ifdef G_OS_WIN32
639 else if (strncmp(buf, "window", 6) == 0)
641 HWND hwnd = (HWND) gdk_win32_drawable_get_handle(GDK_DRAWABLE(window->window));
642 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
644 #endif
647 if (popup)
649 #ifdef GDK_WINDOWING_X11
650 /* Set the proper interaction time on the window. This seems necessary to make
651 * gtk_window_present() really bring the main window into the foreground on some
652 * window managers like Gnome's metacity.
653 * Code taken from Gedit. */
654 gdk_x11_window_set_user_time(window->window, gdk_x11_get_server_time(window->window));
655 #endif
656 gtk_window_present(GTK_WINDOW(window));
657 #ifdef G_OS_WIN32
658 gdk_window_show(window->window);
659 #endif
662 socket_fd_close(sock);
664 return TRUE;
668 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
670 gchar *newline, *bp = buf;
671 gint n;
673 if (--len < 1)
674 return -1;
677 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
678 return -1;
679 if ((newline = memchr(bp, '\n', n)) != NULL)
680 n = newline - bp + 1;
681 if ((n = socket_fd_read(fd, bp, n)) < 0)
682 return -1;
683 bp += n;
684 len -= n;
685 } while (! newline && len);
687 *bp = '\0';
688 return bp - buf;
692 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
694 if (socket_fd_check_io(fd, G_IO_IN) < 0)
695 return -1;
697 return recv(fd, buf, len, flags);
701 static gint socket_fd_read(gint fd, gchar *buf, gint len)
703 if (socket_fd_check_io(fd, G_IO_IN) < 0)
704 return -1;
706 #ifdef G_OS_WIN32
707 return recv(fd, buf, len, 0);
708 #else
709 return read(fd, buf, len);
710 #endif
714 static gint socket_fd_check_io(gint fd, GIOCondition cond)
716 struct timeval timeout;
717 fd_set fds;
718 #ifdef G_OS_UNIX
719 gint flags;
720 #endif
722 timeout.tv_sec = 60;
723 timeout.tv_usec = 0;
725 #ifdef G_OS_UNIX
726 /* checking for non-blocking mode */
727 flags = fcntl(fd, F_GETFL, 0);
728 if (flags < 0)
730 perror("fcntl");
731 return 0;
733 if ((flags & O_NONBLOCK) != 0)
734 return 0;
735 #endif
737 FD_ZERO(&fds);
738 FD_SET(fd, &fds);
740 if (cond == G_IO_IN)
742 select(fd + 1, &fds, NULL, NULL, &timeout);
744 else
746 select(fd + 1, NULL, &fds, NULL, &timeout);
749 if (FD_ISSET(fd, &fds))
751 return 0;
753 else
755 geany_debug("Socket IO timeout");
756 return -1;
761 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
763 gint n, wrlen = 0;
765 while (len)
767 n = socket_fd_write(fd, buf, len);
768 if (n <= 0)
769 return -1;
770 len -= n;
771 wrlen += n;
772 buf += n;
775 return wrlen;
779 gint socket_fd_write(gint fd, const gchar *buf, gint len)
781 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
782 return -1;
784 #ifdef G_OS_WIN32
785 return send(fd, buf, len, 0);
786 #else
787 return write(fd, buf, len);
788 #endif
792 #endif