Avoid gdk_display_get_name() on OS X
[geany-mirror.git] / src / socket.c
blob2bd6c1d0955be0feceb7b846e27be2ecf76224b6
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 SocketInfo 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;
132 g_return_if_fail(argc > 1);
133 geany_debug("using running instance of Geany");
135 if (cl_options.goto_line >= 0)
137 gchar *line = g_strdup_printf("%d\n", cl_options.goto_line);
138 socket_fd_write_all(sock, "line\n", 5);
139 socket_fd_write_all(sock, line, strlen(line));
140 socket_fd_write_all(sock, ".\n", 2);
141 g_free(line);
144 if (cl_options.goto_column >= 0)
146 gchar *col = g_strdup_printf("%d\n", cl_options.goto_column);
147 socket_fd_write_all(sock, "column\n", 7);
148 socket_fd_write_all(sock, col, strlen(col));
149 socket_fd_write_all(sock, ".\n", 2);
150 g_free(col);
153 if (cl_options.readonly) /* append "ro" to denote readonly status for new docs */
154 socket_fd_write_all(sock, "openro\n", 7);
155 else
156 socket_fd_write_all(sock, "open\n", 5);
158 for (i = 1; i < argc && argv[i] != NULL; i++)
160 gchar *filename = main_get_argv_filename(argv[i]);
162 /* if the filename is valid or if a new file should be opened is check on the other side */
163 if (filename != NULL)
165 socket_fd_write_all(sock, filename, strlen(filename));
166 socket_fd_write_all(sock, "\n", 1);
168 else
170 g_printerr(_("Could not find file '%s'."), filename);
171 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
173 g_free(filename);
175 socket_fd_write_all(sock, ".\n", 2);
179 #ifndef G_OS_WIN32
180 static void remove_socket_link_full(void)
182 gchar real_path[512];
183 gsize len;
185 real_path[0] = '\0';
187 /* read the contents of the symbolic link socket_info.file_name and delete it
188 * readlink should return something like "/tmp/geany_socket.499602d2" */
189 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
190 if ((gint) len > 0)
192 real_path[len] = '\0';
193 g_unlink(real_path);
195 g_unlink(socket_info.file_name);
197 #endif
200 static void socket_get_document_list(gint sock)
202 gchar buf[BUFFER_LENGTH];
203 gint n_read;
205 if (sock < 0)
206 return;
208 socket_fd_write_all(sock, "doclist\n", 8);
212 n_read = socket_fd_read(sock, buf, BUFFER_LENGTH);
213 /* if we received ETX (end-of-text), there is nothing else to read, so cut that
214 * byte not to output it and to be sure not to validate the loop condition */
215 if (n_read > 0 && buf[n_read - 1] == '\3')
216 n_read--;
217 if (n_read > 0)
218 fwrite(buf, 1, n_read, stdout);
220 while (n_read >= BUFFER_LENGTH);
224 #ifndef G_OS_WIN32
225 static void check_socket_permissions(void)
227 GStatBuf socket_stat;
229 if (g_lstat(socket_info.file_name, &socket_stat) == 0)
230 { /* If the user id of the process is not the same as the owner of the socket
231 * file, then ignore this socket and start a new session. */
232 if (socket_stat.st_uid != getuid())
234 const gchar *msg = _(
235 /* TODO maybe this message needs a rewording */
236 "Geany tried to access the Unix Domain socket of another instance running as another user.\n"
237 "This is a fatal error and Geany will now quit.");
238 g_warning("%s", msg);
239 dialogs_show_msgbox(GTK_MESSAGE_ERROR, "%s", msg);
240 exit(1);
244 #endif
247 /* (Unix domain) socket support to replace the old FIFO code
248 * (taken from Sylpheed, thanks)
249 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
250 * were sent to it. */
251 gint socket_init(gint argc, gchar **argv)
253 gint sock;
254 #ifdef G_OS_WIN32
255 HANDLE hmutex;
256 HWND hwnd;
257 socket_init_win32();
258 hmutex = CreateMutexA(NULL, FALSE, "Geany");
259 if (! hmutex)
261 geany_debug("cannot create Mutex\n");
262 return -1;
264 if (GetLastError() != ERROR_ALREADY_EXISTS)
266 /* To support multiple instances with different configuration directories (as we do on
267 * non-Windows systems) we would need to use different port number s but it might be
268 * difficult to get a port number which is unique for a configuration directory (path)
269 * and which is unused. This port number has to be guessed by the first and new instance
270 * and the only data is the configuration directory path.
271 * For now we use one port number, that is we support only one instance at all. */
272 sock = socket_fd_open_inet(REMOTE_CMD_PORT);
273 if (sock < 0)
274 return 0;
275 return sock;
278 sock = socket_fd_connect_inet(REMOTE_CMD_PORT);
279 if (sock < 0)
280 return -1;
281 #else
282 gchar *display_name = NULL;
283 const gchar *hostname = g_get_host_name();
284 GdkDisplay *display = gdk_display_get_default();
285 gchar *p;
287 /* On OS X with quartz backend gdk_display_get_name() returns hostname
288 * using [NSHost currentHost] (it could return more or less whatever string
289 * as display name is a X11 specific thing). This call can lead to network
290 * query and block for several seconds so better skip it. */
291 #ifndef GDK_WINDOWING_QUARTZ
292 if (display != NULL)
293 display_name = g_strdup(gdk_display_get_name(display));
294 #endif
296 if (display_name == NULL)
297 display_name = g_strdup("NODISPLAY");
299 /* these lines are taken from dcopc.c in kdelibs */
300 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
301 *p = '\0';
302 /* remove characters that may not be acceptable in a filename */
303 for (p = display_name; *p; p++)
305 if (*p == ':' || *p == '/')
306 *p = '_';
309 if (socket_info.file_name == NULL)
310 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
311 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
313 g_free(display_name);
315 /* check whether the real user id is the same as this of the socket file */
316 check_socket_permissions();
318 sock = socket_fd_connect_unix(socket_info.file_name);
319 if (sock < 0)
321 remove_socket_link_full(); /* deletes the socket file and the symlink */
322 return socket_fd_open_unix(socket_info.file_name);
324 #endif
326 /* remote command mode, here we have another running instance and want to use it */
328 #ifdef G_OS_WIN32
329 /* first we send a request to retrieve the window handle and focus the window */
330 socket_fd_write_all(sock, "window\n", 7);
331 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
332 SetForegroundWindow(hwnd);
333 #endif
334 /* now we send the command line args */
335 if (argc > 1)
337 send_open_command(sock, argc, argv);
340 if (cl_options.list_documents)
342 socket_get_document_list(sock);
345 socket_fd_close(sock);
346 return -2;
350 gint socket_finalize(void)
352 if (socket_info.lock_socket < 0)
353 return -1;
355 if (socket_info.lock_socket_tag > 0)
356 g_source_remove(socket_info.lock_socket_tag);
357 if (socket_info.read_ioc)
359 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
360 g_io_channel_unref(socket_info.read_ioc);
361 socket_info.read_ioc = NULL;
364 #ifdef G_OS_WIN32
365 WSACleanup();
366 #else
367 if (socket_info.file_name != NULL)
369 remove_socket_link_full(); /* deletes the socket file and the symlink */
370 g_free(socket_info.file_name);
372 #endif
374 return 0;
378 #ifdef G_OS_UNIX
379 static gint socket_fd_connect_unix(const gchar *path)
381 gint sock;
382 struct sockaddr_un addr;
384 sock = socket(PF_UNIX, SOCK_STREAM, 0);
385 if (sock < 0)
387 perror("fd_connect_unix(): socket");
388 return -1;
391 memset(&addr, 0, sizeof(addr));
392 addr.sun_family = AF_UNIX;
393 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
395 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
397 socket_fd_close(sock);
398 return -1;
401 return sock;
405 static gint socket_fd_open_unix(const gchar *path)
407 gint sock;
408 struct sockaddr_un addr;
409 gint val;
410 gchar *real_path;
412 sock = socket(PF_UNIX, SOCK_STREAM, 0);
414 if (sock < 0)
416 perror("sock_open_unix(): socket");
417 return -1;
420 val = 1;
421 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
423 perror("setsockopt");
424 socket_fd_close(sock);
425 return -1;
428 /* fix for #1888561:
429 * in case the configuration directory is located on a network file system or any other
430 * file system which doesn't support sockets, we just link the socket there and create the
431 * real socket in the system's tmp directory assuming it supports sockets */
432 real_path = g_strdup_printf("%s%cgeany_socket.%08x",
433 g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());
435 if (utils_is_file_writable(real_path) != 0)
436 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
437 /* instead of creating a symlink and print a warning */
438 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
439 SETPTR(real_path, g_strdup(path));
441 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
442 else if (symlink(real_path, path) != 0)
444 perror("symlink");
445 socket_fd_close(sock);
446 return -1;
449 memset(&addr, 0, sizeof(addr));
450 addr.sun_family = AF_UNIX;
451 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
453 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
455 perror("bind");
456 socket_fd_close(sock);
457 return -1;
460 if (listen(sock, 1) < 0)
462 perror("listen");
463 socket_fd_close(sock);
464 return -1;
467 g_chmod(real_path, 0600);
469 g_free(real_path);
471 return sock;
473 #endif
475 static gint socket_fd_close(gint fd)
477 #ifdef G_OS_WIN32
478 return closesocket(fd);
479 #else
480 return close(fd);
481 #endif
485 #ifdef G_OS_WIN32
486 static gint socket_fd_open_inet(gushort port)
488 SOCKET sock;
489 struct sockaddr_in addr;
490 gchar val;
492 sock = socket(AF_INET, SOCK_STREAM, 0);
493 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
495 geany_debug("fd_open_inet(): socket() failed: %d\n", WSAGetLastError());
496 return -1;
499 val = 1;
500 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
502 perror("setsockopt");
503 socket_fd_close(sock);
504 return -1;
507 memset(&addr, 0, sizeof(addr));
508 addr.sin_family = AF_INET;
509 addr.sin_port = htons(port);
510 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
512 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
514 perror("bind");
515 socket_fd_close(sock);
516 return -1;
519 if (listen(sock, 1) < 0)
521 perror("listen");
522 socket_fd_close(sock);
523 return -1;
526 return sock;
530 static gint socket_fd_connect_inet(gushort port)
532 SOCKET sock;
533 struct sockaddr_in addr;
535 sock = socket(AF_INET, SOCK_STREAM, 0);
536 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
538 geany_debug("fd_connect_inet(): socket() failed: %d\n", WSAGetLastError());
539 return -1;
542 memset(&addr, 0, sizeof(addr));
543 addr.sin_family = AF_INET;
544 addr.sin_port = htons(port);
545 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
547 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
549 socket_fd_close(sock);
550 return -1;
553 return sock;
557 static void socket_init_win32(void)
559 WSADATA wsadata;
561 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
562 geany_debug("WSAStartup() failed\n");
564 return;
566 #endif
569 static void handle_input_filename(const gchar *buf)
571 gchar *utf8_filename, *locale_filename;
573 /* we never know how the input is encoded, so do the best auto detection we can */
574 if (! g_utf8_validate(buf, -1, NULL))
575 utf8_filename = encodings_convert_to_utf8(buf, -1, NULL);
576 else
577 utf8_filename = g_strdup(buf);
579 locale_filename = utils_get_locale_from_utf8(utf8_filename);
580 if (locale_filename)
582 if (g_str_has_suffix(locale_filename, ".geany"))
584 if (project_ask_close())
585 main_load_project_from_command_line(locale_filename, TRUE);
587 else
588 main_handle_filename(locale_filename);
590 g_free(utf8_filename);
591 g_free(locale_filename);
595 static gchar *build_document_list(void)
597 GString *doc_list = g_string_new(NULL);
598 guint i;
599 const gchar *filename;
601 foreach_document(i)
603 filename = DOC_FILENAME(documents[i]);
604 g_string_append(doc_list, filename);
605 g_string_append_c(doc_list, '\n');
607 return g_string_free(doc_list, FALSE);
611 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
613 gint fd, sock;
614 gchar buf[BUFFER_LENGTH];
615 struct sockaddr_in caddr;
616 socklen_t caddr_len = sizeof(caddr);
617 GtkWidget *window = data;
618 gboolean popup = FALSE;
620 fd = g_io_channel_unix_get_fd(source);
621 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
623 /* first get the command */
624 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
626 if (strncmp(buf, "open", 4) == 0)
628 cl_options.readonly = strncmp(buf+4, "ro", 2) == 0; /* open in readonly? */
629 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
631 gsize buf_len = strlen(buf);
633 /* remove trailing newline */
634 if (buf_len > 0 && buf[buf_len - 1] == '\n')
635 buf[buf_len - 1] = '\0';
637 handle_input_filename(buf);
639 popup = TRUE;
641 else if (strncmp(buf, "doclist", 7) == 0)
643 gchar *doc_list = build_document_list();
644 if (!EMPTY(doc_list))
645 socket_fd_write_all(sock, doc_list, strlen(doc_list));
646 /* send ETX (end-of-text) so reader knows to stop reading */
647 socket_fd_write_all(sock, "\3", 1);
648 g_free(doc_list);
650 else if (strncmp(buf, "line", 4) == 0)
652 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
654 g_strstrip(buf); /* remove \n char */
655 /* on any error we get 0 which should be safe enough as fallback */
656 cl_options.goto_line = atoi(buf);
659 else if (strncmp(buf, "column", 6) == 0)
661 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
663 g_strstrip(buf); /* remove \n char */
664 /* on any error we get 0 which should be safe enough as fallback */
665 cl_options.goto_column = atoi(buf);
668 #ifdef G_OS_WIN32
669 else if (strncmp(buf, "window", 6) == 0)
671 # if GTK_CHECK_VERSION(3, 0, 0)
672 HWND hwnd = (HWND) gdk_win32_window_get_handle(gtk_widget_get_window(window));
673 # else
674 HWND hwnd = (HWND) gdk_win32_drawable_get_handle(
675 GDK_DRAWABLE(gtk_widget_get_window(window)));
676 # endif
677 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
679 #endif
682 if (popup)
684 #ifdef GDK_WINDOWING_X11
685 GdkWindow *x11_window = gtk_widget_get_window(window);
687 /* Set the proper interaction time on the window. This seems necessary to make
688 * gtk_window_present() really bring the main window into the foreground on some
689 * window managers like Gnome's metacity.
690 * Code taken from Gedit. */
691 # if GTK_CHECK_VERSION(3, 0, 0)
692 if (GDK_IS_X11_WINDOW(x11_window))
693 # endif
695 gdk_x11_window_set_user_time(x11_window, gdk_x11_get_server_time(x11_window));
697 #endif
698 gtk_window_present(GTK_WINDOW(window));
699 #ifdef G_OS_WIN32
700 gdk_window_show(gtk_widget_get_window(window));
701 #endif
704 socket_fd_close(sock);
706 return TRUE;
710 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
712 gchar *newline, *bp = buf;
713 gint n;
715 if (--len < 1)
716 return -1;
719 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
720 return -1;
721 if ((newline = memchr(bp, '\n', n)) != NULL)
722 n = newline - bp + 1;
723 if ((n = socket_fd_read(fd, bp, n)) < 0)
724 return -1;
725 bp += n;
726 len -= n;
727 } while (! newline && len);
729 *bp = '\0';
730 return bp - buf;
734 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
736 if (socket_fd_check_io(fd, G_IO_IN) < 0)
737 return -1;
739 return recv(fd, buf, len, flags);
743 static gint socket_fd_read(gint fd, gchar *buf, gint len)
745 if (socket_fd_check_io(fd, G_IO_IN) < 0)
746 return -1;
748 #ifdef G_OS_WIN32
749 return recv(fd, buf, len, 0);
750 #else
751 return read(fd, buf, len);
752 #endif
756 static gint socket_fd_check_io(gint fd, GIOCondition cond)
758 struct timeval timeout;
759 fd_set fds;
760 #ifdef G_OS_UNIX
761 gint flags;
762 #endif
764 timeout.tv_sec = 60;
765 timeout.tv_usec = 0;
767 #ifdef G_OS_UNIX
768 /* checking for non-blocking mode */
769 flags = fcntl(fd, F_GETFL, 0);
770 if (flags < 0)
772 perror("fcntl");
773 return 0;
775 if ((flags & O_NONBLOCK) != 0)
776 return 0;
777 #endif
779 FD_ZERO(&fds);
780 #ifdef G_OS_WIN32
781 FD_SET((SOCKET)fd, &fds);
782 #else
783 FD_SET(fd, &fds);
784 #endif
786 if (cond == G_IO_IN)
788 select(fd + 1, &fds, NULL, NULL, &timeout);
790 else
792 select(fd + 1, NULL, &fds, NULL, &timeout);
795 if (FD_ISSET(fd, &fds))
797 return 0;
799 else
801 geany_debug("Socket IO timeout");
802 return -1;
807 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
809 gint n, wrlen = 0;
811 while (len)
813 n = socket_fd_write(fd, buf, len);
814 if (n <= 0)
815 return -1;
816 len -= n;
817 wrlen += n;
818 buf += n;
821 return wrlen;
825 gint socket_fd_write(gint fd, const gchar *buf, gint len)
827 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
828 return -1;
830 #ifdef G_OS_WIN32
831 return send(fd, buf, len, 0);
832 #else
833 return write(fd, buf, len);
834 #endif
838 #endif