Merge pull request #890 from kugel-/gtkdoc-hdr
[geany-mirror.git] / src / socket.c
blob3b2fe55d49ab3b749c58957a46acdbe5825a2a4e
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 "socket.h"
62 #include "app.h"
63 #include "dialogs.h"
64 #include "document.h"
65 #include "encodings.h"
66 #include "main.h"
67 #include "support.h"
68 #include "utils.h"
69 #include "win32.h"
71 #include "gtkcompat.h"
74 #ifndef G_OS_WIN32
75 # include <sys/time.h>
76 # include <sys/types.h>
77 # include <sys/socket.h>
78 # include <sys/un.h>
79 # include <netinet/in.h>
80 # include <glib/gstdio.h>
81 #else
82 # include <winsock2.h>
83 # include <windows.h>
84 # include <gdk/gdkwin32.h>
85 # include <ws2tcpip.h>
86 #endif
87 #include <string.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 REMOTE_CMD_PORT 49876
99 #define SOCKET_IS_VALID(s) ((s) != INVALID_SOCKET)
100 #else
101 #define SOCKET_IS_VALID(s) ((s) >= 0)
102 #define INVALID_SOCKET (-1)
103 #endif
104 #define BUFFER_LENGTH 4096
106 struct socket_info_struct socket_info;
109 #ifdef G_OS_WIN32
110 static gint socket_fd_connect_inet (gushort port);
111 static gint socket_fd_open_inet (gushort port);
112 static void socket_init_win32 (void);
113 #else
114 static gint socket_fd_connect_unix (const gchar *path);
115 static gint socket_fd_open_unix (const gchar *path);
116 #endif
118 static gint socket_fd_write (gint sock, const gchar *buf, gint len);
119 static gint socket_fd_write_all (gint sock, const gchar *buf, gint len);
120 static gint socket_fd_gets (gint sock, gchar *buf, gint len);
121 static gint socket_fd_check_io (gint fd, GIOCondition cond);
122 static gint socket_fd_read (gint sock, gchar *buf, gint len);
123 static gint socket_fd_recv (gint fd, gchar *buf, gint len, gint flags);
124 static gint socket_fd_close (gint sock);
128 static void send_open_command(gint sock, gint argc, gchar **argv)
130 gint i;
131 gchar *filename;
133 g_return_if_fail(argc > 1);
134 geany_debug("using running instance of Geany");
136 if (cl_options.goto_line >= 0)
138 gchar *line = g_strdup_printf("%d\n", cl_options.goto_line);
139 socket_fd_write_all(sock, "line\n", 5);
140 socket_fd_write_all(sock, line, strlen(line));
141 socket_fd_write_all(sock, ".\n", 2);
142 g_free(line);
145 if (cl_options.goto_column >= 0)
147 gchar *col = g_strdup_printf("%d\n", cl_options.goto_column);
148 socket_fd_write_all(sock, "column\n", 7);
149 socket_fd_write_all(sock, col, strlen(col));
150 socket_fd_write_all(sock, ".\n", 2);
151 g_free(col);
154 if (cl_options.readonly) /* append "ro" to denote readonly status for new docs */
155 socket_fd_write_all(sock, "openro\n", 7);
156 else
157 socket_fd_write_all(sock, "open\n", 5);
159 for (i = 1; i < argc && argv[i] != NULL; i++)
161 filename = main_get_argv_filename(argv[i]);
163 /* if the filename is valid or if a new file should be opened is check on the other side */
164 if (filename != NULL)
166 socket_fd_write_all(sock, filename, strlen(filename));
167 socket_fd_write_all(sock, "\n", 1);
169 else
171 g_printerr(_("Could not find file '%s'."), filename);
172 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
174 g_free(filename);
176 socket_fd_write_all(sock, ".\n", 2);
180 #ifndef G_OS_WIN32
181 static void remove_socket_link_full(void)
183 gchar real_path[512];
184 gsize len;
186 real_path[0] = '\0';
188 /* read the contents of the symbolic link socket_info.file_name and delete it
189 * readlink should return something like "/tmp/geany_socket.499602d2" */
190 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
191 if ((gint) len > 0)
193 real_path[len] = '\0';
194 g_unlink(real_path);
196 g_unlink(socket_info.file_name);
198 #endif
201 static void socket_get_document_list(gint sock)
203 gchar buf[BUFFER_LENGTH];
204 gint n_read;
206 if (sock < 0)
207 return;
209 socket_fd_write_all(sock, "doclist\n", 8);
213 n_read = socket_fd_read(sock, buf, BUFFER_LENGTH);
214 /* if we received ETX (end-of-text), there is nothing else to read, so cut that
215 * byte not to output it and to be sure not to validate the loop condition */
216 if (n_read > 0 && buf[n_read - 1] == '\3')
217 n_read--;
218 if (n_read > 0)
219 fwrite(buf, 1, n_read, stdout);
221 while (n_read >= BUFFER_LENGTH);
225 #ifndef G_OS_WIN32
226 static void check_socket_permissions(void)
228 GStatBuf socket_stat;
230 if (g_lstat(socket_info.file_name, &socket_stat) == 0)
231 { /* If the user id of the process is not the same as the owner of the socket
232 * file, then ignore this socket and start a new session. */
233 if (socket_stat.st_uid != getuid())
235 const gchar *msg = _(
236 /* TODO maybe this message needs a rewording */
237 "Geany tried to access the Unix Domain socket of another instance running as another user.\n"
238 "This is a fatal error and Geany will now quit.");
239 g_warning("%s", msg);
240 dialogs_show_msgbox(GTK_MESSAGE_ERROR, "%s", msg);
241 exit(1);
245 #endif
248 /* (Unix domain) socket support to replace the old FIFO code
249 * (taken from Sylpheed, thanks)
250 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
251 * were sent to it. */
252 gint socket_init(gint argc, gchar **argv)
254 gint sock;
255 #ifdef G_OS_WIN32
256 HANDLE hmutex;
257 HWND hwnd;
258 socket_init_win32();
259 hmutex = CreateMutexA(NULL, FALSE, "Geany");
260 if (! hmutex)
262 geany_debug("cannot create Mutex\n");
263 return -1;
265 if (GetLastError() != ERROR_ALREADY_EXISTS)
267 /* To support multiple instances with different configuration directories (as we do on
268 * non-Windows systems) we would need to use different port number s but it might be
269 * difficult to get a port number which is unique for a configuration directory (path)
270 * and which is unused. This port number has to be guessed by the first and new instance
271 * and the only data is the configuration directory path.
272 * For now we use one port number, that is we support only one instance at all. */
273 sock = socket_fd_open_inet(REMOTE_CMD_PORT);
274 if (sock < 0)
275 return 0;
276 return sock;
279 sock = socket_fd_connect_inet(REMOTE_CMD_PORT);
280 if (sock < 0)
281 return -1;
282 #else
283 gchar *display_name = NULL;
284 const gchar *hostname = g_get_host_name();
285 GdkDisplay *display = gdk_display_get_default();
286 gchar *p;
288 if (display != NULL)
289 display_name = g_strdup(gdk_display_get_name(display));
290 if (display_name == NULL)
291 display_name = g_strdup("NODISPLAY");
293 /* these lines are taken from dcopc.c in kdelibs */
294 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
295 *p = '\0';
296 /* remove characters that may not be acceptable in a filename */
297 for (p = display_name; *p; p++)
299 if (*p == ':' || *p == '/')
300 *p = '_';
303 if (socket_info.file_name == NULL)
304 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
305 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
307 g_free(display_name);
309 /* check whether the real user id is the same as this of the socket file */
310 check_socket_permissions();
312 sock = socket_fd_connect_unix(socket_info.file_name);
313 if (sock < 0)
315 remove_socket_link_full(); /* deletes the socket file and the symlink */
316 return socket_fd_open_unix(socket_info.file_name);
318 #endif
320 /* remote command mode, here we have another running instance and want to use it */
322 #ifdef G_OS_WIN32
323 /* first we send a request to retrieve the window handle and focus the window */
324 socket_fd_write_all(sock, "window\n", 7);
325 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
326 SetForegroundWindow(hwnd);
327 #endif
328 /* now we send the command line args */
329 if (argc > 1)
331 send_open_command(sock, argc, argv);
334 if (cl_options.list_documents)
336 socket_get_document_list(sock);
339 socket_fd_close(sock);
340 return -2;
344 gint socket_finalize(void)
346 if (socket_info.lock_socket < 0)
347 return -1;
349 if (socket_info.lock_socket_tag > 0)
350 g_source_remove(socket_info.lock_socket_tag);
351 if (socket_info.read_ioc)
353 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
354 g_io_channel_unref(socket_info.read_ioc);
355 socket_info.read_ioc = NULL;
358 #ifdef G_OS_WIN32
359 WSACleanup();
360 #else
361 if (socket_info.file_name != NULL)
363 remove_socket_link_full(); /* deletes the socket file and the symlink */
364 g_free(socket_info.file_name);
366 #endif
368 return 0;
372 #ifdef G_OS_UNIX
373 static gint socket_fd_connect_unix(const gchar *path)
375 gint sock;
376 struct sockaddr_un addr;
378 sock = socket(PF_UNIX, SOCK_STREAM, 0);
379 if (sock < 0)
381 perror("fd_connect_unix(): socket");
382 return -1;
385 memset(&addr, 0, sizeof(addr));
386 addr.sun_family = AF_UNIX;
387 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
389 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
391 socket_fd_close(sock);
392 return -1;
395 return sock;
399 static gint socket_fd_open_unix(const gchar *path)
401 gint sock;
402 struct sockaddr_un addr;
403 gint val;
404 gchar *real_path;
406 sock = socket(PF_UNIX, SOCK_STREAM, 0);
408 if (sock < 0)
410 perror("sock_open_unix(): socket");
411 return -1;
414 val = 1;
415 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
417 perror("setsockopt");
418 socket_fd_close(sock);
419 return -1;
422 /* fix for #1888561:
423 * in case the configuration directory is located on a network file system or any other
424 * file system which doesn't support sockets, we just link the socket there and create the
425 * real socket in the system's tmp directory assuming it supports sockets */
426 real_path = g_strdup_printf("%s%cgeany_socket.%08x",
427 g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());
429 if (utils_is_file_writable(real_path) != 0)
430 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
431 /* instead of creating a symlink and print a warning */
432 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
433 SETPTR(real_path, g_strdup(path));
435 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
436 else if (symlink(real_path, path) != 0)
438 perror("symlink");
439 socket_fd_close(sock);
440 return -1;
443 memset(&addr, 0, sizeof(addr));
444 addr.sun_family = AF_UNIX;
445 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
447 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
449 perror("bind");
450 socket_fd_close(sock);
451 return -1;
454 if (listen(sock, 1) < 0)
456 perror("listen");
457 socket_fd_close(sock);
458 return -1;
461 g_chmod(real_path, 0600);
463 g_free(real_path);
465 return sock;
467 #endif
469 static gint socket_fd_close(gint fd)
471 #ifdef G_OS_WIN32
472 return closesocket(fd);
473 #else
474 return close(fd);
475 #endif
479 #ifdef G_OS_WIN32
480 static gint socket_fd_open_inet(gushort port)
482 SOCKET sock;
483 struct sockaddr_in addr;
484 gchar val;
486 sock = socket(AF_INET, SOCK_STREAM, 0);
487 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
489 geany_debug("fd_open_inet(): socket() failed: %d\n", WSAGetLastError());
490 return -1;
493 val = 1;
494 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
496 perror("setsockopt");
497 socket_fd_close(sock);
498 return -1;
501 memset(&addr, 0, sizeof(addr));
502 addr.sin_family = AF_INET;
503 addr.sin_port = htons(port);
504 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
506 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
508 perror("bind");
509 socket_fd_close(sock);
510 return -1;
513 if (listen(sock, 1) < 0)
515 perror("listen");
516 socket_fd_close(sock);
517 return -1;
520 return sock;
524 static gint socket_fd_connect_inet(gushort port)
526 SOCKET sock;
527 struct sockaddr_in addr;
529 sock = socket(AF_INET, SOCK_STREAM, 0);
530 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
532 geany_debug("fd_connect_inet(): socket() failed: %d\n", WSAGetLastError());
533 return -1;
536 memset(&addr, 0, sizeof(addr));
537 addr.sin_family = AF_INET;
538 addr.sin_port = htons(port);
539 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
541 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
543 socket_fd_close(sock);
544 return -1;
547 return sock;
551 static void socket_init_win32(void)
553 WSADATA wsadata;
555 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
556 geany_debug("WSAStartup() failed\n");
558 return;
560 #endif
563 static void handle_input_filename(const gchar *buf)
565 gchar *utf8_filename, *locale_filename;
567 /* we never know how the input is encoded, so do the best auto detection we can */
568 if (! g_utf8_validate(buf, -1, NULL))
569 utf8_filename = encodings_convert_to_utf8(buf, -1, NULL);
570 else
571 utf8_filename = g_strdup(buf);
573 locale_filename = utils_get_locale_from_utf8(utf8_filename);
574 if (locale_filename)
576 if (g_str_has_suffix(locale_filename, ".geany"))
578 if (project_ask_close())
579 main_load_project_from_command_line(locale_filename, TRUE);
581 else
582 main_handle_filename(locale_filename);
584 g_free(utf8_filename);
585 g_free(locale_filename);
589 static gchar *build_document_list(void)
591 GString *doc_list = g_string_new(NULL);
592 guint i;
593 const gchar *filename;
595 foreach_document(i)
597 filename = DOC_FILENAME(documents[i]);
598 g_string_append(doc_list, filename);
599 g_string_append_c(doc_list, '\n');
601 return g_string_free(doc_list, FALSE);
605 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
607 gint fd, sock;
608 gchar buf[BUFFER_LENGTH];
609 struct sockaddr_in caddr;
610 socklen_t caddr_len = sizeof(caddr);
611 GtkWidget *window = data;
612 gboolean popup = FALSE;
614 fd = g_io_channel_unix_get_fd(source);
615 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
617 /* first get the command */
618 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
620 if (strncmp(buf, "open", 4) == 0)
622 cl_options.readonly = strncmp(buf+4, "ro", 2) == 0; /* open in readonly? */
623 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
625 gsize buf_len = strlen(buf);
627 /* remove trailing newline */
628 if (buf_len > 0 && buf[buf_len - 1] == '\n')
629 buf[buf_len - 1] = '\0';
631 handle_input_filename(buf);
633 popup = TRUE;
635 else if (strncmp(buf, "doclist", 7) == 0)
637 gchar *doc_list = build_document_list();
638 if (!EMPTY(doc_list))
639 socket_fd_write_all(sock, doc_list, strlen(doc_list));
640 /* send ETX (end-of-text) so reader knows to stop reading */
641 socket_fd_write_all(sock, "\3", 1);
642 g_free(doc_list);
644 else if (strncmp(buf, "line", 4) == 0)
646 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
648 g_strstrip(buf); /* remove \n char */
649 /* on any error we get 0 which should be safe enough as fallback */
650 cl_options.goto_line = atoi(buf);
653 else if (strncmp(buf, "column", 6) == 0)
655 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
657 g_strstrip(buf); /* remove \n char */
658 /* on any error we get 0 which should be safe enough as fallback */
659 cl_options.goto_column = atoi(buf);
662 #ifdef G_OS_WIN32
663 else if (strncmp(buf, "window", 6) == 0)
665 # if GTK_CHECK_VERSION(3, 0, 0)
666 HWND hwnd = (HWND) gdk_win32_window_get_handle(gtk_widget_get_window(window));
667 # else
668 HWND hwnd = (HWND) gdk_win32_drawable_get_handle(
669 GDK_DRAWABLE(gtk_widget_get_window(window)));
670 # endif
671 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
673 #endif
676 if (popup)
678 #ifdef GDK_WINDOWING_X11
679 GdkWindow *x11_window = gtk_widget_get_window(window);
681 /* Set the proper interaction time on the window. This seems necessary to make
682 * gtk_window_present() really bring the main window into the foreground on some
683 * window managers like Gnome's metacity.
684 * Code taken from Gedit. */
685 # if GTK_CHECK_VERSION(3, 0, 0)
686 if (GDK_IS_X11_WINDOW(x11_window))
687 # endif
689 gdk_x11_window_set_user_time(x11_window, gdk_x11_get_server_time(x11_window));
691 #endif
692 gtk_window_present(GTK_WINDOW(window));
693 #ifdef G_OS_WIN32
694 gdk_window_show(gtk_widget_get_window(window));
695 #endif
698 socket_fd_close(sock);
700 return TRUE;
704 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
706 gchar *newline, *bp = buf;
707 gint n;
709 if (--len < 1)
710 return -1;
713 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
714 return -1;
715 if ((newline = memchr(bp, '\n', n)) != NULL)
716 n = newline - bp + 1;
717 if ((n = socket_fd_read(fd, bp, n)) < 0)
718 return -1;
719 bp += n;
720 len -= n;
721 } while (! newline && len);
723 *bp = '\0';
724 return bp - buf;
728 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
730 if (socket_fd_check_io(fd, G_IO_IN) < 0)
731 return -1;
733 return recv(fd, buf, len, flags);
737 static gint socket_fd_read(gint fd, gchar *buf, gint len)
739 if (socket_fd_check_io(fd, G_IO_IN) < 0)
740 return -1;
742 #ifdef G_OS_WIN32
743 return recv(fd, buf, len, 0);
744 #else
745 return read(fd, buf, len);
746 #endif
750 static gint socket_fd_check_io(gint fd, GIOCondition cond)
752 struct timeval timeout;
753 fd_set fds;
754 #ifdef G_OS_UNIX
755 gint flags;
756 #endif
758 timeout.tv_sec = 60;
759 timeout.tv_usec = 0;
761 #ifdef G_OS_UNIX
762 /* checking for non-blocking mode */
763 flags = fcntl(fd, F_GETFL, 0);
764 if (flags < 0)
766 perror("fcntl");
767 return 0;
769 if ((flags & O_NONBLOCK) != 0)
770 return 0;
771 #endif
773 FD_ZERO(&fds);
774 #ifdef G_OS_WIN32
775 FD_SET((SOCKET)fd, &fds);
776 #else
777 FD_SET(fd, &fds);
778 #endif
780 if (cond == G_IO_IN)
782 select(fd + 1, &fds, NULL, NULL, &timeout);
784 else
786 select(fd + 1, NULL, &fds, NULL, &timeout);
789 if (FD_ISSET(fd, &fds))
791 return 0;
793 else
795 geany_debug("Socket IO timeout");
796 return -1;
801 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
803 gint n, wrlen = 0;
805 while (len)
807 n = socket_fd_write(fd, buf, len);
808 if (n <= 0)
809 return -1;
810 len -= n;
811 wrlen += n;
812 buf += n;
815 return wrlen;
819 gint socket_fd_write(gint fd, const gchar *buf, gint len)
821 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
822 return -1;
824 #ifdef G_OS_WIN32
825 return send(fd, buf, len, 0);
826 #else
827 return write(fd, buf, len);
828 #endif
832 #endif