Print filename of failed plugin
[geany-mirror.git] / src / socket.c
blob3691ac455ad5d44f6efbe7c499d45ca523d072e2
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.
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"
89 #include "project.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 if (cl_options.readonly) /* append "ro" to denote readonly status for new docs */
150 socket_fd_write_all(sock, "openro\n", 7);
151 else
152 socket_fd_write_all(sock, "open\n", 5);
154 for (i = 1; i < argc && argv[i] != NULL; i++)
156 filename = main_get_argv_filename(argv[i]);
158 /* if the filename is valid or if a new file should be opened is check on the other side */
159 if (filename != NULL)
161 socket_fd_write_all(sock, filename, strlen(filename));
162 socket_fd_write_all(sock, "\n", 1);
164 else
166 g_printerr(_("Could not find file '%s'."), filename);
167 g_printerr("\n"); /* keep translation from open_cl_files() in main.c. */
169 g_free(filename);
171 socket_fd_write_all(sock, ".\n", 2);
175 #ifndef G_OS_WIN32
176 static void remove_socket_link_full(void)
178 gchar real_path[512];
179 gsize len;
181 real_path[0] = '\0';
183 /* read the contents of the symbolic link socket_info.file_name and delete it
184 * readlink should return something like "/tmp/geany_socket.499602d2" */
185 len = readlink(socket_info.file_name, real_path, sizeof(real_path) - 1);
186 if ((gint) len > 0)
188 real_path[len] = '\0';
189 g_unlink(real_path);
191 g_unlink(socket_info.file_name);
193 #endif
196 static void socket_get_document_list(gint sock)
198 gchar doc_list[BUFFER_LENGTH];
199 gint doc_list_len;
201 if (sock < 0)
202 return;
204 socket_fd_write_all(sock, "doclist\n", 8);
206 doc_list_len = socket_fd_read(sock, doc_list, sizeof(doc_list));
207 if (doc_list_len >= BUFFER_LENGTH)
208 doc_list_len = BUFFER_LENGTH -1;
209 doc_list[doc_list_len] = '\0';
210 /* if we received ETX (end-of-text), there were no open files, so print only otherwise */
211 if (! utils_str_equal(doc_list, "\3"))
212 printf("%s", doc_list);
216 #ifndef G_OS_WIN32
217 static void check_socket_permissions(void)
219 struct stat socket_stat;
221 if (g_lstat(socket_info.file_name, &socket_stat) == 0)
222 { /* If the user id of the process is not the same as the owner of the socket
223 * file, then ignore this socket and start a new session. */
224 if (socket_stat.st_uid != getuid())
226 const gchar *msg = _(
227 /* TODO maybe this message needs a rewording */
228 "Geany tried to access the Unix Domain socket of another instance running as another user.\n"
229 "This is a fatal error and Geany will now quit.");
230 g_warning("%s", msg);
231 dialogs_show_msgbox(GTK_MESSAGE_ERROR, "%s", msg);
232 exit(1);
236 #endif
239 /* (Unix domain) socket support to replace the old FIFO code
240 * (taken from Sylpheed, thanks)
241 * Returns the created socket, -1 if an error occurred or -2 if another socket exists and files
242 * were sent to it. */
243 gint socket_init(gint argc, gchar **argv)
245 gint sock;
246 #ifdef G_OS_WIN32
247 HANDLE hmutex;
248 HWND hwnd;
249 socket_init_win32();
250 hmutex = CreateMutexA(NULL, FALSE, "Geany");
251 if (! hmutex)
253 geany_debug("cannot create Mutex\n");
254 return -1;
256 if (GetLastError() != ERROR_ALREADY_EXISTS)
258 /* To support multiple instances with different configuration directories (as we do on
259 * non-Windows systems) we would need to use different port number s but it might be
260 * difficult to get a port number which is unique for a configuration directory (path)
261 * and which is unused. This port number has to be guessed by the first and new instance
262 * and the only data is the configuration directory path.
263 * For now we use one port number, that is we support only one instance at all. */
264 sock = socket_fd_open_inet(REMOTE_CMD_PORT);
265 if (sock < 0)
266 return 0;
267 return sock;
270 sock = socket_fd_connect_inet(REMOTE_CMD_PORT);
271 if (sock < 0)
272 return -1;
273 #else
274 gchar *display_name = gdk_get_display();
275 gchar *hostname = utils_get_hostname();
276 gchar *p;
278 if (display_name == NULL)
279 display_name = g_strdup("NODISPLAY");
281 /* these lines are taken from dcopc.c in kdelibs */
282 if ((p = strrchr(display_name, '.')) > strrchr(display_name, ':') && p != NULL)
283 *p = '\0';
284 /* remove characters that may not be acceptable in a filename */
285 for (p = display_name; *p; p++)
287 if (*p == ':' || *p == '/')
288 *p = '_';
291 if (socket_info.file_name == NULL)
292 socket_info.file_name = g_strdup_printf("%s%cgeany_socket_%s_%s",
293 app->configdir, G_DIR_SEPARATOR, hostname, display_name);
295 g_free(display_name);
296 g_free(hostname);
298 /* check whether the real user id is the same as this of the socket file */
299 check_socket_permissions();
301 sock = socket_fd_connect_unix(socket_info.file_name);
302 if (sock < 0)
304 remove_socket_link_full(); /* deletes the socket file and the symlink */
305 return socket_fd_open_unix(socket_info.file_name);
307 #endif
309 /* remote command mode, here we have another running instance and want to use it */
311 #ifdef G_OS_WIN32
312 /* first we send a request to retrieve the window handle and focus the window */
313 socket_fd_write_all(sock, "window\n", 7);
314 if (socket_fd_read(sock, (gchar *)&hwnd, sizeof(hwnd)) == sizeof(hwnd))
315 SetForegroundWindow(hwnd);
316 #endif
317 /* now we send the command line args */
318 if (argc > 1)
320 send_open_command(sock, argc, argv);
323 if (cl_options.list_documents)
325 socket_get_document_list(sock);
328 socket_fd_close(sock);
329 return -2;
333 gint socket_finalize(void)
335 if (socket_info.lock_socket < 0)
336 return -1;
338 if (socket_info.lock_socket_tag > 0)
339 g_source_remove(socket_info.lock_socket_tag);
340 if (socket_info.read_ioc)
342 g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL);
343 g_io_channel_unref(socket_info.read_ioc);
344 socket_info.read_ioc = NULL;
347 #ifdef G_OS_WIN32
348 WSACleanup();
349 #else
350 if (socket_info.file_name != NULL)
352 remove_socket_link_full(); /* deletes the socket file and the symlink */
353 g_free(socket_info.file_name);
355 #endif
357 return 0;
361 #ifdef G_OS_UNIX
362 static gint socket_fd_connect_unix(const gchar *path)
364 gint sock;
365 struct sockaddr_un addr;
367 sock = socket(PF_UNIX, SOCK_STREAM, 0);
368 if (sock < 0)
370 perror("fd_connect_unix(): socket");
371 return -1;
374 memset(&addr, 0, sizeof(addr));
375 addr.sun_family = AF_UNIX;
376 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
378 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
380 socket_fd_close(sock);
381 return -1;
384 return sock;
388 static gint socket_fd_open_unix(const gchar *path)
390 gint sock;
391 struct sockaddr_un addr;
392 gint val;
393 gchar *real_path;
395 sock = socket(PF_UNIX, SOCK_STREAM, 0);
397 if (sock < 0)
399 perror("sock_open_unix(): socket");
400 return -1;
403 val = 1;
404 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
406 perror("setsockopt");
407 socket_fd_close(sock);
408 return -1;
411 /* fix for #1888561:
412 * in case the configuration directory is located on a network file system or any other
413 * file system which doesn't support sockets, we just link the socket there and create the
414 * real socket in the system's tmp directory assuming it supports sockets */
415 real_path = g_strdup_printf("%s%cgeany_socket.%08x",
416 g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());
418 if (utils_is_file_writable(real_path) != 0)
419 { /* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
420 /* instead of creating a symlink and print a warning */
421 g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
422 SETPTR(real_path, g_strdup(path));
424 /* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
425 else if (symlink(real_path, path) != 0)
427 perror("symlink");
428 socket_fd_close(sock);
429 return -1;
432 memset(&addr, 0, sizeof(addr));
433 addr.sun_family = AF_UNIX;
434 strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);
436 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
438 perror("bind");
439 socket_fd_close(sock);
440 return -1;
443 if (listen(sock, 1) < 0)
445 perror("listen");
446 socket_fd_close(sock);
447 return -1;
450 g_chmod(real_path, 0600);
452 g_free(real_path);
454 return sock;
456 #endif
458 static gint socket_fd_close(gint fd)
460 #ifdef G_OS_WIN32
461 return closesocket(fd);
462 #else
463 return close(fd);
464 #endif
468 #ifdef G_OS_WIN32
469 static gint socket_fd_open_inet(gushort port)
471 SOCKET sock;
472 struct sockaddr_in addr;
473 gchar val;
475 sock = socket(AF_INET, SOCK_STREAM, 0);
476 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
478 geany_debug("fd_open_inet(): socket() failed: %d\n", WSAGetLastError());
479 return -1;
482 val = 1;
483 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
485 perror("setsockopt");
486 socket_fd_close(sock);
487 return -1;
490 memset(&addr, 0, sizeof(addr));
491 addr.sin_family = AF_INET;
492 addr.sin_port = htons(port);
493 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
495 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
497 perror("bind");
498 socket_fd_close(sock);
499 return -1;
502 if (listen(sock, 1) < 0)
504 perror("listen");
505 socket_fd_close(sock);
506 return -1;
509 return sock;
513 static gint socket_fd_connect_inet(gushort port)
515 SOCKET sock;
516 struct sockaddr_in addr;
518 sock = socket(AF_INET, SOCK_STREAM, 0);
519 if (G_UNLIKELY(! SOCKET_IS_VALID(sock)))
521 geany_debug("fd_connect_inet(): socket() failed: %d\n", WSAGetLastError());
522 return -1;
525 memset(&addr, 0, sizeof(addr));
526 addr.sin_family = AF_INET;
527 addr.sin_port = htons(port);
528 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
530 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
532 socket_fd_close(sock);
533 return -1;
536 return sock;
540 static void socket_init_win32(void)
542 WSADATA wsadata;
544 if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
545 geany_debug("WSAStartup() failed\n");
547 return;
549 #endif
552 static void handle_input_filename(const gchar *buf)
554 gchar *utf8_filename, *locale_filename;
556 /* we never know how the input is encoded, so do the best auto detection we can */
557 if (! g_utf8_validate(buf, -1, NULL))
558 utf8_filename = encodings_convert_to_utf8(buf, -1, NULL);
559 else
560 utf8_filename = g_strdup(buf);
562 locale_filename = utils_get_locale_from_utf8(utf8_filename);
563 if (locale_filename)
565 if (g_str_has_suffix(locale_filename, ".geany"))
567 if (project_ask_close())
568 main_load_project_from_command_line(locale_filename, TRUE);
570 else
571 main_handle_filename(locale_filename);
573 g_free(utf8_filename);
574 g_free(locale_filename);
578 static gchar *build_document_list(void)
580 GString *doc_list = g_string_new(NULL);
581 guint i;
582 const gchar *filename;
584 foreach_document(i)
586 filename = DOC_FILENAME(documents[i]);
587 g_string_append(doc_list, filename);
588 g_string_append_c(doc_list, '\n');
590 return g_string_free(doc_list, FALSE);
594 gboolean socket_lock_input_cb(GIOChannel *source, GIOCondition condition, gpointer data)
596 gint fd, sock;
597 gchar buf[BUFFER_LENGTH];
598 struct sockaddr_in caddr;
599 socklen_t caddr_len = sizeof(caddr);
600 GtkWidget *window = data;
601 gboolean popup = FALSE;
603 fd = g_io_channel_unix_get_fd(source);
604 sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len);
606 /* first get the command */
607 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1)
609 if (strncmp(buf, "open", 4) == 0)
611 cl_options.readonly = strncmp(buf+4, "ro", 2) == 0; /* open in readonly? */
612 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
614 gsize buf_len = strlen(buf);
616 /* remove trailing newline */
617 if (buf_len > 0 && buf[buf_len - 1] == '\n')
618 buf[buf_len - 1] = '\0';
620 handle_input_filename(buf);
622 popup = TRUE;
624 else if (strncmp(buf, "doclist", 7) == 0)
626 gchar *doc_list = build_document_list();
627 if (NZV(doc_list))
628 socket_fd_write_all(sock, doc_list, strlen(doc_list));
629 else
630 /* send ETX (end-of-text) in case we have no open files, we must send anything
631 * otherwise the client would hang on reading */
632 socket_fd_write_all(sock, "\3", 1);
633 g_free(doc_list);
635 else if (strncmp(buf, "line", 4) == 0)
637 while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.')
639 g_strstrip(buf); /* remove \n char */
640 /* on any error we get 0 which should be safe enough as fallback */
641 cl_options.goto_line = atoi(buf);
644 else if (strncmp(buf, "column", 6) == 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_column = atoi(buf);
653 #ifdef G_OS_WIN32
654 else if (strncmp(buf, "window", 6) == 0)
656 HWND hwnd = (HWND) gdk_win32_drawable_get_handle(
657 GDK_DRAWABLE(gtk_widget_get_window(window)));
658 socket_fd_write(sock, (gchar *)&hwnd, sizeof(hwnd));
660 #endif
663 if (popup)
665 #ifdef GDK_WINDOWING_X11
666 /* Set the proper interaction time on the window. This seems necessary to make
667 * gtk_window_present() really bring the main window into the foreground on some
668 * window managers like Gnome's metacity.
669 * Code taken from Gedit. */
670 gdk_x11_window_set_user_time(gtk_widget_get_window(window),
671 gdk_x11_get_server_time(gtk_widget_get_window(window)));
672 #endif
673 gtk_window_present(GTK_WINDOW(window));
674 #ifdef G_OS_WIN32
675 gdk_window_show(gtk_widget_get_window(window));
676 #endif
679 socket_fd_close(sock);
681 return TRUE;
685 static gint socket_fd_gets(gint fd, gchar *buf, gint len)
687 gchar *newline, *bp = buf;
688 gint n;
690 if (--len < 1)
691 return -1;
694 if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
695 return -1;
696 if ((newline = memchr(bp, '\n', n)) != NULL)
697 n = newline - bp + 1;
698 if ((n = socket_fd_read(fd, bp, n)) < 0)
699 return -1;
700 bp += n;
701 len -= n;
702 } while (! newline && len);
704 *bp = '\0';
705 return bp - buf;
709 static gint socket_fd_recv(gint fd, gchar *buf, gint len, gint flags)
711 if (socket_fd_check_io(fd, G_IO_IN) < 0)
712 return -1;
714 return recv(fd, buf, len, flags);
718 static gint socket_fd_read(gint fd, gchar *buf, gint len)
720 if (socket_fd_check_io(fd, G_IO_IN) < 0)
721 return -1;
723 #ifdef G_OS_WIN32
724 return recv(fd, buf, len, 0);
725 #else
726 return read(fd, buf, len);
727 #endif
731 static gint socket_fd_check_io(gint fd, GIOCondition cond)
733 struct timeval timeout;
734 fd_set fds;
735 #ifdef G_OS_UNIX
736 gint flags;
737 #endif
739 timeout.tv_sec = 60;
740 timeout.tv_usec = 0;
742 #ifdef G_OS_UNIX
743 /* checking for non-blocking mode */
744 flags = fcntl(fd, F_GETFL, 0);
745 if (flags < 0)
747 perror("fcntl");
748 return 0;
750 if ((flags & O_NONBLOCK) != 0)
751 return 0;
752 #endif
754 FD_ZERO(&fds);
755 FD_SET(fd, &fds);
757 if (cond == G_IO_IN)
759 select(fd + 1, &fds, NULL, NULL, &timeout);
761 else
763 select(fd + 1, NULL, &fds, NULL, &timeout);
766 if (FD_ISSET(fd, &fds))
768 return 0;
770 else
772 geany_debug("Socket IO timeout");
773 return -1;
778 static gint socket_fd_write_all(gint fd, const gchar *buf, gint len)
780 gint n, wrlen = 0;
782 while (len)
784 n = socket_fd_write(fd, buf, len);
785 if (n <= 0)
786 return -1;
787 len -= n;
788 wrlen += n;
789 buf += n;
792 return wrlen;
796 gint socket_fd_write(gint fd, const gchar *buf, gint len)
798 if (socket_fd_check_io(fd, G_IO_OUT) < 0)
799 return -1;
801 #ifdef G_OS_WIN32
802 return send(fd, buf, len, 0);
803 #else
804 return write(fd, buf, len);
805 #endif
809 #endif