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
18 /* API used by UST components to communicate with each other via sockets. */
21 #include <sys/types.h>
24 #include <sys/socket.h>
38 #include "multipoll.h"
40 #define UNIX_PATH_MAX 108
42 static int mkdir_p(const char *path
, mode_t mode
)
50 tmp
= malloc(strlen(path
) + 1);
58 while (*path_p
!= '/') {
64 strncpy(tmp
, path
, path_p
- path
);
65 tmp
[path_p
-path
] = '\0';
66 if (tmp
[path_p
- path
- 1] != '/') {
67 result
= mkdir(tmp
, mode
);
69 if (!(errno
== EEXIST
|| errno
== EACCES
|| errno
== EROFS
)) {
70 /* Then this is a real error */
80 result
= mkdir(path
, mode
);
91 static int signal_process(pid_t pid
)
96 void ustcomm_init_connection(struct ustcomm_connection
*conn
)
98 conn
->recv_buf
= NULL
;
99 conn
->recv_buf_size
= 0;
100 conn
->recv_buf_alloc
= 0;
103 int pid_is_online(pid_t pid
) {
109 * @fd: file descriptor to send to
110 * @msg: a null-terminated string containing the message to send
114 * 0: connection closed
118 static int send_message_fd(int fd
, const char *msg
)
122 /* Send including the final \0 */
123 result
= patient_send(fd
, msg
, strlen(msg
)+1, MSG_NOSIGNAL
);
129 else if(result
== 0) {
133 DBG("sent message \"%s\"", msg
);
137 /* Called by an app to ask the consumer daemon to connect to it. */
139 int ustcomm_request_consumer(pid_t pid
, const char *channel
)
141 char path
[UNIX_PATH_MAX
];
145 struct ustcomm_connection conn
;
146 char *explicit_daemon_socket_path
;
148 explicit_daemon_socket_path
= getenv("UST_DAEMON_SOCKET");
149 if(explicit_daemon_socket_path
) {
150 /* user specified explicitly a socket path */
151 result
= snprintf(path
, UNIX_PATH_MAX
, "%s", explicit_daemon_socket_path
);
154 /* just use the default path */
155 result
= snprintf(path
, UNIX_PATH_MAX
, "%s/ustd", SOCK_DIR
);
158 if(result
>= UNIX_PATH_MAX
) {
159 ERR("string overflow allocating socket name");
163 asprintf(&msg
, "collect %d %s", pid
, channel
);
165 /* don't signal it because it's the daemon */
166 result
= ustcomm_connect_path(path
, &conn
, -1);
168 WARN("ustcomm_connect_path failed");
173 result
= ustcomm_send_request(&conn
, msg
, NULL
);
175 WARN("ustcomm_send_request failed");
181 ustcomm_disconnect(&conn
);
188 /* returns 1 to indicate a message was received
189 * returns 0 to indicate no message was received (end of stream)
190 * returns -1 to indicate an error
193 #define RECV_INCREMENT 1000
194 #define RECV_INITIAL_BUF_SIZE 10
196 static int recv_message_fd(int fd
, char **recv_buf
, int *recv_buf_size
, int *recv_buf_alloc
, char **msg
)
200 /* 1. Check if there is a message in the buf */
202 2.1 receive chunk and put it in buffer
203 2.2 process full message if there is one
204 -- while no message arrived
211 /* Search for full message in buffer */
212 for(i
=0; i
<*recv_buf_size
; i
++) {
213 if((*recv_buf
)[i
] == '\0') {
219 /* Process found message */
225 WARN("received empty message");
227 *msg
= strndup(*recv_buf
, i
);
229 /* Remove processed message from buffer */
230 newbuf
= (char *) malloc(*recv_buf_size
- (i
+1));
231 memcpy(newbuf
, *recv_buf
+ (i
+1), *recv_buf_size
- (i
+1));
234 *recv_buf_size
-= (i
+1);
235 *recv_buf_alloc
-= (i
+1);
240 /* Receive a chunk from the fd */
241 if(*recv_buf_alloc
- *recv_buf_size
< RECV_INCREMENT
) {
242 *recv_buf_alloc
+= RECV_INCREMENT
- (*recv_buf_alloc
- *recv_buf_size
);
243 *recv_buf
= (char *) realloc(*recv_buf
, *recv_buf_alloc
);
246 result
= recv(fd
, *recv_buf
+*recv_buf_size
, RECV_INCREMENT
, 0);
248 if(errno
== ECONNRESET
) {
252 else if(errno
== EINTR
) {
263 *recv_buf_size
+= result
;
265 /* Go back to the beginning to check if there is a full message in the buffer */
268 DBG("received message \"%s\"", *recv_buf
);
274 static int recv_message_conn(struct ustcomm_connection
*conn
, char **msg
)
276 return recv_message_fd(conn
->fd
, &conn
->recv_buf
, &conn
->recv_buf_size
, &conn
->recv_buf_alloc
, msg
);
279 int ustcomm_send_reply(struct ustcomm_server
*server
, char *msg
, struct ustcomm_source
*src
)
283 result
= send_message_fd(src
->fd
, msg
);
285 ERR("error in send_message_fd");
292 /* Called after a fork. */
294 int ustcomm_close_all_connections(struct ustcomm_server
*server
)
296 struct ustcomm_connection
*conn
;
297 struct ustcomm_connection
*deletable_conn
= NULL
;
299 list_for_each_entry(conn
, &server
->connections
, list
) {
300 free(deletable_conn
);
301 deletable_conn
= conn
;
302 ustcomm_close_app(conn
);
303 list_del(&conn
->list
);
309 /* @timeout: max blocking time in milliseconds, -1 means infinity
311 * returns 1 to indicate a message was received
312 * returns 0 to indicate no message was received
313 * returns -1 to indicate an error
316 int ustcomm_recv_message(struct ustcomm_server
*server
, char **msg
, struct ustcomm_source
*src
, int timeout
)
319 struct ustcomm_connection
**conn_table
;
320 struct ustcomm_connection
*conn
;
328 list_for_each_entry(conn
, &server
->connections
, list
) {
332 fds
= (struct pollfd
*) malloc(n_fds
* sizeof(struct pollfd
));
334 ERR("malloc returned NULL");
338 conn_table
= (struct ustcomm_connection
**) malloc(n_fds
* sizeof(struct ustcomm_connection
*));
339 if(conn_table
== NULL
) {
340 ERR("malloc returned NULL");
342 goto free_fds_return
;
345 /* special idx 0 is for listening socket */
346 fds
[idx
].fd
= server
->listen_fd
;
347 fds
[idx
].events
= POLLIN
;
350 list_for_each_entry(conn
, &server
->connections
, list
) {
351 fds
[idx
].fd
= conn
->fd
;
352 fds
[idx
].events
= POLLIN
;
353 conn_table
[idx
] = conn
;
357 result
= poll(fds
, n_fds
, timeout
);
358 if(result
== -1 && errno
== EINTR
) {
359 /* That's ok. ustd receives signals to notify it must shutdown. */
361 goto free_conn_table_return
;
363 else if(result
== -1) {
366 goto free_conn_table_return
;
368 else if(result
== 0) {
370 goto free_conn_table_return
;
374 struct ustcomm_connection
*newconn
;
377 result
= newfd
= accept(server
->listen_fd
, NULL
, NULL
);
381 goto free_conn_table_return
;
384 newconn
= (struct ustcomm_connection
*) malloc(sizeof(struct ustcomm_connection
));
385 if(newconn
== NULL
) {
386 ERR("malloc returned NULL");
390 ustcomm_init_connection(newconn
);
393 list_add(&newconn
->list
, &server
->connections
);
396 for(idx
=1; idx
<n_fds
; idx
++) {
397 if(fds
[idx
].revents
) {
398 retval
= recv_message_conn(conn_table
[idx
], msg
);
400 src
->fd
= fds
[idx
].fd
;
403 /* connection finished */
404 list_for_each_entry(conn
, &server
->connections
, list
) {
405 if(conn
->fd
== fds
[idx
].fd
) {
406 ustcomm_close_app(conn
);
407 list_del(&conn
->list
);
414 goto free_conn_table_return
;
423 free_conn_table_return
:
430 int ustcomm_ustd_recv_message(struct ustcomm_ustd
*ustd
, char **msg
, struct ustcomm_source
*src
, int timeout
)
432 return ustcomm_recv_message(&ustd
->server
, msg
, src
, timeout
);
435 int ustcomm_app_recv_message(struct ustcomm_app
*app
, char **msg
, struct ustcomm_source
*src
, int timeout
)
437 return ustcomm_recv_message(&app
->server
, msg
, src
, timeout
);
440 /* This removes src from the list of active connections of app.
443 int ustcomm_app_detach_client(struct ustcomm_app
*app
, struct ustcomm_source
*src
)
445 struct ustcomm_server
*server
= (struct ustcomm_server
*)app
;
446 struct ustcomm_connection
*conn
;
448 list_for_each_entry(conn
, &server
->connections
, list
) {
449 if(conn
->fd
== src
->fd
) {
450 list_del(&conn
->list
);
460 static int init_named_socket(const char *name
, char **path_out
)
465 struct sockaddr_un addr
;
467 result
= fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
473 addr
.sun_family
= AF_UNIX
;
475 strncpy(addr
.sun_path
, name
, UNIX_PATH_MAX
);
476 addr
.sun_path
[UNIX_PATH_MAX
-1] = '\0';
478 result
= access(name
, F_OK
);
481 result
= unlink(name
);
483 PERROR("unlink of socket file");
486 DBG("socket already exists; overwriting");
489 result
= bind(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
495 result
= listen(fd
, 1);
502 *path_out
= strdup(addr
.sun_path
);
515 * 0: Success, but no reply because recv() returned 0
519 * On error, the error message is printed, except on
520 * ECONNRESET, which is normal when the application dies.
523 int ustcomm_send_request(struct ustcomm_connection
*conn
, const char *req
, char **reply
)
527 /* Send including the final \0 */
528 result
= send_message_fd(conn
->fd
, req
);
535 result
= recv_message_conn(conn
, reply
);
539 else if(result
== 0) {
551 int ustcomm_connect_path(const char *path
, struct ustcomm_connection
*conn
, pid_t signalpid
)
555 struct sockaddr_un addr
;
557 ustcomm_init_connection(conn
);
559 result
= fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
565 addr
.sun_family
= AF_UNIX
;
567 result
= snprintf(addr
.sun_path
, UNIX_PATH_MAX
, "%s", path
);
568 if(result
>= UNIX_PATH_MAX
) {
569 ERR("string overflow allocating socket name");
574 result
= signal_process(signalpid
);
576 ERR("could not signal process");
581 result
= connect(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
583 PERROR("connect (path=%s)", path
);
592 int ustcomm_disconnect(struct ustcomm_connection
*conn
)
594 return close(conn
->fd
);
597 /* Open a connection to a traceable app.
604 int ustcomm_connect_app(pid_t pid
, struct ustcomm_connection
*conn
)
607 char path
[UNIX_PATH_MAX
];
610 result
= snprintf(path
, UNIX_PATH_MAX
, "%s/%d", SOCK_DIR
, pid
);
611 if(result
>= UNIX_PATH_MAX
) {
612 ERR("string overflow allocating socket name");
616 return ustcomm_connect_path(path
, conn
, pid
);
619 /* Close a connection to a traceable app. It frees the
620 * resources. It however does not free the
621 * ustcomm_connection itself.
624 int ustcomm_close_app(struct ustcomm_connection
*conn
)
627 free(conn
->recv_buf
);
632 static int ensure_dir_exists(const char *dir
)
640 result
= stat(dir
, &st
);
641 if(result
== -1 && errno
!= ENOENT
) {
644 else if(result
== -1) {
648 result
= mkdir_p(dir
, 0777);
650 ERR("executing in recursive creation of directory %s", dir
);
658 /* Called by an application to initialize its server so daemons can
662 int ustcomm_init_app(pid_t pid
, struct ustcomm_app
*handle
)
667 result
= asprintf(&name
, "%s/%d", SOCK_DIR
, (int)pid
);
668 if(result
>= UNIX_PATH_MAX
) {
669 ERR("string overflow allocating socket name");
673 result
= ensure_dir_exists(SOCK_DIR
);
675 ERR("Unable to create socket directory %s", SOCK_DIR
);
679 handle
->server
.listen_fd
= init_named_socket(name
, &(handle
->server
.socketpath
));
680 if(handle
->server
.listen_fd
< 0) {
681 ERR("Error initializing named socket (%s). Check that directory exists and that it is writable.", name
);
686 INIT_LIST_HEAD(&handle
->server
.connections
);
695 /* Used by the daemon to initialize its server so applications
699 int ustcomm_init_ustd(struct ustcomm_ustd
*handle
, const char *sock_path
)
705 asprintf(&name
, "%s", sock_path
);
710 /* Only check if socket dir exists if we are using the default directory */
711 result
= ensure_dir_exists(SOCK_DIR
);
713 ERR("Unable to create socket directory %s", SOCK_DIR
);
717 asprintf(&name
, "%s/%s", SOCK_DIR
, "ustd");
720 handle
->server
.listen_fd
= init_named_socket(name
, &handle
->server
.socketpath
);
721 if(handle
->server
.listen_fd
< 0) {
722 ERR("error initializing named socket at %s", name
);
727 INIT_LIST_HEAD(&handle
->server
.connections
);
735 static void ustcomm_fini_server(struct ustcomm_server
*server
, int keep_socket_file
)
740 if(!keep_socket_file
) {
742 result
= stat(server
->socketpath
, &st
);
744 PERROR("stat (%s)", server
->socketpath
);
748 /* Paranoid check before deleting. */
749 result
= S_ISSOCK(st
.st_mode
);
751 ERR("The socket we are about to delete is not a socket.");
755 result
= unlink(server
->socketpath
);
761 free(server
->socketpath
);
763 result
= close(server
->listen_fd
);
770 /* Free a traceable application server */
772 void ustcomm_fini_app(struct ustcomm_app
*handle
, int keep_socket_file
)
774 ustcomm_fini_server(&handle
->server
, keep_socket_file
);
777 /* Free a ustd server */
779 void ustcomm_fini_ustd(struct ustcomm_ustd
*handle
)
781 ustcomm_fini_server(&handle
->server
, 0);
784 static const char *find_tok(const char *str
)
796 static const char *find_sep(const char *str
)
808 int nth_token_is(const char *str
, const char *token
, int tok_no
)
814 for(i
=0; i
<=tok_no
; i
++) {
828 if(end
-start
!= strlen(token
))
831 if(strncmp(start
, token
, end
-start
))
837 char *nth_token(const char *str
, int tok_no
)
839 static char *retval
= NULL
;
844 for(i
=0; i
<=tok_no
; i
++) {
863 asprintf(&retval
, "%.*s", (int)(end
-start
), start
);
868 /* Callback from multipoll.
869 * Receive a new connection on the listening socket.
872 static int process_mp_incoming_conn(void *priv
, int fd
, short events
)
874 struct ustcomm_connection
*newconn
;
875 struct ustcomm_server
*server
= (struct ustcomm_server
*) priv
;
879 result
= newfd
= accept(server
->listen_fd
, NULL
, NULL
);
885 newconn
= (struct ustcomm_connection
*) malloc(sizeof(struct ustcomm_connection
));
886 if(newconn
== NULL
) {
887 ERR("malloc returned NULL");
891 ustcomm_init_connection(newconn
);
894 list_add(&newconn
->list
, &server
->connections
);
899 /* Callback from multipoll.
900 * Receive a message on an existing connection.
903 static int process_mp_conn_msg(void *priv
, int fd
, short revents
)
905 struct ustcomm_multipoll_conn_info
*mpinfo
= (struct ustcomm_multipoll_conn_info
*) priv
;
908 struct ustcomm_source src
;
913 result
= recv_message_conn(mpinfo
->conn
, &msg
);
915 ERR("error in recv_message_conn");
918 else if(result
== 0) {
919 /* connection finished */
920 ustcomm_close_app(mpinfo
->conn
);
921 list_del(&mpinfo
->conn
->list
);
925 mpinfo
->cb(msg
, &src
);
933 int free_ustcomm_client_poll(void *data
)
939 void ustcomm_mp_add_app_clients(struct mpentries
*ent
, struct ustcomm_app
*app
, int (*cb
)(char *recvbuf
, struct ustcomm_source
*src
))
941 struct ustcomm_connection
*conn
;
943 /* add listener socket */
944 multipoll_add(ent
, app
->server
.listen_fd
, POLLIN
, process_mp_incoming_conn
, &app
->server
, NULL
);
946 list_for_each_entry(conn
, &app
->server
.connections
, list
) {
947 struct ustcomm_multipoll_conn_info
*mpinfo
= (struct ustcomm_multipoll_conn_info
*) malloc(sizeof(struct ustcomm_multipoll_conn_info
));
950 multipoll_add(ent
, conn
->fd
, POLLIN
, process_mp_conn_msg
, mpinfo
, free_ustcomm_client_poll
);