1 /* Copyright (C) 2009 Pierre-Marc Fournier
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 #include <sys/types.h>
22 #include <sys/socket.h>
36 #include "multipoll.h"
38 #define UNIX_PATH_MAX 108
42 /* FIXME: ustcomm blocks on message sending, which might be problematic in
43 * some cases. Fix the poll() usage so sends are buffered until they don't
47 //static void bt(void)
52 // result = backtrace(&buffer, 100);
53 // backtrace_symbols_fd(buffer, result, STDERR_FILENO);
56 static int mkdir_p(const char *path
, mode_t mode
)
64 tmp
= malloc(strlen(path
) + 1);
72 while (*path_p
!= '/') {
78 strncpy(tmp
, path
, path_p
- path
);
79 tmp
[path_p
-path
] = '\0';
80 if (tmp
[path_p
- path
- 1] != '/') {
81 result
= mkdir(tmp
, mode
);
83 if (!(errno
== EEXIST
|| errno
== EACCES
|| errno
== EROFS
)) {
84 /* Then this is a real error */
94 result
= mkdir(path
, mode
);
105 char *strdup_malloc(const char *s
)
112 retval
= (char *) malloc(strlen(s
)+1);
119 static int signal_process(pid_t pid
)
124 void ustcomm_init_connection(struct ustcomm_connection
*conn
)
126 conn
->recv_buf
= NULL
;
127 conn
->recv_buf_size
= 0;
128 conn
->recv_buf_alloc
= 0;
131 int pid_is_online(pid_t pid
) {
137 * @fd: file descriptor to send to
138 * @msg: a null-terminated string containing the message to send
142 * 0: connection closed
146 static int send_message_fd(int fd
, const char *msg
)
150 /* Send including the final \0 */
151 result
= patient_send(fd
, msg
, strlen(msg
)+1, MSG_NOSIGNAL
);
157 else if(result
== 0) {
161 DBG("sent message \"%s\"", msg
);
165 /* Called by an app to ask the consumer daemon to connect to it. */
167 int ustcomm_request_consumer(pid_t pid
, const char *channel
)
169 char path
[UNIX_PATH_MAX
];
173 struct ustcomm_connection conn
;
174 char *explicit_daemon_socket_path
;
176 explicit_daemon_socket_path
= getenv("UST_DAEMON_SOCKET");
177 if(explicit_daemon_socket_path
) {
178 /* user specified explicitly a socket path */
179 result
= snprintf(path
, UNIX_PATH_MAX
, "%s", explicit_daemon_socket_path
);
182 /* just use the default path */
183 result
= snprintf(path
, UNIX_PATH_MAX
, "%s/ustd", SOCK_DIR
);
186 if(result
>= UNIX_PATH_MAX
) {
187 ERR("string overflow allocating socket name");
191 asprintf(&msg
, "collect %d %s", pid
, channel
);
193 /* don't signal it because it's the daemon */
194 result
= ustcomm_connect_path(path
, &conn
, -1);
196 WARN("ustcomm_connect_path failed");
201 result
= ustcomm_send_request(&conn
, msg
, NULL
);
203 WARN("ustcomm_send_request failed");
209 ustcomm_disconnect(&conn
);
216 /* returns 1 to indicate a message was received
217 * returns 0 to indicate no message was received (end of stream)
218 * returns -1 to indicate an error
221 #define RECV_INCREMENT 1000
222 #define RECV_INITIAL_BUF_SIZE 10
224 static int recv_message_fd(int fd
, char **recv_buf
, int *recv_buf_size
, int *recv_buf_alloc
, char **msg
)
228 /* 1. Check if there is a message in the buf */
230 2.1 receive chunk and put it in buffer
231 2.2 process full message if there is one
232 -- while no message arrived
239 /* Search for full message in buffer */
240 for(i
=0; i
<*recv_buf_size
; i
++) {
241 if((*recv_buf
)[i
] == '\0') {
247 /* Process found message */
253 WARN("received empty message");
255 *msg
= strndup(*recv_buf
, i
);
257 /* Remove processed message from buffer */
258 newbuf
= (char *) malloc(*recv_buf_size
- (i
+1));
259 memcpy(newbuf
, *recv_buf
+ (i
+1), *recv_buf_size
- (i
+1));
262 *recv_buf_size
-= (i
+1);
263 *recv_buf_alloc
-= (i
+1);
268 /* Receive a chunk from the fd */
269 if(*recv_buf_alloc
- *recv_buf_size
< RECV_INCREMENT
) {
270 *recv_buf_alloc
+= RECV_INCREMENT
- (*recv_buf_alloc
- *recv_buf_size
);
271 *recv_buf
= (char *) realloc(*recv_buf
, *recv_buf_alloc
);
274 result
= recv(fd
, *recv_buf
+*recv_buf_size
, RECV_INCREMENT
, 0);
276 if(errno
== ECONNRESET
) {
287 *recv_buf_size
+= result
;
289 /* Go back to the beginning to check if there is a full message in the buffer */
292 DBG("received message \"%s\"", *recv_buf
);
298 static int recv_message_conn(struct ustcomm_connection
*conn
, char **msg
)
300 return recv_message_fd(conn
->fd
, &conn
->recv_buf
, &conn
->recv_buf_size
, &conn
->recv_buf_alloc
, msg
);
303 int ustcomm_send_reply(struct ustcomm_server
*server
, char *msg
, struct ustcomm_source
*src
)
307 result
= send_message_fd(src
->fd
, msg
);
309 ERR("error in send_message_fd");
316 /* Called after a fork. */
318 int ustcomm_close_all_connections(struct ustcomm_server
*server
)
320 struct ustcomm_connection
*conn
;
321 struct ustcomm_connection
*deletable_conn
= NULL
;
323 list_for_each_entry(conn
, &server
->connections
, list
) {
324 free(deletable_conn
);
325 deletable_conn
= conn
;
326 ustcomm_close_app(conn
);
327 list_del(&conn
->list
);
333 /* @timeout: max blocking time in milliseconds, -1 means infinity
335 * returns 1 to indicate a message was received
336 * returns 0 to indicate no message was received
337 * returns -1 to indicate an error
340 int ustcomm_recv_message(struct ustcomm_server
*server
, char **msg
, struct ustcomm_source
*src
, int timeout
)
343 struct ustcomm_connection
**conn_table
;
344 struct ustcomm_connection
*conn
;
352 list_for_each_entry(conn
, &server
->connections
, list
) {
356 fds
= (struct pollfd
*) malloc(n_fds
* sizeof(struct pollfd
));
358 ERR("malloc returned NULL");
362 conn_table
= (struct ustcomm_connection
**) malloc(n_fds
* sizeof(struct ustcomm_connection
*));
363 if(conn_table
== NULL
) {
364 ERR("malloc returned NULL");
366 goto free_fds_return
;
369 /* special idx 0 is for listening socket */
370 fds
[idx
].fd
= server
->listen_fd
;
371 fds
[idx
].events
= POLLIN
;
374 list_for_each_entry(conn
, &server
->connections
, list
) {
375 fds
[idx
].fd
= conn
->fd
;
376 fds
[idx
].events
= POLLIN
;
377 conn_table
[idx
] = conn
;
381 while((result
= poll(fds
, n_fds
, timeout
)) == -1 && errno
== EINTR
)
386 goto free_conn_table_return
;
391 goto free_conn_table_return
;
395 struct ustcomm_connection
*newconn
;
398 result
= newfd
= accept(server
->listen_fd
, NULL
, NULL
);
402 goto free_conn_table_return
;
405 newconn
= (struct ustcomm_connection
*) malloc(sizeof(struct ustcomm_connection
));
406 if(newconn
== NULL
) {
407 ERR("malloc returned NULL");
411 ustcomm_init_connection(newconn
);
414 list_add(&newconn
->list
, &server
->connections
);
417 for(idx
=1; idx
<n_fds
; idx
++) {
418 if(fds
[idx
].revents
) {
419 retval
= recv_message_conn(conn_table
[idx
], msg
);
421 src
->fd
= fds
[idx
].fd
;
424 /* connection finished */
425 list_for_each_entry(conn
, &server
->connections
, list
) {
426 if(conn
->fd
== fds
[idx
].fd
) {
427 ustcomm_close_app(conn
);
428 list_del(&conn
->list
);
435 goto free_conn_table_return
;
444 free_conn_table_return
:
451 int ustcomm_ustd_recv_message(struct ustcomm_ustd
*ustd
, char **msg
, struct ustcomm_source
*src
, int timeout
)
453 return ustcomm_recv_message(&ustd
->server
, msg
, src
, timeout
);
456 int ustcomm_app_recv_message(struct ustcomm_app
*app
, char **msg
, struct ustcomm_source
*src
, int timeout
)
458 return ustcomm_recv_message(&app
->server
, msg
, src
, timeout
);
461 /* This removes src from the list of active connections of app.
464 int ustcomm_app_detach_client(struct ustcomm_app
*app
, struct ustcomm_source
*src
)
466 struct ustcomm_server
*server
= (struct ustcomm_server
*)app
;
467 struct ustcomm_connection
*conn
;
469 list_for_each_entry(conn
, &server
->connections
, list
) {
470 if(conn
->fd
== src
->fd
) {
471 list_del(&conn
->list
);
481 static int init_named_socket(const char *name
, char **path_out
)
486 struct sockaddr_un addr
;
488 result
= fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
494 addr
.sun_family
= AF_UNIX
;
496 strncpy(addr
.sun_path
, name
, UNIX_PATH_MAX
);
497 addr
.sun_path
[UNIX_PATH_MAX
-1] = '\0';
499 result
= access(name
, F_OK
);
502 result
= unlink(name
);
504 PERROR("unlink of socket file");
507 DBG("socket already exists; overwriting");
510 result
= bind(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
516 result
= listen(fd
, 1);
523 *path_out
= strdup(addr
.sun_path
);
536 * 0: Success, but no reply because recv() returned 0
540 * On error, the error message is printed, except on
541 * ECONNRESET, which is normal when the application dies.
544 int ustcomm_send_request(struct ustcomm_connection
*conn
, const char *req
, char **reply
)
548 /* Send including the final \0 */
549 result
= send_message_fd(conn
->fd
, req
);
556 result
= recv_message_conn(conn
, reply
);
560 else if(result
== 0) {
572 int ustcomm_connect_path(const char *path
, struct ustcomm_connection
*conn
, pid_t signalpid
)
576 struct sockaddr_un addr
;
578 ustcomm_init_connection(conn
);
580 result
= fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
586 addr
.sun_family
= AF_UNIX
;
588 result
= snprintf(addr
.sun_path
, UNIX_PATH_MAX
, "%s", path
);
589 if(result
>= UNIX_PATH_MAX
) {
590 ERR("string overflow allocating socket name");
595 result
= signal_process(signalpid
);
597 ERR("could not signal process");
602 result
= connect(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
604 PERROR("connect (path=%s)", path
);
613 int ustcomm_disconnect(struct ustcomm_connection
*conn
)
615 return close(conn
->fd
);
618 /* Open a connection to a traceable app.
625 int ustcomm_connect_app(pid_t pid
, struct ustcomm_connection
*conn
)
628 char path
[UNIX_PATH_MAX
];
631 result
= snprintf(path
, UNIX_PATH_MAX
, "%s/%d", SOCK_DIR
, pid
);
632 if(result
>= UNIX_PATH_MAX
) {
633 ERR("string overflow allocating socket name");
637 return ustcomm_connect_path(path
, conn
, pid
);
640 /* Close a connection to a traceable app. It frees the
641 * resources. It however does not free the
642 * ustcomm_connection itself.
645 int ustcomm_close_app(struct ustcomm_connection
*conn
)
648 free(conn
->recv_buf
);
653 static int ensure_dir_exists(const char *dir
)
661 result
= stat(dir
, &st
);
662 if(result
== -1 && errno
!= ENOENT
) {
665 else if(result
== -1) {
669 result
= mkdir_p(dir
, 0777);
671 ERR("executing in recursive creation of directory %s", dir
);
679 /* Called by an application to initialize its server so daemons can
683 int ustcomm_init_app(pid_t pid
, struct ustcomm_app
*handle
)
688 result
= asprintf(&name
, "%s/%d", SOCK_DIR
, (int)pid
);
689 if(result
>= UNIX_PATH_MAX
) {
690 ERR("string overflow allocating socket name");
694 result
= ensure_dir_exists(SOCK_DIR
);
696 ERR("Unable to create socket directory %s", SOCK_DIR
);
700 handle
->server
.listen_fd
= init_named_socket(name
, &(handle
->server
.socketpath
));
701 if(handle
->server
.listen_fd
< 0) {
702 ERR("Error initializing named socket (%s). Check that directory exists and that it is writable.", name
);
707 INIT_LIST_HEAD(&handle
->server
.connections
);
716 /* Used by the daemon to initialize its server so applications
720 int ustcomm_init_ustd(struct ustcomm_ustd
*handle
, const char *sock_path
)
726 asprintf(&name
, "%s", sock_path
);
731 /* Only check if socket dir exists if we are using the default directory */
732 result
= ensure_dir_exists(SOCK_DIR
);
734 ERR("Unable to create socket directory %s", SOCK_DIR
);
738 asprintf(&name
, "%s/%s", SOCK_DIR
, "ustd");
741 handle
->server
.listen_fd
= init_named_socket(name
, &handle
->server
.socketpath
);
742 if(handle
->server
.listen_fd
< 0) {
743 ERR("error initializing named socket at %s", name
);
748 INIT_LIST_HEAD(&handle
->server
.connections
);
756 static void ustcomm_fini_server(struct ustcomm_server
*server
, int keep_socket_file
)
761 if(!keep_socket_file
) {
763 result
= stat(server
->socketpath
, &st
);
765 PERROR("stat (%s)", server
->socketpath
);
769 /* Paranoid check before deleting. */
770 result
= S_ISSOCK(st
.st_mode
);
772 ERR("The socket we are about to delete is not a socket.");
776 result
= unlink(server
->socketpath
);
782 free(server
->socketpath
);
784 result
= close(server
->listen_fd
);
791 /* Free a traceable application server */
793 void ustcomm_fini_app(struct ustcomm_app
*handle
, int keep_socket_file
)
795 ustcomm_fini_server(&handle
->server
, keep_socket_file
);
798 /* Free a ustd server */
800 void ustcomm_fini_ustd(struct ustcomm_ustd
*handle
)
802 ustcomm_fini_server(&handle
->server
, 0);
805 static const char *find_tok(const char *str
)
817 static const char *find_sep(const char *str
)
829 int nth_token_is(const char *str
, const char *token
, int tok_no
)
835 for(i
=0; i
<=tok_no
; i
++) {
849 if(end
-start
!= strlen(token
))
852 if(strncmp(start
, token
, end
-start
))
858 char *nth_token(const char *str
, int tok_no
)
860 static char *retval
= NULL
;
865 for(i
=0; i
<=tok_no
; i
++) {
884 asprintf(&retval
, "%.*s", (int)(end
-start
), start
);
889 /* Callback from multipoll.
890 * Receive a new connection on the listening socket.
893 static int process_mp_incoming_conn(void *priv
, int fd
, short events
)
895 struct ustcomm_connection
*newconn
;
896 struct ustcomm_server
*server
= (struct ustcomm_server
*) priv
;
900 result
= newfd
= accept(server
->listen_fd
, NULL
, NULL
);
906 newconn
= (struct ustcomm_connection
*) malloc(sizeof(struct ustcomm_connection
));
907 if(newconn
== NULL
) {
908 ERR("malloc returned NULL");
912 ustcomm_init_connection(newconn
);
915 list_add(&newconn
->list
, &server
->connections
);
920 /* Callback from multipoll.
921 * Receive a message on an existing connection.
924 static int process_mp_conn_msg(void *priv
, int fd
, short revents
)
926 struct ustcomm_multipoll_conn_info
*mpinfo
= (struct ustcomm_multipoll_conn_info
*) priv
;
929 struct ustcomm_source src
;
934 result
= recv_message_conn(mpinfo
->conn
, &msg
);
936 ERR("error in recv_message_conn");
939 else if(result
== 0) {
940 /* connection finished */
941 ustcomm_close_app(mpinfo
->conn
);
942 list_del(&mpinfo
->conn
->list
);
946 mpinfo
->cb(msg
, &src
);
954 int free_ustcomm_client_poll(void *data
)
960 void ustcomm_mp_add_app_clients(struct mpentries
*ent
, struct ustcomm_app
*app
, int (*cb
)(struct ustcomm_connection
*conn
, char *msg
))
962 struct ustcomm_connection
*conn
;
964 /* add listener socket */
965 multipoll_add(ent
, app
->server
.listen_fd
, POLLIN
, process_mp_incoming_conn
, &app
->server
, NULL
);
967 list_for_each_entry(conn
, &app
->server
.connections
, list
) {
968 struct ustcomm_multipoll_conn_info
*mpinfo
= (struct ustcomm_multipoll_conn_info
*) malloc(sizeof(struct ustcomm_multipoll_conn_info
));
971 multipoll_add(ent
, conn
->fd
, POLLIN
, process_mp_conn_msg
, mpinfo
, free_ustcomm_client_poll
);