First steps toward actually handling monitoring requests
[trust_router.git] / mon / mons.c
1 /*
2  * Copyright (c) 2018, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <talloc.h>
36 #include <fcntl.h>
37 #include <unistd.h>
38 #include <netdb.h>
39
40 #include <tr.h>
41 #include <tr_debug.h>
42 #include <mon_internal.h>
43 #include <tr_socket.h>
44 #include <sys/wait.h>
45 #include <tr_gss.h>
46
47 #include "mons_handlers.h"
48
49 /**
50  * Allocate a new MONS_INSTANCE
51  *
52  * @param mem_ctx talloc context for allocation
53  * @return new MONS_INSTANCE or null on failure
54  */
55 MONS_INSTANCE *mons_new(TALLOC_CTX *mem_ctx)
56 {
57   MONS_INSTANCE *mons = talloc(mem_ctx, MONS_INSTANCE);
58
59   if (mons) {
60     mons->hostname = NULL;
61     mons->port = 0;
62     mons->tids = NULL;
63     mons->trps = NULL;
64     mons->req_handler = NULL;
65     mons->auth_handler = NULL;
66     mons->cookie = NULL;
67     mons->authorized_gss_names = tr_gss_names_new(mons);
68     if (mons->authorized_gss_names == NULL) {
69       talloc_free(mons);
70       mons = NULL;
71     }
72   }
73   return mons;
74 }
75
76 /**
77  * Callback to process a request and produce a response
78  *
79  * @param req_str JSON-encoded request
80  * @param data pointer to a MONS_INSTANCE
81  * @return pointer to the response string or null to send no response
82  */
83 static TR_MSG *mons_req_cb(TALLOC_CTX *mem_ctx, TR_MSG *req_msg, void *data)
84 {
85   TALLOC_CTX *tmp_ctx = talloc_new(NULL);
86   MONS_INSTANCE *mons = talloc_get_type_abort(data, MONS_INSTANCE);
87   MON_REQ *req = NULL;
88   MON_RESP *resp = NULL;
89   TR_MSG *resp_msg = NULL; /* This is the response value */
90
91   /* Validate inputs */
92   if (req_msg == NULL)
93     goto cleanup;
94
95   req = tr_msg_get_mon_req(req_msg);
96   if (req == NULL) {
97     /* this is an internal error */
98     tr_err("mons_req_cb: Received incorrect message type (was %d, expected %d)",
99            tr_msg_get_msg_type(req_msg),
100            MON_REQUEST);
101     /* TODO send an error response */
102     goto cleanup;
103   }
104
105   /* Allocate a response message */
106   resp_msg = talloc(tmp_ctx, TR_MSG);
107   if (resp_msg == NULL) {
108     /* can't return a message, just emit an error */
109     tr_crit("mons_req_cb: Error allocating response message.");
110     goto cleanup;
111   }
112
113   /* Handle the request */
114   resp = mons_handle_request(resp_msg, mons, req);
115   if (resp == NULL) {
116     /* error processing the request */
117     /* TODO send back an error */
118     goto cleanup;
119   }
120
121   /* Set the response message payload */
122   tr_msg_set_mon_resp(resp_msg, resp);
123
124   /* Put the response message in the caller's context so it does not get freed when we exit */
125   talloc_steal(mem_ctx, resp_msg);
126
127 cleanup:
128   talloc_free(tmp_ctx);
129   return resp_msg;
130 }
131
132 /**
133  * Create a listener for monitoring requests
134  *
135  * Accept connections with mons_accept()
136  *
137  * @param mons monitoring server instance
138  * @param req_handler
139  * @param auth_handler
140  * @param hostname
141  * @param port
142  * @param cookie
143  * @param fd_out
144  * @param max_fd
145  * @return
146  */
147 int mons_get_listener(MONS_INSTANCE *mons, MONS_REQ_FUNC *req_handler, MONS_AUTH_FUNC *auth_handler, const char *hostname,
148                       unsigned int port, void *cookie, int *fd_out, size_t max_fd)
149 {
150   size_t n_fd=0;
151   size_t ii=0;
152
153   mons->port = port;
154   n_fd = tr_sock_listen_all(port, fd_out, max_fd);
155   if (n_fd<=0)
156     tr_err("mons_get_listener: Error opening port %d");
157   else {
158     /* opening port succeeded */
159     tr_info("mons_get_listener: Opened port %d.", port);
160
161     /* make this socket non-blocking */
162     for (ii=0; ii<n_fd; ii++) {
163       if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
164         tr_err("mons_get_listener: Error setting O_NONBLOCK.");
165         for (ii=0; ii<n_fd; ii++) {
166           close(fd_out[ii]);
167           fd_out[ii]=-1;
168         }
169         n_fd=0;
170         break;
171       }
172     }
173   }
174
175   if (n_fd>0) {
176     /* store the caller's request handler & cookie */
177     mons->req_handler = req_handler;
178     mons->auth_handler = auth_handler;
179     mons->hostname = hostname;
180     mons->cookie = cookie;
181   }
182
183   return (int) n_fd;
184 }
185
186 /**
187  * Accept and process a connection on a port opened with mons_get_listener()
188  *
189  * @param mons monitoring interface instance
190  * @param listen FD of the connection socket
191  * @return 0 on success
192  */
193 int mons_accept(MONS_INSTANCE *mons, int listen)
194 {
195   int conn=-1;
196   int pid=-1;
197
198   if (0 > (conn = accept(listen, NULL, NULL))) {
199     perror("Error from monitoring interface accept()");
200     return 1;
201   }
202
203   if (0 > (pid = fork())) {
204     perror("Error on fork()");
205     return 1;
206   }
207
208   if (pid == 0) {
209     close(listen);
210     tr_gss_handle_connection(conn,
211                              "trustmonitor", mons->hostname, /* acceptor name */
212                              mons->auth_handler, mons->cookie, /* auth callback and cookie */
213                              mons_req_cb, mons /* req callback and cookie */
214     );
215     close(conn);
216     exit(0); /* exit to kill forked child process */
217   } else {
218     close(conn);
219   }
220
221   /* clean up any processes that have completed */
222   while (waitpid(-1, 0, WNOHANG) > 0);
223
224   return 0;
225 }