Fix a few typos in NEWS
[geany-mirror.git] / src / socket.c
blob4a0d1dcf136a9fa771f164a5ff552ae2eb3f845d
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 "win32defines.h"
83 # include <winsock2.h>
84 # include <windows.h>
85 # include <gdk/gdkwin32.h>
86 # include <ws2tcpip.h>
87 #endif
88 #include <string.h>
89 #include <stdlib.h>
90 #include <unistd.h>
91 #include <fcntl.h>
93 #ifdef GDK_WINDOWING_X11
94 #include <gdk/gdkx.h>
95 #endif
98 #ifdef G_OS_WIN32
99 #define REMOTE_CMD_PORT 49876
100 #define SOCKET_IS_VALID(s) ((s) != INVALID_SOCKET)
101 #else
102 #define SOCKET_IS_VALID(s) ((s) >= 0)
103 #define INVALID_SOCKET (-1)
104 #endif
105 #define BUFFER_LENGTH 4096
107 struct socket_info_struct socket_info;
110 #ifdef G_OS_WIN32
111 static gint socket_fd_connect_inet (gushort port);
112 static gint socket_fd_open_inet (gushort port);
113 static void socket_init_win32 (void);
114 #else
115 static gint socket_fd_connect_unix (const gchar *path);
116 static gint socket_fd_open_unix (const gchar *path);
117 #endif
119 static gint socket_fd_write (gint sock, const gchar *buf, gint len);
120 static gint socket_fd_write_all (gint sock, const gchar *buf, gint len);
121 static gint socket_fd_gets (gint sock, gchar *buf, gint len);
122 static gint socket_fd_check_io (gint fd, GIOCondition cond);
123 static gint socket_fd_read (gint sock, gchar *buf, gint len);
124 static gint socket_fd_recv (gint fd, gchar *buf, gint len, gint flags);
125 static gint socket_fd_close (gint sock);
129 static void send_open_command(gint sock, gint argc, gchar **argv)
131 gint i;
132 gchar *filename;
134 g_return_if_fail(argc > 1);
135 geany_debug("using running instance of Geany");
137 if (cl_options.goto_line >= 0)
139 gchar *line = g_strdup_printf("%d\n", cl_options.goto_line);
140 socket_fd_write_all(sock, "line\n", 5);
141 socket_fd_write_all(sock, line, strlen(line));
142 socket_fd_write_all(sock, ".\n", 2);
143 g_free(line);
146 if (cl_options.goto_column >= 0)
148 gchar *col = g_strdup_printf("%d\n", cl_options.goto_column);
149 socket_fd_write_all(sock, "column\n", 7);
150 socket_fd_write_all(sock, col, strlen(col));
151 socket_fd_write_all(sock, ".\n", 2);
152 g_free(col);
155 if (cl_options.readonly) /* append "ro" to denote readonly status for new docs */
156 socket_fd_write_all(sock, "openro\n", 7);
157 else
158 socket_fd_write_all(sock, "open\n", 5);
160 for (i = 1; i < argc && argv[i] != NULL; i++)
162 filename = main_get_argv_filename(argv[i]);
164 /* if the filename is valid or if a new file should be opened is check on the other side */
165 if (filename != NULL)
167 socket_fd_write_all(sock, filename, strlen(filename));
168 socket_fd_write_all(sock, "\n", 1);
170 else
172 g_printerr(_("Could not find file '%s'."), filename);
173 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
175 g_free(filename);
177 socket_fd_write_all(sock, ".\n", 2);
181 #ifndef G_OS_WIN32
182 static void remove_socket_link_full(void)
184 gchar real_path[512];
185 gsize len;
187 real_path[0] = '\0';
189 /* read the contents of the symbolic link socket_info.file_name and delete it
190 * readlink should return something like "/tmp/geany_socket.499602d2" */
191 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
192 if ((gint) len > 0)
194 real_path[len] = '\0';
195 g_unlink(real_path);
197 g_unlink(socket_info.file_name);
199 #endif
202 static void socket_get_document_list(gint sock)
204 gchar buf[BUFFER_LENGTH];
205 gint n_read;
207 if (sock < 0)
208 return;
210 socket_fd_write_all(sock, "doclist\n", 8);
214 n_read = socket_fd_read(sock, buf, BUFFER_LENGTH);
215 /* if we received ETX (end-of-text), there is nothing else to read, so cut that
216 * byte not to output it and to be sure not to validate the loop condition */
217 if (n_read > 0 && buf[n_read - 1] == '\3')
218 n_read--;
219 if (n_read > 0)
220 fwrite(buf, 1, n_read, stdout);
222 while (n_read >= BUFFER_LENGTH);
226 #ifndef G_OS_WIN32
227 static void check_socket_permissions(void)
229 struct stat socket_stat;
231 if (g_lstat(socket_info.file_name, &socket_stat) == 0)
232 { /* If the user id of the process is not the same as the owner of the socket
233 * file, then ignore this socket and start a new session. */
234 if (socket_stat.st_uid != getuid())
236 const gchar *msg = _(
237 /* TODO maybe this message needs a rewording */
238 "Geany tried to access the Unix Domain socket of another instance running as another user.\n"
239 "This is a fatal error and Geany will now quit.");
240 g_warning("%s", msg);
241 dialogs_show_msgbox(GTK_MESSAGE_ERROR, "%s", msg);
242 exit(1);
246 #endif
249 /* (Unix domain) socket support to replace the old FIFO code
250 * (taken from Sylpheed, thanks)
251 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
252 * were sent to it. */
253 gint socket_init(gint argc, gchar **argv)
255 gint sock;
256 #ifdef G_OS_WIN32
257 HANDLE hmutex;
258 HWND hwnd;
259 socket_init_win32();
260 hmutex = CreateMutexA(NULL, FALSE, "Geany");
261 if (! hmutex)
263 geany_debug("cannot create Mutex\n");
264 return -1;
266 if (GetLastError() != ERROR_ALREADY_EXISTS)
268 /* To support multiple instances with different configuration directories (as we do on
269 * non-Windows systems) we would need to use different port number s but it might be
270 * difficult to get a port number which is unique for a configuration directory (path)
271 * and which is unused. This port number has to be guessed by the first and new instance
272 * and the only data is the configuration directory path.
273 * For now we use one port number, that is we support only one instance at all. */
274 sock = socket_fd_open_inet(REMOTE_CMD_PORT);
275 if (sock < 0)
276 return 0;
277 return sock;
280 sock = socket_fd_connect_inet(REMOTE_CMD_PORT);
281 if (sock < 0)
282 return -1;
283 #else
284 gchar *display_name = NULL;
285 const gchar *hostname = g_get_host_name();
286 GdkDisplay *display = gdk_display_get_default();
287 gchar *p;
289 if (display != NULL)
290 display_name = g_strdup(gdk_display_get_name(display));
291 if (display_name == NULL)
292 display_name = g_strdup("NODISPLAY");
294 /* these lines are taken from dcopc.c in kdelibs */
295 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
296 *p = '\0';
297 /* remove characters that may not be acceptable in a filename */
298 for (p = display_name; *p; p++)
300 if (*p == ':' || *p == '/')
301 *p = '_';
304 if (socket_info.file_name == NULL)
305 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
306 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
308 g_free(display_name);
310 /* check whether the real user id is the same as this of the socket file */
311 check_socket_permissions();
313 sock = socket_fd_connect_unix(socket_info.file_name);
314 if (sock < 0)
316 remove_socket_link_full(); /* deletes the socket file and the symlink */
317 return socket_fd_open_unix(socket_info.file_name);
319 #endif
321 /* remote command mode, here we have another running instance and want to use it */
323 #ifdef G_OS_WIN32
324 /* first we send a request to retrieve the window handle and focus the window */
325 socket_fd_write_all(sock, "window\n", 7);
326 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
327 SetForegroundWindow(hwnd);
328 #endif
329 /* now we send the command line args */
330 if (argc > 1)
332 send_open_command(sock, argc, argv);
335 if (cl_options.list_documents)
337 socket_get_document_list(sock);
340 socket_fd_close(sock);
341 return -2;
345 gint socket_finalize(void)
347 if (socket_info.lock_socket < 0)
348 return -1;
350 if (socket_info.lock_socket_tag > 0)
351 g_source_remove(socket_info.lock_socket_tag);
352 if (socket_info.read_ioc)
354 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
355 g_io_channel_unref(socket_info.read_ioc);
356 socket_info.read_ioc = NULL;
359 #ifdef G_OS_WIN32
360 WSACleanup();
361 #else
362 if (socket_info.file_name != NULL)
364 remove_socket_link_full(); /* deletes the socket file and the symlink */
365 g_free(socket_info.file_name);
367 #endif
369 return 0;
373 #ifdef G_OS_UNIX
374 static gint socket_fd_connect_unix(const gchar *path)
376 gint sock;
377 struct sockaddr_un addr;
379 sock = socket(PF_UNIX, SOCK_STREAM, 0);
380 if (sock < 0)
382 perror("fd_connect_unix(): socket");
383 return -1;
386 memset(&addr, 0, sizeof(addr));
387 addr.sun_family = AF_UNIX;
388 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
390 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
392 socket_fd_close(sock);
393 return -1;
396 return sock;
400 static gint socket_fd_open_unix(const gchar *path)
402 gint sock;
403 struct sockaddr_un addr;
404 gint val;
405 gchar *real_path;
407 sock = socket(PF_UNIX, SOCK_STREAM, 0);
409 if (sock < 0)
411 perror("sock_open_unix(): socket");
412 return -1;
415 val = 1;
416 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
418 perror("setsockopt");
419 socket_fd_close(sock);
420 return -1;
423 /* fix for #1888561:
424 * in case the configuration directory is located on a network file system or any other
425 * file system which doesn't support sockets, we just link the socket there and create the
426 * real socket in the system's tmp directory assuming it supports sockets */
427 real_path = g_strdup_printf("%s%cgeany_socket.%08x",
428 g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());
430 if (utils_is_file_writable(real_path) != 0)
431 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
432 /* instead of creating a symlink and print a warning */
433 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
434 SETPTR(real_path, g_strdup(path));
436 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
437 else if (symlink(real_path, path) != 0)
439 perror("symlink");
440 socket_fd_close(sock);
441 return -1;
444 memset(&addr, 0, sizeof(addr));
445 addr.sun_family = AF_UNIX;
446 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
448 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
450 perror("bind");
451 socket_fd_close(sock);
452 return -1;
455 if (listen(sock, 1) < 0)
457 perror("listen");
458 socket_fd_close(sock);
459 return -1;
462 g_chmod(real_path, 0600);
464 g_free(real_path);
466 return sock;
468 #endif
470 static gint socket_fd_close(gint fd)
472 #ifdef G_OS_WIN32
473 return closesocket(fd);
474 #else
475 return close(fd);
476 #endif
480 #ifdef G_OS_WIN32
481 static gint socket_fd_open_inet(gushort port)
483 SOCKET sock;
484 struct sockaddr_in addr;
485 gchar val;
487 sock = socket(AF_INET, SOCK_STREAM, 0);
488 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
490 geany_debug("fd_open_inet(): socket() failed: %d\n", WSAGetLastError());
491 return -1;
494 val = 1;
495 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
497 perror("setsockopt");
498 socket_fd_close(sock);
499 return -1;
502 memset(&addr, 0, sizeof(addr));
503 addr.sin_family = AF_INET;
504 addr.sin_port = htons(port);
505 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
507 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
509 perror("bind");
510 socket_fd_close(sock);
511 return -1;
514 if (listen(sock, 1) < 0)
516 perror("listen");
517 socket_fd_close(sock);
518 return -1;
521 return sock;
525 static gint socket_fd_connect_inet(gushort port)
527 SOCKET sock;
528 struct sockaddr_in addr;
530 sock = socket(AF_INET, SOCK_STREAM, 0);
531 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
533 geany_debug("fd_connect_inet(): socket() failed: %d\n", WSAGetLastError());
534 return -1;
537 memset(&addr, 0, sizeof(addr));
538 addr.sin_family = AF_INET;
539 addr.sin_port = htons(port);
540 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
542 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
544 socket_fd_close(sock);
545 return -1;
548 return sock;
552 static void socket_init_win32(void)
554 WSADATA wsadata;
556 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
557 geany_debug("WSAStartup() failed\n");
559 return;
561 #endif
564 static void handle_input_filename(const gchar *buf)
566 gchar *utf8_filename, *locale_filename;
568 /* we never know how the input is encoded, so do the best auto detection we can */
569 if (! g_utf8_validate(buf, -1, NULL))
570 utf8_filename = encodings_convert_to_utf8(buf, -1, NULL);
571 else
572 utf8_filename = g_strdup(buf);
574 locale_filename = utils_get_locale_from_utf8(utf8_filename);
575 if (locale_filename)
577 if (g_str_has_suffix(locale_filename, ".geany"))
579 if (project_ask_close())
580 main_load_project_from_command_line(locale_filename, TRUE);
582 else
583 main_handle_filename(locale_filename);
585 g_free(utf8_filename);
586 g_free(locale_filename);
590 static gchar *build_document_list(void)
592 GString *doc_list = g_string_new(NULL);
593 guint i;
594 const gchar *filename;
596 foreach_document(i)
598 filename = DOC_FILENAME(documents[i]);
599 g_string_append(doc_list, filename);
600 g_string_append_c(doc_list, '\n');
602 return g_string_free(doc_list, FALSE);
606 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
608 gint fd, sock;
609 gchar buf[BUFFER_LENGTH];
610 struct sockaddr_in caddr;
611 socklen_t caddr_len = sizeof(caddr);
612 GtkWidget *window = data;
613 gboolean popup = FALSE;
615 fd = g_io_channel_unix_get_fd(source);
616 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
618 /* first get the command */
619 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
621 if (strncmp(buf, "open", 4) == 0)
623 cl_options.readonly = strncmp(buf+4, "ro", 2) == 0; /* open in readonly? */
624 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
626 gsize buf_len = strlen(buf);
628 /* remove trailing newline */
629 if (buf_len > 0 && buf[buf_len - 1] == '\n')
630 buf[buf_len - 1] = '\0';
632 handle_input_filename(buf);
634 popup = TRUE;
636 else if (strncmp(buf, "doclist", 7) == 0)
638 gchar *doc_list = build_document_list();
639 if (!EMPTY(doc_list))
640 socket_fd_write_all(sock, doc_list, strlen(doc_list));
641 /* send ETX (end-of-text) so reader knows to stop reading */
642 socket_fd_write_all(sock, "\3", 1);
643 g_free(doc_list);
645 else if (strncmp(buf, "line", 4) == 0)
647 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
649 g_strstrip(buf); /* remove \n char */
650 /* on any error we get 0 which should be safe enough as fallback */
651 cl_options.goto_line = atoi(buf);
654 else if (strncmp(buf, "column", 6) == 0)
656 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
658 g_strstrip(buf); /* remove \n char */
659 /* on any error we get 0 which should be safe enough as fallback */
660 cl_options.goto_column = atoi(buf);
663 #ifdef G_OS_WIN32
664 else if (strncmp(buf, "window", 6) == 0)
666 # if GTK_CHECK_VERSION(3, 0, 0)
667 HWND hwnd = (HWND) gdk_win32_window_get_handle(gtk_widget_get_window(window));
668 # else
669 HWND hwnd = (HWND) gdk_win32_drawable_get_handle(
670 GDK_DRAWABLE(gtk_widget_get_window(window)));
671 # endif
672 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
674 #endif
677 if (popup)
679 #ifdef GDK_WINDOWING_X11
680 GdkWindow *x11_window = gtk_widget_get_window(window);
682 /* Set the proper interaction time on the window. This seems necessary to make
683 * gtk_window_present() really bring the main window into the foreground on some
684 * window managers like Gnome's metacity.
685 * Code taken from Gedit. */
686 # if GTK_CHECK_VERSION(3, 0, 0)
687 if (GDK_IS_X11_WINDOW(x11_window))
688 # endif
690 gdk_x11_window_set_user_time(x11_window, gdk_x11_get_server_time(x11_window));
692 #endif
693 gtk_window_present(GTK_WINDOW(window));
694 #ifdef G_OS_WIN32
695 gdk_window_show(gtk_widget_get_window(window));
696 #endif
699 socket_fd_close(sock);
701 return TRUE;
705 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
707 gchar *newline, *bp = buf;
708 gint n;
710 if (--len < 1)
711 return -1;
714 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
715 return -1;
716 if ((newline = memchr(bp, '\n', n)) != NULL)
717 n = newline - bp + 1;
718 if ((n = socket_fd_read(fd, bp, n)) < 0)
719 return -1;
720 bp += n;
721 len -= n;
722 } while (! newline && len);
724 *bp = '\0';
725 return bp - buf;
729 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
731 if (socket_fd_check_io(fd, G_IO_IN) < 0)
732 return -1;
734 return recv(fd, buf, len, flags);
738 static gint socket_fd_read(gint fd, gchar *buf, gint len)
740 if (socket_fd_check_io(fd, G_IO_IN) < 0)
741 return -1;
743 #ifdef G_OS_WIN32
744 return recv(fd, buf, len, 0);
745 #else
746 return read(fd, buf, len);
747 #endif
751 static gint socket_fd_check_io(gint fd, GIOCondition cond)
753 struct timeval timeout;
754 fd_set fds;
755 #ifdef G_OS_UNIX
756 gint flags;
757 #endif
759 timeout.tv_sec = 60;
760 timeout.tv_usec = 0;
762 #ifdef G_OS_UNIX
763 /* checking for non-blocking mode */
764 flags = fcntl(fd, F_GETFL, 0);
765 if (flags < 0)
767 perror("fcntl");
768 return 0;
770 if ((flags & O_NONBLOCK) != 0)
771 return 0;
772 #endif
774 FD_ZERO(&fds);
775 #ifdef G_OS_WIN32
776 FD_SET((SOCKET)fd, &fds);
777 #else
778 FD_SET(fd, &fds);
779 #endif
781 if (cond == G_IO_IN)
783 select(fd + 1, &fds, NULL, NULL, &timeout);
785 else
787 select(fd + 1, NULL, &fds, NULL, &timeout);
790 if (FD_ISSET(fd, &fds))
792 return 0;
794 else
796 geany_debug("Socket IO timeout");
797 return -1;
802 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
804 gint n, wrlen = 0;
806 while (len)
808 n = socket_fd_write(fd, buf, len);
809 if (n <= 0)
810 return -1;
811 len -= n;
812 wrlen += n;
813 buf += n;
816 return wrlen;
820 gint socket_fd_write(gint fd, const gchar *buf, gint len)
822 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
823 return -1;
825 #ifdef G_OS_WIN32
826 return send(fd, buf, len, 0);
827 #else
828 return write(fd, buf, len);
829 #endif
833 #endif