api: refactor vlibmemory
[vpp.git] / src / vlibmemory / socket_client.c
1 /*
2  *------------------------------------------------------------------
3  * socket_client.c - API message handling over sockets, client code.
4  *
5  * Copyright (c) 2017 Cisco and/or its affiliates.
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at:
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *------------------------------------------------------------------
18  */
19
20 #include <stdio.h>
21 #define __USE_GNU
22 #include <sys/socket.h>
23
24 #include <svm/memfd.h>
25 #include <vlibmemory/socket_client.h>
26 #include <vlibmemory/memory_client.h>
27
28 #include <vlibmemory/vl_memory_msg_enum.h>
29
30 #define vl_typedefs             /* define message structures */
31 #include <vlibmemory/vl_memory_api_h.h>
32 #undef vl_typedefs
33
34 #define vl_endianfun            /* define message structures */
35 #include <vlibmemory/vl_memory_api_h.h>
36 #undef vl_endianfun
37
38 /* instantiate all the print functions we know about */
39 #define vl_print(handle, ...) clib_warning (__VA_ARGS__)
40 #define vl_printfun
41 #include <vlibmemory/vl_memory_api_h.h>
42 #undef vl_printfun
43
44 socket_client_main_t socket_client_main;
45
46 /* Debug aid */
47 u32 vl (void *p) __attribute__ ((weak));
48
49 u32
50 vl (void *p)
51 {
52   return vec_len (p);
53 }
54
55 int
56 vl_socket_client_read (int wait)
57 {
58   socket_client_main_t *scm = &socket_client_main;
59   int n, current_rx_index;
60   msgbuf_t *mbp = 0;
61   f64 timeout;
62
63   if (scm->socket_fd == 0)
64     return -1;
65
66   if (wait)
67     timeout = clib_time_now (&scm->clib_time) + wait;
68
69   while (1)
70     {
71       current_rx_index = vec_len (scm->socket_rx_buffer);
72       while (vec_len (scm->socket_rx_buffer) <
73              sizeof (*mbp) + 2 /* msg id */ )
74         {
75           vec_validate (scm->socket_rx_buffer, current_rx_index
76                         + scm->socket_buffer_size - 1);
77           _vec_len (scm->socket_rx_buffer) = current_rx_index;
78           n = read (scm->socket_fd, scm->socket_rx_buffer + current_rx_index,
79                     scm->socket_buffer_size);
80           if (n < 0)
81             {
82               clib_unix_warning ("socket_read");
83               return -1;
84             }
85           _vec_len (scm->socket_rx_buffer) += n;
86         }
87
88 #if CLIB_DEBUG > 1
89       if (n > 0)
90         clib_warning ("read %d bytes", n);
91 #endif
92
93       if (mbp == 0)
94         mbp = (msgbuf_t *) (scm->socket_rx_buffer);
95
96       if (vec_len (scm->socket_rx_buffer) >= ntohl (mbp->data_len)
97           + sizeof (*mbp))
98         {
99           vl_msg_api_socket_handler ((void *) (mbp->data));
100
101           if (vec_len (scm->socket_rx_buffer) == ntohl (mbp->data_len)
102               + sizeof (*mbp))
103             _vec_len (scm->socket_rx_buffer) = 0;
104           else
105             vec_delete (scm->socket_rx_buffer, ntohl (mbp->data_len)
106                         + sizeof (*mbp), 0);
107           mbp = 0;
108
109           /* Quit if we're out of data, and not expecting a ping reply */
110           if (vec_len (scm->socket_rx_buffer) == 0
111               && scm->control_pings_outstanding == 0)
112             break;
113         }
114
115       if (wait && clib_time_now (&scm->clib_time) >= timeout)
116         return -1;
117     }
118   return 0;
119 }
120
121 int
122 vl_socket_client_write (void)
123 {
124   socket_client_main_t *scm = &socket_client_main;
125   int n;
126
127   msgbuf_t msgbuf = {
128     .q = 0,
129     .gc_mark_timestamp = 0,
130     .data_len = htonl (scm->socket_tx_nbytes),
131   };
132
133   n = write (scm->socket_fd, &msgbuf, sizeof (msgbuf));
134   if (n < sizeof (msgbuf))
135     {
136       clib_unix_warning ("socket write (msgbuf)");
137       return -1;
138     }
139
140   n = write (scm->socket_fd, scm->socket_tx_buffer, scm->socket_tx_nbytes);
141   if (n < scm->socket_tx_nbytes)
142     {
143       clib_unix_warning ("socket write (msg)");
144       return -1;
145     }
146
147   return n;
148 }
149
150 void *
151 vl_socket_client_msg_alloc (int nbytes)
152 {
153   socket_client_main.socket_tx_nbytes = nbytes;
154   return ((void *) socket_client_main.socket_tx_buffer);
155 }
156
157 void
158 vl_socket_client_disconnect (void)
159 {
160   socket_client_main_t *scm = &socket_client_main;
161   if (scm->socket_fd && (close (scm->socket_fd) < 0))
162     clib_unix_warning ("close");
163   scm->socket_fd = 0;
164 }
165
166 void
167 vl_socket_client_enable_disable (int enable)
168 {
169   socket_client_main_t *scm = &socket_client_main;
170   scm->socket_enable = enable;
171 }
172
173 static clib_error_t *
174 receive_fd_msg (int socket_fd, int *my_fd)
175 {
176   char msgbuf[16];
177   char ctl[CMSG_SPACE (sizeof (int)) + CMSG_SPACE (sizeof (struct ucred))];
178   struct msghdr mh = { 0 };
179   struct iovec iov[1];
180   ssize_t size;
181   struct ucred *cr = 0;
182   struct cmsghdr *cmsg;
183   pid_t pid __attribute__ ((unused));
184   uid_t uid __attribute__ ((unused));
185   gid_t gid __attribute__ ((unused));
186
187   iov[0].iov_base = msgbuf;
188   iov[0].iov_len = 5;
189   mh.msg_iov = iov;
190   mh.msg_iovlen = 1;
191   mh.msg_control = ctl;
192   mh.msg_controllen = sizeof (ctl);
193
194   memset (ctl, 0, sizeof (ctl));
195
196   /* receive the incoming message */
197   size = recvmsg (socket_fd, &mh, 0);
198   if (size != 5)
199     {
200       return (size == 0) ? clib_error_return (0, "disconnected") :
201         clib_error_return_unix (0, "recvmsg: malformed message (fd %d)",
202                                 socket_fd);
203     }
204
205   cmsg = CMSG_FIRSTHDR (&mh);
206   while (cmsg)
207     {
208       if (cmsg->cmsg_level == SOL_SOCKET)
209         {
210           if (cmsg->cmsg_type == SCM_CREDENTIALS)
211             {
212               cr = (struct ucred *) CMSG_DATA (cmsg);
213               uid = cr->uid;
214               gid = cr->gid;
215               pid = cr->pid;
216             }
217           else if (cmsg->cmsg_type == SCM_RIGHTS)
218             {
219               clib_memcpy (my_fd, CMSG_DATA (cmsg), sizeof (int));
220             }
221         }
222       cmsg = CMSG_NXTHDR (&mh, cmsg);
223     }
224   return 0;
225 }
226
227 static void vl_api_sock_init_shm_reply_t_handler
228   (vl_api_sock_init_shm_reply_t * mp)
229 {
230   socket_client_main_t *scm = &socket_client_main;
231   int my_fd = -1;
232   clib_error_t *error;
233   i32 retval = ntohl (mp->retval);
234   memfd_private_t memfd;
235   api_main_t *am = &api_main;
236   u8 *new_name;
237
238   if (retval)
239     {
240       clib_warning ("failed to init shmem");
241       return;
242     }
243
244   /*
245    * Check the socket for the magic fd
246    */
247   error = receive_fd_msg (scm->socket_fd, &my_fd);
248   if (error)
249     {
250       retval = -99;
251       return;
252     }
253
254   memset (&memfd, 0, sizeof (memfd));
255   memfd.fd = my_fd;
256
257   /* Note: this closes memfd.fd */
258   retval = memfd_slave_init (&memfd);
259   if (retval)
260     clib_warning ("WARNING: segment map returned %d", retval);
261
262   /*
263    * Pivot to the memory client segment that vpp just created
264    */
265   am->vlib_rp = (void *) (memfd.requested_va + MMAP_PAGESIZE);
266   am->shmem_hdr = (void *) am->vlib_rp->user_ctx;
267
268   new_name = format (0, "%v[shm]%c", scm->name, 0);
269   vl_client_install_client_message_handlers ();
270   vl_client_connect_to_vlib_no_map ("pvt", (char *) new_name,
271                                     32 /* input_queue_length */ );
272   vl_socket_client_enable_disable (0);
273   vec_free (new_name);
274 }
275
276 static void
277 vl_api_sockclnt_create_reply_t_handler (vl_api_sockclnt_create_reply_t * mp)
278 {
279   socket_client_main_t *scm = &socket_client_main;
280   if (!mp->response)
281     scm->socket_enable = 1;
282 }
283
284 #define foreach_sock_client_api_msg                             \
285 _(SOCKCLNT_CREATE_REPLY, sockclnt_create_reply)                 \
286 _(SOCK_INIT_SHM_REPLY, sock_init_shm_reply)                     \
287
288 static void
289 noop_handler (void *notused)
290 {
291 }
292
293 void
294 vl_sock_client_install_message_handlers (void)
295 {
296
297 #define _(N,n)                                                  \
298     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
299                             vl_api_##n##_t_handler,             \
300                             noop_handler,                       \
301                             vl_api_##n##_t_endian,              \
302                             vl_api_##n##_t_print,               \
303                             sizeof(vl_api_##n##_t), 1);
304   foreach_sock_client_api_msg;
305 #undef _
306 }
307
308 int
309 vl_socket_client_connect (char *socket_path, char *client_name,
310                           u32 socket_buffer_size)
311 {
312   socket_client_main_t *scm = &socket_client_main;
313   vl_api_sockclnt_create_t *mp;
314   clib_socket_t *sock;
315   clib_error_t *error;
316
317   /* Already connected? */
318   if (scm->socket_fd)
319     return (-2);
320
321   /* bogus call? */
322   if (socket_path == 0 || client_name == 0)
323     return (-3);
324
325   sock = &scm->client_socket;
326   sock->config = socket_path;
327   sock->flags = CLIB_SOCKET_F_IS_CLIENT | CLIB_SOCKET_F_SEQPACKET;
328
329   if ((error = clib_socket_init (sock)))
330     {
331       clib_error_report (error);
332       return (-1);
333     }
334
335   vl_sock_client_install_message_handlers ();
336
337   scm->socket_fd = sock->fd;
338   scm->socket_buffer_size = socket_buffer_size ? socket_buffer_size :
339     SOCKET_CLIENT_DEFAULT_BUFFER_SIZE;
340   vec_validate (scm->socket_tx_buffer, scm->socket_buffer_size - 1);
341   vec_validate (scm->socket_rx_buffer, scm->socket_buffer_size - 1);
342   _vec_len (scm->socket_rx_buffer) = 0;
343   _vec_len (scm->socket_tx_buffer) = 0;
344   scm->name = format (0, "%s", client_name);
345
346   mp = vl_socket_client_msg_alloc (sizeof (*mp));
347   mp->_vl_msg_id = htons (VL_API_SOCKCLNT_CREATE);
348   strncpy ((char *) mp->name, client_name, sizeof (mp->name) - 1);
349   mp->name[sizeof (mp->name) - 1] = 0;
350   mp->context = 0xfeedface;
351
352   if (vl_socket_client_write () <= 0)
353     return (-1);
354
355   if (vl_socket_client_read (1))
356     return (-1);
357
358   clib_time_init (&scm->clib_time);
359   return (0);
360 }
361
362 int
363 vl_socket_client_init_shm (vl_api_shm_elem_config_t * config)
364 {
365   vl_api_sock_init_shm_t *mp;
366   int rv, i;
367   u64 *cfg;
368
369   mp = vl_socket_client_msg_alloc (sizeof (*mp) +
370                                    vec_len (config) * sizeof (u64));
371   memset (mp, 0, sizeof (*mp));
372   mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_SOCK_INIT_SHM);
373   mp->client_index = ~0;
374   mp->requested_size = 64 << 20;
375
376   if (config)
377     {
378       for (i = 0; i < vec_len (config); i++)
379         {
380           cfg = (u64 *) & config[i];
381           mp->configs[i] = *cfg;
382         }
383       mp->nitems = vec_len (config);
384     }
385   rv = vl_socket_client_write ();
386   if (rv <= 0)
387     return rv;
388
389   if (vl_socket_client_read (1))
390     return -1;
391
392   return 0;
393 }
394
395 /*
396  * fd.io coding-style-patch-verification: ON
397  *
398  * Local Variables:
399  * eval: (c-set-style "gnu")
400  * End:
401  */