api: keep AddressSanitizer happy
[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 #define _GNU_SOURCE
23 #include <sys/socket.h>
24
25 #include <svm/ssvm.h>
26 #include <vlibmemory/socket_client.h>
27 #include <vlibmemory/memory_client.h>
28
29 #include <vlibmemory/vl_memory_msg_enum.h>
30
31 #define vl_typedefs             /* define message structures */
32 #include <vlibmemory/vl_memory_api_h.h>
33 #undef vl_typedefs
34
35 #define vl_endianfun            /* define message structures */
36 #include <vlibmemory/vl_memory_api_h.h>
37 #undef vl_endianfun
38
39 #define vl_calcsizefun
40 #include <vlibmemory/vl_memory_api_h.h>
41 #undef vl_calcsizefun
42
43 /* instantiate all the print functions we know about */
44 #define vl_printfun
45 #include <vlibmemory/vl_memory_api_h.h>
46 #undef vl_printfun
47
48 socket_client_main_t socket_client_main;
49 __thread socket_client_main_t *socket_client_ctx = &socket_client_main;
50
51 /* Debug aid */
52 u32 vl (void *p) __attribute__ ((weak));
53
54 u32
55 vl (void *p)
56 {
57   return vec_len (p);
58 }
59
60 static socket_client_main_t *
61 vl_socket_client_ctx_push (socket_client_main_t * ctx)
62 {
63   socket_client_main_t *old = socket_client_ctx;
64   socket_client_ctx = ctx;
65   return old;
66 }
67
68 static void
69 vl_socket_client_ctx_pop (socket_client_main_t * old_ctx)
70 {
71   socket_client_ctx = old_ctx;
72 }
73
74 static int
75 vl_socket_client_read_internal (socket_client_main_t * scm, int wait)
76 {
77   u32 data_len = 0, msg_size;
78   int n, current_rx_index;
79   msgbuf_t *mbp = 0;
80   f64 timeout;
81
82   if (scm->socket_fd == 0)
83     return -1;
84
85   if (wait)
86     timeout = clib_time_now (&scm->clib_time) + wait;
87
88   while (1)
89     {
90       while (vec_len (scm->socket_rx_buffer) < sizeof (*mbp))
91         {
92           current_rx_index = vec_len (scm->socket_rx_buffer);
93           vec_validate (scm->socket_rx_buffer, current_rx_index
94                         + scm->socket_buffer_size - 1);
95           vec_set_len (scm->socket_rx_buffer, current_rx_index);
96           n = read (scm->socket_fd, scm->socket_rx_buffer + current_rx_index,
97                     scm->socket_buffer_size);
98           if (n < 0)
99             {
100               if (errno == EAGAIN)
101                 continue;
102
103               clib_unix_warning ("socket_read");
104               return -1;
105             }
106           vec_inc_len (scm->socket_rx_buffer, n);
107         }
108
109 #if CLIB_DEBUG > 1
110       if (n > 0)
111         clib_warning ("read %d bytes", n);
112 #endif
113
114       mbp = (msgbuf_t *) (scm->socket_rx_buffer);
115       data_len = ntohl (mbp->data_len);
116       current_rx_index = vec_len (scm->socket_rx_buffer);
117       vec_validate (scm->socket_rx_buffer, current_rx_index + data_len);
118       vec_set_len (scm->socket_rx_buffer, current_rx_index);
119       mbp = (msgbuf_t *) (scm->socket_rx_buffer);
120       msg_size = data_len + sizeof (*mbp);
121
122       while (vec_len (scm->socket_rx_buffer) < msg_size)
123         {
124           n = read (scm->socket_fd,
125                     scm->socket_rx_buffer + vec_len (scm->socket_rx_buffer),
126                     msg_size - vec_len (scm->socket_rx_buffer));
127           if (n < 0)
128             {
129               if (errno == EAGAIN)
130                 continue;
131
132               clib_unix_warning ("socket_read");
133               return -1;
134             }
135           vec_inc_len (scm->socket_rx_buffer, n);
136         }
137
138       if (vec_len (scm->socket_rx_buffer) >= data_len + sizeof (*mbp))
139         {
140           vl_msg_api_socket_handler ((void *) (mbp->data), data_len);
141
142           if (vec_len (scm->socket_rx_buffer) == data_len + sizeof (*mbp))
143             vec_set_len (scm->socket_rx_buffer, 0);
144           else
145             vec_delete (scm->socket_rx_buffer, data_len + sizeof (*mbp), 0);
146           mbp = 0;
147
148           /* Quit if we're out of data, and not expecting a ping reply */
149           if (vec_len (scm->socket_rx_buffer) == 0
150               && scm->control_pings_outstanding == 0)
151             break;
152         }
153       if (wait && clib_time_now (&scm->clib_time) >= timeout)
154         return -1;
155     }
156   return 0;
157 }
158
159 int
160 vl_socket_client_read (int wait)
161 {
162   return vl_socket_client_read_internal (socket_client_ctx, wait);
163 }
164
165 int
166 vl_socket_client_read2 (socket_client_main_t * scm, int wait)
167 {
168   socket_client_main_t *old_ctx;
169   int rv;
170
171   old_ctx = vl_socket_client_ctx_push (scm);
172   rv = vl_socket_client_read_internal (scm, wait);
173   vl_socket_client_ctx_pop (old_ctx);
174   return rv;
175 }
176
177 static int
178 vl_socket_client_write_internal (socket_client_main_t * scm)
179 {
180   int n;
181   int len = vec_len (scm->socket_tx_buffer);
182   msgbuf_t msgbuf = {
183     .q = 0,
184     .gc_mark_timestamp = 0,
185     .data_len = htonl (len),
186   };
187
188   n = write (scm->socket_fd, &msgbuf, sizeof (msgbuf));
189   if (n < sizeof (msgbuf))
190     {
191       clib_unix_warning ("socket write (msgbuf)");
192       return -1;
193     }
194
195   n = write (scm->socket_fd, scm->socket_tx_buffer, len);
196
197   vec_set_len (scm->socket_tx_buffer, 0);
198
199   if (n < len)
200     {
201       clib_unix_warning ("socket write (msg)");
202       return -1;
203     }
204
205   return n;
206 }
207
208 int
209 vl_socket_client_write (void)
210 {
211   return vl_socket_client_write_internal (socket_client_ctx);
212 }
213
214 int
215 vl_socket_client_write2 (socket_client_main_t * scm)
216 {
217   socket_client_main_t *old_ctx;
218   int rv;
219
220   old_ctx = vl_socket_client_ctx_push (scm);
221   rv = vl_socket_client_write_internal (scm);
222   vl_socket_client_ctx_pop (old_ctx);
223   return rv;
224 }
225
226 void *
227 vl_socket_client_msg_alloc2 (socket_client_main_t * scm, int nbytes)
228 {
229   vec_set_len (scm->socket_tx_buffer, nbytes);
230   return ((void *) scm->socket_tx_buffer);
231 }
232
233 void *
234 vl_socket_client_msg_alloc (int nbytes)
235 {
236   return vl_socket_client_msg_alloc2 (socket_client_ctx, nbytes);
237 }
238
239 void
240 vl_socket_client_disconnect2 (socket_client_main_t * scm)
241 {
242   if (vl_mem_client_is_connected ())
243     {
244       vl_client_disconnect_from_vlib_no_unmap ();
245       ssvm_delete_memfd (&scm->memfd_segment);
246     }
247   if (scm->socket_fd && (close (scm->socket_fd) < 0))
248     clib_unix_warning ("close");
249   scm->socket_fd = 0;
250 }
251
252 void
253 vl_socket_client_disconnect (void)
254 {
255   vl_socket_client_disconnect2 (socket_client_ctx);
256 }
257
258 void
259 vl_socket_client_enable_disable2 (socket_client_main_t * scm, int enable)
260 {
261   scm->socket_enable = enable;
262 }
263
264 void
265 vl_socket_client_enable_disable (int enable)
266 {
267   vl_socket_client_enable_disable2 (socket_client_ctx, enable);
268 }
269
270 static clib_error_t *
271 vl_sock_api_recv_fd_msg_internal (socket_client_main_t * scm, int fds[],
272                                   int n_fds, u32 wait)
273 {
274   char msgbuf[16];
275   char ctl[CMSG_SPACE (sizeof (int) * n_fds)
276            + CMSG_SPACE (sizeof (struct ucred))];
277   struct msghdr mh = { 0 };
278   struct iovec iov[1];
279   ssize_t size = 0;
280   struct ucred *cr = 0;
281   struct cmsghdr *cmsg;
282   pid_t pid __attribute__ ((unused));
283   uid_t uid __attribute__ ((unused));
284   gid_t gid __attribute__ ((unused));
285   int socket_fd;
286   f64 timeout;
287
288   socket_fd = scm->client_socket.fd;
289
290   iov[0].iov_base = msgbuf;
291   iov[0].iov_len = 5;
292   mh.msg_iov = iov;
293   mh.msg_iovlen = 1;
294   mh.msg_control = ctl;
295   mh.msg_controllen = sizeof (ctl);
296
297   clib_memset (ctl, 0, sizeof (ctl));
298
299   if (wait != ~0)
300     {
301       timeout = clib_time_now (&scm->clib_time) + wait;
302       while (size != 5 && clib_time_now (&scm->clib_time) < timeout)
303         size = recvmsg (socket_fd, &mh, MSG_DONTWAIT);
304     }
305   else
306     size = recvmsg (socket_fd, &mh, 0);
307
308   if (size != 5)
309     {
310       return (size == 0) ? clib_error_return (0, "disconnected") :
311         clib_error_return_unix (0, "recvmsg: malformed message (fd %d)",
312                                 socket_fd);
313     }
314
315   cmsg = CMSG_FIRSTHDR (&mh);
316   while (cmsg)
317     {
318       if (cmsg->cmsg_level == SOL_SOCKET)
319         {
320           if (cmsg->cmsg_type == SCM_CREDENTIALS)
321             {
322               cr = (struct ucred *) CMSG_DATA (cmsg);
323               uid = cr->uid;
324               gid = cr->gid;
325               pid = cr->pid;
326             }
327           else if (cmsg->cmsg_type == SCM_RIGHTS)
328             {
329               clib_memcpy_fast (fds, CMSG_DATA (cmsg), sizeof (int) * n_fds);
330             }
331         }
332       cmsg = CMSG_NXTHDR (&mh, cmsg);
333     }
334   return 0;
335 }
336
337 clib_error_t *
338 vl_sock_api_recv_fd_msg (int socket_fd, int fds[], int n_fds, u32 wait)
339 {
340   return vl_sock_api_recv_fd_msg_internal (socket_client_ctx, fds, n_fds,
341                                            wait);
342 }
343
344 clib_error_t *
345 vl_sock_api_recv_fd_msg2 (socket_client_main_t * scm, int socket_fd,
346                           int fds[], int n_fds, u32 wait)
347 {
348   socket_client_main_t *old_ctx;
349   clib_error_t *error;
350
351   old_ctx = vl_socket_client_ctx_push (scm);
352   error = vl_sock_api_recv_fd_msg_internal (scm, fds, n_fds, wait);
353   vl_socket_client_ctx_pop (old_ctx);
354   return error;
355 }
356
357 static void vl_api_sock_init_shm_reply_t_handler
358   (vl_api_sock_init_shm_reply_t * mp)
359 {
360   socket_client_main_t *scm = socket_client_ctx;
361   ssvm_private_t *memfd = &scm->memfd_segment;
362   i32 retval = ntohl (mp->retval);
363   api_main_t *am = vlibapi_get_main ();
364   clib_error_t *error;
365   int my_fd = -1;
366   u8 *new_name;
367
368   if (retval)
369     {
370       clib_warning ("failed to init shmem");
371       return;
372     }
373
374   /*
375    * Check the socket for the magic fd
376    */
377   error = vl_sock_api_recv_fd_msg (scm->socket_fd, &my_fd, 1, 5);
378   if (error)
379     {
380       clib_error_report (error);
381       retval = -99;
382       return;
383     }
384
385   clib_memset (memfd, 0, sizeof (*memfd));
386   memfd->fd = my_fd;
387
388   /* Note: this closes memfd.fd */
389   retval = ssvm_client_init_memfd (memfd);
390   if (retval)
391     clib_warning ("WARNING: segment map returned %d", retval);
392
393   /*
394    * Pivot to the memory client segment that vpp just created
395    */
396   am->vlib_rp = (void *) (memfd->requested_va + MMAP_PAGESIZE);
397   am->shmem_hdr = (void *) am->vlib_rp->user_ctx;
398
399   new_name = format (0, "%v[shm]%c", scm->name, 0);
400   vl_client_install_client_message_handlers ();
401   if (scm->want_shm_pthread)
402     {
403       vl_client_connect_to_vlib_no_map ("pvt", (char *) new_name,
404                                         32 /* input_queue_length */ );
405     }
406   else
407     {
408       vl_client_connect_to_vlib_no_rx_pthread_no_map ("pvt",
409                                                       (char *) new_name, 32
410                                                       /* input_queue_length */
411         );
412     }
413   vl_socket_client_enable_disable (0);
414   vec_free (new_name);
415 }
416
417 static void
418 vl_api_sockclnt_create_reply_t_handler (vl_api_sockclnt_create_reply_t * mp)
419 {
420   socket_client_main_t *scm = socket_client_ctx;
421   if (!mp->response)
422     {
423       scm->socket_enable = 1;
424       scm->client_index = clib_net_to_host_u32 (mp->index);
425     }
426 }
427
428 #define foreach_sock_client_api_msg                             \
429 _(SOCKCLNT_CREATE_REPLY, sockclnt_create_reply)                 \
430 _(SOCK_INIT_SHM_REPLY, sock_init_shm_reply)                     \
431
432 void
433 vl_sock_client_install_message_handlers (void)
434 {
435
436 #define _(N, n)                                                               \
437   vl_msg_api_config (&(vl_msg_api_msg_config_t){                              \
438     .id = VL_API_##N,                                                         \
439     .name = #n,                                                               \
440     .handler = vl_api_##n##_t_handler,                                        \
441     .endian = vl_api_##n##_t_endian,                                          \
442     .format_fn = vl_api_##n##_t_format,                                       \
443     .size = sizeof (vl_api_##n##_t),                                          \
444     .traced = 0,                                                              \
445     .tojson = vl_api_##n##_t_tojson,                                          \
446     .fromjson = vl_api_##n##_t_fromjson,                                      \
447     .calc_size = vl_api_##n##_t_calc_size,                                    \
448   });
449   foreach_sock_client_api_msg;
450 #undef _
451 }
452
453 int
454 vl_socket_client_connect_internal (socket_client_main_t * scm,
455                                    char *socket_path, char *client_name,
456                                    u32 socket_buffer_size)
457 {
458   vl_api_sockclnt_create_t *mp;
459   clib_socket_t *sock;
460   clib_error_t *error;
461
462   /* Already connected? */
463   if (scm->socket_fd)
464     return (-2);
465
466   /* bogus call? */
467   if (socket_path == 0 || client_name == 0)
468     return (-3);
469
470   sock = &scm->client_socket;
471   sock->config = socket_path;
472   sock->flags = CLIB_SOCKET_F_IS_CLIENT;
473
474   if ((error = clib_socket_init (sock)))
475     {
476       clib_error_report (error);
477       return (-1);
478     }
479
480   vl_sock_client_install_message_handlers ();
481
482   scm->socket_fd = sock->fd;
483   scm->socket_buffer_size = socket_buffer_size ? socket_buffer_size :
484     SOCKET_CLIENT_DEFAULT_BUFFER_SIZE;
485   vec_validate (scm->socket_tx_buffer, scm->socket_buffer_size - 1);
486   vec_validate (scm->socket_rx_buffer, scm->socket_buffer_size - 1);
487   vec_set_len (scm->socket_rx_buffer, 0);
488   vec_set_len (scm->socket_tx_buffer, 0);
489   scm->name = format (0, "%s", client_name);
490
491   mp = vl_socket_client_msg_alloc2 (scm, sizeof (*mp));
492   mp->_vl_msg_id = htons (VL_API_SOCKCLNT_CREATE);
493   strncpy ((char *) mp->name, client_name, sizeof (mp->name) - 1);
494   mp->name[sizeof (mp->name) - 1] = 0;
495   mp->context = 0xfeedface;
496
497   clib_time_init (&scm->clib_time);
498
499   if (vl_socket_client_write_internal (scm) <= 0)
500     return (-1);
501
502   if (vl_socket_client_read_internal (scm, 5))
503     return (-1);
504
505   return (0);
506 }
507
508 int
509 vl_socket_client_connect (char *socket_path, char *client_name,
510                           u32 socket_buffer_size)
511 {
512   return vl_socket_client_connect_internal (socket_client_ctx, socket_path,
513                                             client_name, socket_buffer_size);
514 }
515
516 int
517 vl_socket_client_connect2 (socket_client_main_t * scm, char *socket_path,
518                            char *client_name, u32 socket_buffer_size)
519 {
520   socket_client_main_t *old_ctx;
521   int rv;
522
523   old_ctx = vl_socket_client_ctx_push (scm);
524   rv = vl_socket_client_connect_internal (socket_client_ctx, socket_path,
525                                           client_name, socket_buffer_size);
526   vl_socket_client_ctx_pop (old_ctx);
527   return rv;
528 }
529
530 int
531 vl_socket_client_init_shm_internal (socket_client_main_t * scm,
532                                     vl_api_shm_elem_config_t * config,
533                                     int want_pthread)
534 {
535   vl_api_sock_init_shm_t *mp;
536   int rv, i;
537   u64 *cfg;
538
539   scm->want_shm_pthread = want_pthread;
540
541   mp = vl_socket_client_msg_alloc2 (scm, sizeof (*mp) +
542                                     vec_len (config) * sizeof (u64));
543   clib_memset (mp, 0, sizeof (*mp));
544   mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_SOCK_INIT_SHM);
545   mp->client_index = clib_host_to_net_u32 (scm->client_index);
546   mp->requested_size = 64 << 20;
547
548   if (config)
549     {
550       for (i = 0; i < vec_len (config); i++)
551         {
552           cfg = (u64 *) & config[i];
553           mp->configs[i] = *cfg;
554         }
555       mp->nitems = vec_len (config);
556     }
557   rv = vl_socket_client_write_internal (scm);
558   if (rv <= 0)
559     return rv;
560
561   if (vl_socket_client_read_internal (scm, 1))
562     return -1;
563
564   return 0;
565 }
566
567 int
568 vl_socket_client_init_shm (vl_api_shm_elem_config_t * config,
569                            int want_pthread)
570 {
571   return vl_socket_client_init_shm_internal (socket_client_ctx, config,
572                                              want_pthread);
573 }
574
575 int
576 vl_socket_client_init_shm2 (socket_client_main_t * scm,
577                             vl_api_shm_elem_config_t * config,
578                             int want_pthread)
579 {
580   socket_client_main_t *old_ctx;
581   int rv;
582
583   old_ctx = vl_socket_client_ctx_push (scm);
584   rv = vl_socket_client_init_shm_internal (socket_client_ctx, config,
585                                            want_pthread);
586   vl_socket_client_ctx_pop (old_ctx);
587   return rv;
588 }
589
590 clib_error_t *
591 vl_socket_client_recv_fd_msg2 (socket_client_main_t * scm, int fds[],
592                                int n_fds, u32 wait)
593 {
594   if (!scm->socket_fd)
595     return clib_error_return (0, "no socket");
596   return vl_sock_api_recv_fd_msg_internal (scm, fds, n_fds, wait);
597 }
598
599 clib_error_t *
600 vl_socket_client_recv_fd_msg (int fds[], int n_fds, u32 wait)
601 {
602   return vl_socket_client_recv_fd_msg2 (socket_client_ctx, fds, n_fds, wait);
603 }
604
605 /*
606  * fd.io coding-style-patch-verification: ON
607  *
608  * Local Variables:
609  * eval: (c-set-style "gnu")
610  * End:
611  */