Fixup various filedefs mappings
[geany-mirror.git] / src / socket.c
blobbf0dea16246441b360a5e2674a3de6fd6b44b3b0
1 /*
2 * socket.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2006-2011 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2011 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.
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, 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 <gdk/gdkwin32.h>
68 # include <windows.h>
69 # include <winsock2.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"
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 socket_fd_write_all(sock, "open\n", 5);
151 for (i = 1; i < argc && argv[i] != NULL; i++)
153 filename = main_get_argv_filename(argv[i]);
155 /* if the filename is valid or if a new file should be opened is check on the other side */
156 if (filename != NULL)
158 socket_fd_write_all(sock, filename, strlen(filename));
159 socket_fd_write_all(sock, "\n", 1);
161 else
163 g_printerr(_("Could not find file '%s'."), filename);
164 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
166 g_free(filename);
168 socket_fd_write_all(sock, ".\n", 2);
172 #ifndef G_OS_WIN32
173 static void remove_socket_link_full(void)
175 gchar real_path[512];
176 gsize len;
178 real_path[0] = '\0';
180 /* read the contents of the symbolic link socket_info.file_name and delete it
181 * readlink should return something like "/tmp/geany_socket.499602d2" */
182 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
183 if ((gint) len > 0)
185 real_path[len] = '\0';
186 g_unlink(real_path);
188 g_unlink(socket_info.file_name);
190 #endif
193 static void socket_get_document_list(gint sock)
195 gchar doc_list[BUFFER_LENGTH];
196 gint doc_list_len;
198 if (sock < 0)
199 return;
201 socket_fd_write_all(sock, "doclist\n", 8);
203 doc_list_len = socket_fd_read(sock, doc_list, sizeof(doc_list));
204 if (doc_list_len >= BUFFER_LENGTH)
205 doc_list_len = BUFFER_LENGTH -1;
206 doc_list[doc_list_len] = '\0';
207 /* if we received ETX (end-of-text), there were no open files, so print only otherwise */
208 if (! utils_str_equal(doc_list, "\3"))
209 printf("%s", doc_list);
213 #ifndef G_OS_WIN32
214 static void check_socket_permissions(void)
216 struct stat socket_stat;
218 if (g_lstat(socket_info.file_name, &socket_stat) == 0)
219 { /* If the user id of the process is not the same as the owner of the socket
220 * file, then ignore this socket and start a new session. */
221 if (socket_stat.st_uid != getuid())
223 const gchar *msg = _(
224 /* TODO maybe this message needs a rewording */
225 "Geany tried to access the Unix Domain socket of another instance running as another user.\n"
226 "This is a fatal error and Geany will now quit.");
227 g_warning("%s", msg);
228 dialogs_show_msgbox(GTK_MESSAGE_ERROR, "%s", msg);
229 exit(1);
233 #endif
236 /* (Unix domain) socket support to replace the old FIFO code
237 * (taken from Sylpheed, thanks)
238 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
239 * were sent to it. */
240 gint socket_init(gint argc, gchar **argv)
242 gint sock;
243 #ifdef G_OS_WIN32
244 HANDLE hmutex;
245 HWND hwnd;
246 socket_init_win32();
247 hmutex = CreateMutexA(NULL, FALSE, "Geany");
248 if (! hmutex)
250 geany_debug("cannot create Mutex\n");
251 return -1;
253 if (GetLastError() != ERROR_ALREADY_EXISTS)
255 /* To support multiple instances with different configuration directories (as we do on
256 * non-Windows systems) we would need to use different port number s but it might be
257 * difficult to get a port number which is unique for a configuration directory (path)
258 * and which is unused. This port number has to be guessed by the first and new instance
259 * and the only data is the configuration directory path.
260 * For now we use one port number, that is we support only one instance at all. */
261 sock = socket_fd_open_inet(REMOTE_CMD_PORT);
262 if (sock < 0)
263 return 0;
264 return sock;
267 sock = socket_fd_connect_inet(REMOTE_CMD_PORT);
268 if (sock < 0)
269 return -1;
270 #else
271 gchar *display_name = gdk_get_display();
272 gchar *hostname = utils_get_hostname();
273 gchar *p;
275 if (display_name == NULL)
276 display_name = g_strdup("NODISPLAY");
278 /* these lines are taken from dcopc.c in kdelibs */
279 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
280 *p = '\0';
281 while ((p = strchr(display_name, ':')) != NULL)
282 *p = '_';
284 if (socket_info.file_name == NULL)
285 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
286 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
288 g_free(display_name);
289 g_free(hostname);
291 /* check whether the real user id is the same as this of the socket file */
292 check_socket_permissions();
294 sock = socket_fd_connect_unix(socket_info.file_name);
295 if (sock < 0)
297 remove_socket_link_full(); /* deletes the socket file and the symlink */
298 return socket_fd_open_unix(socket_info.file_name);
300 #endif
302 /* remote command mode, here we have another running instance and want to use it */
304 #ifdef G_OS_WIN32
305 /* first we send a request to retrieve the window handle and focus the window */
306 socket_fd_write_all(sock, "window\n", 7);
307 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
308 SetForegroundWindow(hwnd);
309 #endif
310 /* now we send the command line args */
311 if (argc > 1)
313 send_open_command(sock, argc, argv);
316 if (cl_options.list_documents)
318 socket_get_document_list(sock);
321 socket_fd_close(sock);
322 return -2;
326 gint socket_finalize(void)
328 if (socket_info.lock_socket < 0)
329 return -1;
331 if (socket_info.lock_socket_tag > 0)
332 g_source_remove(socket_info.lock_socket_tag);
333 if (socket_info.read_ioc)
335 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
336 g_io_channel_unref(socket_info.read_ioc);
337 socket_info.read_ioc = NULL;
340 #ifdef G_OS_WIN32
341 WSACleanup();
342 #else
343 if (socket_info.file_name != NULL)
345 remove_socket_link_full(); /* deletes the socket file and the symlink */
346 g_free(socket_info.file_name);
348 #endif
350 return 0;
354 #ifdef G_OS_UNIX
355 static gint socket_fd_connect_unix(const gchar *path)
357 gint sock;
358 struct sockaddr_un addr;
360 sock = socket(PF_UNIX, SOCK_STREAM, 0);
361 if (sock < 0)
363 perror("fd_connect_unix(): socket");
364 return -1;
367 memset(&addr, 0, sizeof(addr));
368 addr.sun_family = AF_UNIX;
369 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
371 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
373 socket_fd_close(sock);
374 return -1;
377 return sock;
381 static gint socket_fd_open_unix(const gchar *path)
383 gint sock;
384 struct sockaddr_un addr;
385 gint val;
386 gchar *real_path;
388 sock = socket(PF_UNIX, SOCK_STREAM, 0);
390 if (sock < 0)
392 perror("sock_open_unix(): socket");
393 return -1;
396 val = 1;
397 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
399 perror("setsockopt");
400 socket_fd_close(sock);
401 return -1;
404 /* fix for #1888561:
405 * in case the configuration directory is located on a network file system or any other
406 * file system which doesn't support sockets, we just link the socket there and create the
407 * real socket in the system's tmp directory assuming it supports sockets */
408 real_path = g_strdup_printf("%s%cgeany_socket.%08x",
409 g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());
411 if (utils_is_file_writable(real_path) != 0)
412 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
413 /* instead of creating a symlink and print a warning */
414 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
415 setptr(real_path, g_strdup(path));
417 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
418 else if (symlink(real_path, path) != 0)
420 perror("symlink");
421 socket_fd_close(sock);
422 return -1;
425 memset(&addr, 0, sizeof(addr));
426 addr.sun_family = AF_UNIX;
427 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
429 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
431 perror("bind");
432 socket_fd_close(sock);
433 return -1;
436 if (listen(sock, 1) < 0)
438 perror("listen");
439 socket_fd_close(sock);
440 return -1;
443 g_chmod(real_path, 0600);
445 g_free(real_path);
447 return sock;
449 #endif
451 static gint socket_fd_close(gint fd)
453 #ifdef G_OS_WIN32
454 return closesocket(fd);
455 #else
456 return close(fd);
457 #endif
461 #ifdef G_OS_WIN32
462 static gint socket_fd_open_inet(gushort port)
464 SOCKET sock;
465 struct sockaddr_in addr;
466 gchar val;
468 sock = socket(AF_INET, SOCK_STREAM, 0);
469 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
471 geany_debug("fd_open_inet(): socket() failed: %d\n", WSAGetLastError());
472 return -1;
475 val = 1;
476 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
478 perror("setsockopt");
479 socket_fd_close(sock);
480 return -1;
483 memset(&addr, 0, sizeof(addr));
484 addr.sin_family = AF_INET;
485 addr.sin_port = htons(port);
486 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
488 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
490 perror("bind");
491 socket_fd_close(sock);
492 return -1;
495 if (listen(sock, 1) < 0)
497 perror("listen");
498 socket_fd_close(sock);
499 return -1;
502 return sock;
506 static gint socket_fd_connect_inet(gushort port)
508 SOCKET sock;
509 struct sockaddr_in addr;
511 sock = socket(AF_INET, SOCK_STREAM, 0);
512 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
514 geany_debug("fd_connect_inet(): socket() failed: %d\n", WSAGetLastError());
515 return -1;
518 memset(&addr, 0, sizeof(addr));
519 addr.sin_family = AF_INET;
520 addr.sin_port = htons(port);
521 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
523 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
525 socket_fd_close(sock);
526 return -1;
529 return sock;
533 static void socket_init_win32(void)
535 WSADATA wsadata;
537 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
538 geany_debug("WSAStartup() failed\n");
540 return;
542 #endif
545 static void handle_input_filename(const gchar *buf)
547 gchar *utf8_filename, *locale_filename;
549 /* we never know how the input is encoded, so do the best auto detection we can */
550 if (! g_utf8_validate(buf, -1, NULL))
551 utf8_filename = encodings_convert_to_utf8(buf, (gsize) -1, NULL);
552 else
553 utf8_filename = g_strdup(buf);
555 locale_filename = utils_get_locale_from_utf8(utf8_filename);
556 if (locale_filename)
558 if (g_str_has_suffix(locale_filename, ".geany"))
559 main_load_project_from_command_line(locale_filename, TRUE);
560 else
561 main_handle_filename(locale_filename);
563 g_free(utf8_filename);
564 g_free(locale_filename);
568 static gchar *build_document_list(void)
570 GString *doc_list = g_string_new(NULL);
571 guint i;
572 const gchar *filename;
574 foreach_document(i)
576 filename = DOC_FILENAME(documents[i]);
577 g_string_append(doc_list, filename);
578 g_string_append_c(doc_list, '\n');
580 return g_string_free(doc_list, FALSE);
584 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
586 gint fd, sock;
587 gchar buf[BUFFER_LENGTH];
588 struct sockaddr_in caddr;
589 socklen_t caddr_len = sizeof(caddr);
590 GtkWidget *window = data;
591 gboolean popup = FALSE;
593 fd = g_io_channel_unix_get_fd(source);
594 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
596 /* first get the command */
597 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
599 if (strncmp(buf, "open", 4) == 0)
601 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
603 handle_input_filename(g_strstrip(buf));
605 popup = TRUE;
607 else if (strncmp(buf, "doclist", 7) == 0)
609 gchar *doc_list = build_document_list();
610 if (NZV(doc_list))
611 socket_fd_write_all(sock, doc_list, strlen(doc_list));
612 else
613 /* send ETX (end-of-text) in case we have no open files, we must send anything
614 * otherwise the client would hang on reading */
615 socket_fd_write_all(sock, "\3", 1);
616 g_free(doc_list);
618 else if (strncmp(buf, "line", 4) == 0)
620 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
622 g_strstrip(buf); /* remove \n char */
623 /* on any error we get 0 which should be safe enough as fallback */
624 cl_options.goto_line = atoi(buf);
627 else if (strncmp(buf, "column", 6) == 0)
629 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
631 g_strstrip(buf); /* remove \n char */
632 /* on any error we get 0 which should be safe enough as fallback */
633 cl_options.goto_column = atoi(buf);
636 #ifdef G_OS_WIN32
637 else if (strncmp(buf, "window", 6) == 0)
639 HWND hwnd = (HWND) gdk_win32_drawable_get_handle(GDK_DRAWABLE(window->window));
640 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
642 #endif
645 if (popup)
647 #ifdef GDK_WINDOWING_X11
648 /* Set the proper interaction time on the window. This seems necessary to make
649 * gtk_window_present() really bring the main window into the foreground on some
650 * window managers like Gnome's metacity.
651 * Code taken from Gedit. */
652 gdk_x11_window_set_user_time(window->window, gdk_x11_get_server_time(window->window));
653 #endif
654 gtk_window_present(GTK_WINDOW(window));
655 #ifdef G_OS_WIN32
656 gdk_window_show(window->window);
657 #endif
660 socket_fd_close(sock);
662 return TRUE;
666 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
668 gchar *newline, *bp = buf;
669 gint n;
671 if (--len < 1)
672 return -1;
675 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
676 return -1;
677 if ((newline = memchr(bp, '\n', n)) != NULL)
678 n = newline - bp + 1;
679 if ((n = socket_fd_read(fd, bp, n)) < 0)
680 return -1;
681 bp += n;
682 len -= n;
683 } while (! newline && len);
685 *bp = '\0';
686 return bp - buf;
690 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
692 if (socket_fd_check_io(fd, G_IO_IN) < 0)
693 return -1;
695 return recv(fd, buf, len, flags);
699 static gint socket_fd_read(gint fd, gchar *buf, gint len)
701 if (socket_fd_check_io(fd, G_IO_IN) < 0)
702 return -1;
704 #ifdef G_OS_WIN32
705 return recv(fd, buf, len, 0);
706 #else
707 return read(fd, buf, len);
708 #endif
712 static gint socket_fd_check_io(gint fd, GIOCondition cond)
714 struct timeval timeout;
715 fd_set fds;
716 #ifdef G_OS_UNIX
717 gint flags;
718 #endif
720 timeout.tv_sec = 60;
721 timeout.tv_usec = 0;
723 #ifdef G_OS_UNIX
724 /* checking for non-blocking mode */
725 flags = fcntl(fd, F_GETFL, 0);
726 if (flags < 0)
728 perror("fcntl");
729 return 0;
731 if ((flags & O_NONBLOCK) != 0)
732 return 0;
733 #endif
735 FD_ZERO(&fds);
736 FD_SET(fd, &fds);
738 if (cond == G_IO_IN)
740 select(fd + 1, &fds, NULL, NULL, &timeout);
742 else
744 select(fd + 1, NULL, &fds, NULL, &timeout);
747 if (FD_ISSET(fd, &fds))
749 return 0;
751 else
753 geany_debug("Socket IO timeout");
754 return -1;
759 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
761 gint n, wrlen = 0;
763 while (len)
765 n = socket_fd_write(fd, buf, len);
766 if (n <= 0)
767 return -1;
768 len -= n;
769 wrlen += n;
770 buf += n;
773 return wrlen;
777 gint socket_fd_write(gint fd, const gchar *buf, gint len)
779 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
780 return -1;
782 #ifdef G_OS_WIN32
783 return send(fd, buf, len, 0);
784 #else
785 return write(fd, buf, len);
786 #endif
790 #endif