ust_fork(): close the ustcomm_app socket in the child on fork()
[ust.git] / libustcomm / ustcomm.c
1 /* Copyright (C) 2009 Pierre-Marc Fournier
2 *
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.
7 *
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.
12 *
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
16 */
17
18 #define _GNU_SOURCE
19 #include <sys/types.h>
20 #include <signal.h>
21 #include <errno.h>
22 #include <sys/socket.h>
23 #include <sys/un.h>
24 #include <unistd.h>
25 #include <poll.h>
26 #include <sys/stat.h>
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <execinfo.h>
32
33 #include "ustcomm.h"
34 #include "usterr.h"
35 #include "share.h"
36
37 #define UNIX_PATH_MAX 108
38
39 #define MSG_MAX 10000
40
41 /* FIXME: ustcomm blocks on message sending, which might be problematic in
42 * some cases. Fix the poll() usage so sends are buffered until they don't
43 * block.
44 */
45
46 //static void bt(void)
47 //{
48 // void *buffer[100];
49 // int result;
50 //
51 // result = backtrace(&buffer, 100);
52 // backtrace_symbols_fd(buffer, result, STDERR_FILENO);
53 //}
54
55 static int mkdir_p(const char *path, mode_t mode)
56 {
57 const char *path_p;
58 char *tmp;
59
60 int retval = 0;
61 int result;
62
63 tmp = malloc(strlen(path) + 1);
64 if (tmp == NULL)
65 return -1;
66
67 /* skip first / */
68 path_p = path+1;
69
70 for(;;) {
71 while (*path_p != '/') {
72 if(*path_p == 0)
73 break;
74 ++path_p;
75 }
76 if (*path_p == '/') {
77 strncpy(tmp, path, path_p - path);
78 tmp[path_p-path] = '\0';
79 if (tmp[path_p - path - 1] != '/') {
80 result = mkdir(tmp, mode);
81 if(result == -1) {
82 if (!(errno == EEXIST || errno == EACCES || errno == EROFS)) {
83 /* Then this is a real error */
84 retval = -1;
85 break;
86 }
87 }
88 }
89 /* pass / */
90 path_p++;
91 } else {
92 /* last component */
93 result = mkdir(path, mode);
94 if (result == -1)
95 retval = -1;
96 break;
97 }
98 }
99
100 free(tmp);
101 return retval;
102 }
103
104 char *strdup_malloc(const char *s)
105 {
106 char *retval;
107
108 if(s == NULL)
109 return NULL;
110
111 retval = (char *) malloc(strlen(s)+1);
112
113 strcpy(retval, s);
114
115 return retval;
116 }
117
118 static int signal_process(pid_t pid)
119 {
120 return 0;
121 }
122
123 void ustcomm_init_connection(struct ustcomm_connection *conn)
124 {
125 conn->recv_buf = NULL;
126 conn->recv_buf_size = 0;
127 conn->recv_buf_alloc = 0;
128 }
129
130 int pid_is_online(pid_t pid) {
131 return 1;
132 }
133
134 /* Send a message
135 *
136 * @fd: file descriptor to send to
137 * @msg: a null-terminated string containing the message to send
138 *
139 * Return value:
140 * -1: error
141 * 0: connection closed
142 * 1: success
143 */
144
145 static int send_message_fd(int fd, const char *msg)
146 {
147 int result;
148
149 /* Send including the final \0 */
150 result = patient_send(fd, msg, strlen(msg)+1, MSG_NOSIGNAL);
151 if(result == -1) {
152 if(errno != EPIPE)
153 PERROR("send");
154 return -1;
155 }
156 else if(result == 0) {
157 return 0;
158 }
159
160 DBG("sent message \"%s\"", msg);
161 return 1;
162 }
163
164 /* Called by an app to ask the consumer daemon to connect to it. */
165
166 int ustcomm_request_consumer(pid_t pid, const char *channel)
167 {
168 char path[UNIX_PATH_MAX];
169 int result;
170 char *msg=NULL;
171 int retval = 0;
172 struct ustcomm_connection conn;
173 char *explicit_daemon_socket_path;
174
175 explicit_daemon_socket_path = getenv("UST_DAEMON_SOCKET");
176 if(explicit_daemon_socket_path) {
177 /* user specified explicitly a socket path */
178 result = snprintf(path, UNIX_PATH_MAX, "%s", explicit_daemon_socket_path);
179 }
180 else {
181 /* just use the default path */
182 result = snprintf(path, UNIX_PATH_MAX, "%s/ustd", SOCK_DIR);
183 }
184
185 if(result >= UNIX_PATH_MAX) {
186 ERR("string overflow allocating socket name");
187 return -1;
188 }
189
190 asprintf(&msg, "collect %d %s", pid, channel);
191
192 /* don't signal it because it's the daemon */
193 result = ustcomm_connect_path(path, &conn, -1);
194 if(result == -1) {
195 WARN("ustcomm_connect_path failed");
196 retval = -1;
197 goto del_string;
198 }
199
200 result = ustcomm_send_request(&conn, msg, NULL);
201 if(result == -1) {
202 WARN("ustcomm_send_request failed");
203 retval = -1;
204 goto disconnect;
205 }
206
207 disconnect:
208 ustcomm_disconnect(&conn);
209 del_string:
210 free(msg);
211
212 return retval;
213 }
214
215 /* returns 1 to indicate a message was received
216 * returns 0 to indicate no message was received (end of stream)
217 * returns -1 to indicate an error
218 */
219
220 #define RECV_INCREMENT 1000
221 #define RECV_INITIAL_BUF_SIZE 10
222
223 static int recv_message_fd(int fd, char **recv_buf, int *recv_buf_size, int *recv_buf_alloc, char **msg)
224 {
225 int result;
226
227 /* 1. Check if there is a message in the buf */
228 /* 2. If not, do:
229 2.1 receive chunk and put it in buffer
230 2.2 process full message if there is one
231 -- while no message arrived
232 */
233
234 for(;;) {
235 int i;
236 int nulfound = 0;
237
238 /* Search for full message in buffer */
239 for(i=0; i<*recv_buf_size; i++) {
240 if((*recv_buf)[i] == '\0') {
241 nulfound = 1;
242 break;
243 }
244 }
245
246 /* Process found message */
247 if(nulfound == 1) {
248 char *newbuf;
249
250 if(i == 0) {
251 /* problem */
252 }
253 *msg = strndup(*recv_buf, i);
254
255 /* Remove processed message from buffer */
256 newbuf = (char *) malloc(*recv_buf_size - (i+1));
257 memcpy(newbuf, *recv_buf + (i+1), *recv_buf_size - (i+1));
258 free(*recv_buf);
259 *recv_buf = newbuf;
260 *recv_buf_size -= (i+1);
261 *recv_buf_alloc -= (i+1);
262
263 return 1;
264 }
265
266 /* Receive a chunk from the fd */
267 if(*recv_buf_alloc - *recv_buf_size < RECV_INCREMENT) {
268 *recv_buf_alloc += RECV_INCREMENT - (*recv_buf_alloc - *recv_buf_size);
269 *recv_buf = (char *) realloc(*recv_buf, *recv_buf_alloc);
270 }
271
272 result = recv(fd, *recv_buf+*recv_buf_size, RECV_INCREMENT, 0);
273 if(result == -1) {
274 if(errno == ECONNRESET) {
275 *recv_buf_size = 0;
276 return 0;
277 }
278 /* real error */
279 PERROR("recv");
280 return -1;
281 }
282 if(result == 0) {
283 return 0;
284 }
285 *recv_buf_size += result;
286
287 /* Go back to the beginning to check if there is a full message in the buffer */
288 }
289
290 DBG("received message \"%s\"", *recv_buf);
291
292 return 1;
293
294 }
295
296 static int recv_message_conn(struct ustcomm_connection *conn, char **msg)
297 {
298 return recv_message_fd(conn->fd, &conn->recv_buf, &conn->recv_buf_size, &conn->recv_buf_alloc, msg);
299 }
300
301 int ustcomm_send_reply(struct ustcomm_server *server, char *msg, struct ustcomm_source *src)
302 {
303 int result;
304
305 result = send_message_fd(src->fd, msg);
306 if(result < 0) {
307 ERR("error in send_message_fd");
308 return -1;
309 }
310
311 return 0;
312 }
313
314 /* Called after a fork. */
315
316 int ustcomm_close_all_connections(struct ustcomm_server *server)
317 {
318 struct ustcomm_connection *conn;
319 struct ustcomm_connection *deletable_conn = NULL;
320
321 list_for_each_entry(conn, &server->connections, list) {
322 free(deletable_conn);
323 deletable_conn = conn;
324 close(conn->fd);
325 list_del(&conn->list);
326 }
327
328 return 0;
329 }
330
331 /* @timeout: max blocking time in milliseconds, -1 means infinity
332 *
333 * returns 1 to indicate a message was received
334 * returns 0 to indicate no message was received
335 * returns -1 to indicate an error
336 */
337
338 int ustcomm_recv_message(struct ustcomm_server *server, char **msg, struct ustcomm_source *src, int timeout)
339 {
340 struct pollfd *fds;
341 struct ustcomm_connection **conn_table;
342 struct ustcomm_connection *conn;
343 int result;
344 int retval;
345
346 for(;;) {
347 int idx = 0;
348 int n_fds = 1;
349
350 list_for_each_entry(conn, &server->connections, list) {
351 n_fds++;
352 }
353
354 fds = (struct pollfd *) malloc(n_fds * sizeof(struct pollfd));
355 if(fds == NULL) {
356 ERR("malloc returned NULL");
357 return -1;
358 }
359
360 conn_table = (struct ustcomm_connection **) malloc(n_fds * sizeof(struct ustcomm_connection *));
361 if(conn_table == NULL) {
362 ERR("malloc returned NULL");
363 return -1;
364 }
365
366 /* special idx 0 is for listening socket */
367 fds[idx].fd = server->listen_fd;
368 fds[idx].events = POLLIN;
369 idx++;
370
371 list_for_each_entry(conn, &server->connections, list) {
372 fds[idx].fd = conn->fd;
373 fds[idx].events = POLLIN;
374 conn_table[idx] = conn;
375 idx++;
376 }
377
378 while((result = poll(fds, n_fds, timeout)) == -1 && errno == EINTR)
379 /* nothing */;
380 if(result == -1) {
381 PERROR("poll");
382 return -1;
383 }
384
385 if(result == 0)
386 return 0;
387
388 if(fds[0].revents) {
389 struct ustcomm_connection *newconn;
390 int newfd;
391
392 result = newfd = accept(server->listen_fd, NULL, NULL);
393 if(result == -1) {
394 PERROR("accept");
395 return -1;
396 }
397
398 newconn = (struct ustcomm_connection *) malloc(sizeof(struct ustcomm_connection));
399 if(newconn == NULL) {
400 ERR("malloc returned NULL");
401 return -1;
402 }
403
404 ustcomm_init_connection(newconn);
405 newconn->fd = newfd;
406
407 list_add(&newconn->list, &server->connections);
408 }
409
410 for(idx=1; idx<n_fds; idx++) {
411 if(fds[idx].revents) {
412 retval = recv_message_conn(conn_table[idx], msg);
413 if(src)
414 src->fd = fds[idx].fd;
415
416 if(retval == 0) {
417 /* connection finished */
418 close(fds[idx].fd);
419
420 list_for_each_entry(conn, &server->connections, list) {
421 if(conn->fd == fds[idx].fd) {
422 list_del(&conn->list);
423 break;
424 }
425 }
426 }
427 else {
428 goto free_fds_return;
429 }
430 }
431 }
432
433 free(fds);
434 }
435
436 free_fds_return:
437 free(fds);
438 return retval;
439 }
440
441 int ustcomm_ustd_recv_message(struct ustcomm_ustd *ustd, char **msg, struct ustcomm_source *src, int timeout)
442 {
443 return ustcomm_recv_message(&ustd->server, msg, src, timeout);
444 }
445
446 int ustcomm_app_recv_message(struct ustcomm_app *app, char **msg, struct ustcomm_source *src, int timeout)
447 {
448 return ustcomm_recv_message(&app->server, msg, src, timeout);
449 }
450
451 /* This removes src from the list of active connections of app.
452 */
453
454 int ustcomm_app_detach_client(struct ustcomm_app *app, struct ustcomm_source *src)
455 {
456 struct ustcomm_server *server = (struct ustcomm_server *)app;
457 struct ustcomm_connection *conn;
458
459 list_for_each_entry(conn, &server->connections, list) {
460 if(conn->fd == src->fd) {
461 list_del(&conn->list);
462 goto found;
463 }
464 }
465
466 return -1;
467 found:
468 return src->fd;
469 }
470
471 static int init_named_socket(const char *name, char **path_out)
472 {
473 int result;
474 int fd;
475
476 struct sockaddr_un addr;
477
478 result = fd = socket(PF_UNIX, SOCK_STREAM, 0);
479 if(result == -1) {
480 PERROR("socket");
481 return -1;
482 }
483
484 addr.sun_family = AF_UNIX;
485
486 strncpy(addr.sun_path, name, UNIX_PATH_MAX);
487 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
488
489 result = access(name, F_OK);
490 if(result == 0) {
491 /* file exists */
492 result = unlink(name);
493 if(result == -1) {
494 PERROR("unlink of socket file");
495 goto close_sock;
496 }
497 WARN("socket already exists; overwriting");
498 }
499
500 result = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
501 if(result == -1) {
502 PERROR("bind");
503 goto close_sock;
504 }
505
506 result = listen(fd, 1);
507 if(result == -1) {
508 PERROR("listen");
509 goto close_sock;
510 }
511
512 if(path_out) {
513 *path_out = strdup(addr.sun_path);
514 }
515
516 return fd;
517
518 close_sock:
519 close(fd);
520
521 return -1;
522 }
523
524 /*
525 * Return value:
526 * 0: Success, but no reply because recv() returned 0
527 * 1: Success
528 * -1: Error
529 *
530 * On error, the error message is printed, except on
531 * ECONNRESET, which is normal when the application dies.
532 */
533
534 int ustcomm_send_request(struct ustcomm_connection *conn, const char *req, char **reply)
535 {
536 int result;
537
538 /* Send including the final \0 */
539 result = send_message_fd(conn->fd, req);
540 if(result != 1)
541 return result;
542
543 if(!reply)
544 return 1;
545
546 result = recv_message_conn(conn, reply);
547 if(result == -1) {
548 return -1;
549 }
550 else if(result == 0) {
551 return 0;
552 }
553
554 return 1;
555 }
556
557 int ustcomm_connect_path(const char *path, struct ustcomm_connection *conn, pid_t signalpid)
558 {
559 int fd;
560 int result;
561 struct sockaddr_un addr;
562
563 ustcomm_init_connection(conn);
564
565 result = fd = socket(PF_UNIX, SOCK_STREAM, 0);
566 if(result == -1) {
567 PERROR("socket");
568 return -1;
569 }
570
571 addr.sun_family = AF_UNIX;
572
573 result = snprintf(addr.sun_path, UNIX_PATH_MAX, "%s", path);
574 if(result >= UNIX_PATH_MAX) {
575 ERR("string overflow allocating socket name");
576 return -1;
577 }
578
579 if(signalpid >= 0) {
580 result = signal_process(signalpid);
581 if(result == -1) {
582 ERR("could not signal process");
583 return -1;
584 }
585 }
586
587 result = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
588 if(result == -1) {
589 PERROR("connect (path=%s)", path);
590 return -1;
591 }
592
593 conn->fd = fd;
594
595 return 0;
596 }
597
598 int ustcomm_disconnect(struct ustcomm_connection *conn)
599 {
600 return close(conn->fd);
601 }
602
603 int ustcomm_connect_app(pid_t pid, struct ustcomm_connection *conn)
604 {
605 int result;
606 char path[UNIX_PATH_MAX];
607
608
609 result = snprintf(path, UNIX_PATH_MAX, "%s/%d", SOCK_DIR, pid);
610 if(result >= UNIX_PATH_MAX) {
611 ERR("string overflow allocating socket name");
612 return -1;
613 }
614
615 return ustcomm_connect_path(path, conn, pid);
616 }
617
618 static int ensure_dir_exists(const char *dir)
619 {
620 struct stat st;
621 int result;
622
623 if(!strcmp(dir, ""))
624 return -1;
625
626 result = stat(dir, &st);
627 if(result == -1 && errno != ENOENT) {
628 return -1;
629 }
630 else if(result == -1) {
631 /* ENOENT */
632 int result;
633
634 result = mkdir_p(dir, 0777);
635 if(result != 0) {
636 ERR("executing in recursive creation of directory %s", dir);
637 return -1;
638 }
639 }
640
641 return 0;
642 }
643
644 /* Called by an application to initialize its server so daemons can
645 * connect to it.
646 */
647
648 int ustcomm_init_app(pid_t pid, struct ustcomm_app *handle)
649 {
650 int result;
651 char *name;
652
653 result = asprintf(&name, "%s/%d", SOCK_DIR, (int)pid);
654 if(result >= UNIX_PATH_MAX) {
655 ERR("string overflow allocating socket name");
656 return -1;
657 }
658
659 result = ensure_dir_exists(SOCK_DIR);
660 if(result == -1) {
661 ERR("Unable to create socket directory %s", SOCK_DIR);
662 return -1;
663 }
664
665 handle->server.listen_fd = init_named_socket(name, &(handle->server.socketpath));
666 if(handle->server.listen_fd < 0) {
667 ERR("Error initializing named socket (%s). Check that directory exists and that it is writable.", name);
668 goto free_name;
669 }
670 free(name);
671
672 INIT_LIST_HEAD(&handle->server.connections);
673
674 return 0;
675
676 free_name:
677 free(name);
678 return -1;
679 }
680
681 void ustcomm_free_app(struct ustcomm_app *app)
682 {
683 int result;
684 result = close(app->server.listen_fd);
685 if(result == -1) {
686 PERROR("close");
687 return;
688 }
689 }
690
691 /* Used by the daemon to initialize its server so applications
692 * can connect to it.
693 */
694
695 int ustcomm_init_ustd(struct ustcomm_ustd *handle, const char *sock_path)
696 {
697 char *name;
698 int retval = 0;
699
700 if(sock_path) {
701 asprintf(&name, "%s", sock_path);
702 }
703 else {
704 int result;
705
706 /* Only check if socket dir exists if we are using the default directory */
707 result = ensure_dir_exists(SOCK_DIR);
708 if(result == -1) {
709 ERR("Unable to create socket directory %s", SOCK_DIR);
710 return -1;
711 }
712
713 asprintf(&name, "%s/%s", SOCK_DIR, "ustd");
714 }
715
716 handle->server.listen_fd = init_named_socket(name, &handle->server.socketpath);
717 if(handle->server.listen_fd < 0) {
718 ERR("error initializing named socket at %s", name);
719 retval = -1;
720 goto free_name;
721 }
722
723 INIT_LIST_HEAD(&handle->server.connections);
724
725 free_name:
726 free(name);
727
728 return retval;
729 }
730
731 void ustcomm_fini_app(struct ustcomm_app *handle)
732 {
733 int result;
734 struct stat st;
735
736 /* Destroy socket */
737 result = stat(handle->server.socketpath, &st);
738 if(result == -1) {
739 PERROR("stat (%s)", handle->server.socketpath);
740 return;
741 }
742
743 /* Paranoid check before deleting. */
744 result = S_ISSOCK(st.st_mode);
745 if(!result) {
746 ERR("The socket we are about to delete is not a socket.");
747 return;
748 }
749
750 result = unlink(handle->server.socketpath);
751 if(result == -1) {
752 PERROR("unlink");
753 }
754 }
755
756 static const char *find_tok(const char *str)
757 {
758 while(*str == ' ') {
759 str++;
760
761 if(*str == 0)
762 return NULL;
763 }
764
765 return str;
766 }
767
768 static const char *find_sep(const char *str)
769 {
770 while(*str != ' ') {
771 str++;
772
773 if(*str == 0)
774 break;
775 }
776
777 return str;
778 }
779
780 int nth_token_is(const char *str, const char *token, int tok_no)
781 {
782 int i;
783 const char *start;
784 const char *end;
785
786 for(i=0; i<=tok_no; i++) {
787 str = find_tok(str);
788 if(str == NULL)
789 return -1;
790
791 start = str;
792
793 str = find_sep(str);
794 if(str == NULL)
795 return -1;
796
797 end = str;
798 }
799
800 if(end-start != strlen(token))
801 return 0;
802
803 if(strncmp(start, token, end-start))
804 return 0;
805
806 return 1;
807 }
808
809 char *nth_token(const char *str, int tok_no)
810 {
811 static char *retval = NULL;
812 int i;
813 const char *start;
814 const char *end;
815
816 for(i=0; i<=tok_no; i++) {
817 str = find_tok(str);
818 if(str == NULL)
819 return NULL;
820
821 start = str;
822
823 str = find_sep(str);
824 if(str == NULL)
825 return NULL;
826
827 end = str;
828 }
829
830 if(retval) {
831 free(retval);
832 retval = NULL;
833 }
834
835 asprintf(&retval, "%.*s", (int)(end-start), start);
836
837 return retval;
838 }
839
This page took 0.047901 seconds and 4 git commands to generate.