c11 safe string handling support
[vpp.git] / src / vpp-api / vapi / vapi.c
1 /*
2  *------------------------------------------------------------------
3  * Copyright (c) 2017 Cisco and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *------------------------------------------------------------------
16  */
17
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <stdint.h>
21 #include <arpa/inet.h>
22 #include <stddef.h>
23 #include <assert.h>
24
25 #include <vpp-api/vapi/vapi_dbg.h>
26 #include <vpp-api/vapi/vapi.h>
27 #include <vpp-api/vapi/vapi_internal.h>
28 #include <vppinfra/types.h>
29 #include <vppinfra/pool.h>
30 #include <vlib/vlib.h>
31 #include <vlibapi/api_common.h>
32 #include <vlibmemory/memory_client.h>
33
34 #include <vapi/memclnt.api.vapi.h>
35
36 /* we need to use control pings for some stuff and because we're forced to put
37  * the code in headers, we need a way to be able to grab the ids of these
38  * messages - so declare them here as extern */
39 vapi_msg_id_t vapi_msg_id_control_ping = 0;
40 vapi_msg_id_t vapi_msg_id_control_ping_reply = 0;
41
42 DEFINE_VAPI_MSG_IDS_MEMCLNT_API_JSON;
43
44 struct
45 {
46   size_t count;
47   vapi_message_desc_t **msgs;
48   size_t max_len_name_with_crc;
49 } __vapi_metadata;
50
51 typedef struct
52 {
53   u32 context;
54   vapi_cb_t callback;
55   void *callback_ctx;
56   bool is_dump;
57 } vapi_req_t;
58
59 static const u32 context_counter_mask = (1 << 31);
60
61 typedef struct
62 {
63   vapi_error_e (*cb) (vapi_ctx_t ctx, void *callback_ctx, vapi_msg_id_t id,
64                       void *payload);
65   void *ctx;
66 } vapi_generic_cb_with_ctx;
67
68 typedef struct
69 {
70   vapi_error_e (*cb) (vapi_ctx_t ctx, void *callback_ctx, void *payload);
71   void *ctx;
72 } vapi_event_cb_with_ctx;
73
74 struct vapi_ctx_s
75 {
76   vapi_mode_e mode;
77   int requests_size;            /* size of the requests array (circular queue) */
78   int requests_start;           /* index of first request */
79   int requests_count;           /* number of used slots */
80   vapi_req_t *requests;
81   u32 context_counter;
82   vapi_generic_cb_with_ctx generic_cb;
83   vapi_event_cb_with_ctx *event_cbs;
84   u16 *vapi_msg_id_t_to_vl_msg_id;
85   u16 vl_msg_id_max;
86   vapi_msg_id_t *vl_msg_id_to_vapi_msg_t;
87   bool connected;
88   bool handle_keepalives;
89   pthread_mutex_t requests_mutex;
90 };
91
92 u32
93 vapi_gen_req_context (vapi_ctx_t ctx)
94 {
95   ++ctx->context_counter;
96   ctx->context_counter %= context_counter_mask;
97   return ctx->context_counter | context_counter_mask;
98 }
99
100 size_t
101 vapi_get_request_count (vapi_ctx_t ctx)
102 {
103   return ctx->requests_count;
104 }
105
106 bool
107 vapi_requests_full (vapi_ctx_t ctx)
108 {
109   return (ctx->requests_count == ctx->requests_size);
110 }
111
112 bool
113 vapi_requests_empty (vapi_ctx_t ctx)
114 {
115   return (0 == ctx->requests_count);
116 }
117
118 static int
119 vapi_requests_end (vapi_ctx_t ctx)
120 {
121   return (ctx->requests_start + ctx->requests_count) % ctx->requests_size;
122 }
123
124 void
125 vapi_store_request (vapi_ctx_t ctx, u32 context, bool is_dump,
126                     vapi_cb_t callback, void *callback_ctx)
127 {
128   assert (!vapi_requests_full (ctx));
129   /* if the mutex is not held, bad things will happen */
130   assert (0 != pthread_mutex_trylock (&ctx->requests_mutex));
131   const int requests_end = vapi_requests_end (ctx);
132   vapi_req_t *slot = &ctx->requests[requests_end];
133   slot->is_dump = is_dump;
134   slot->context = context;
135   slot->callback = callback;
136   slot->callback_ctx = callback_ctx;
137   VAPI_DBG ("stored@%d: context:%x (start is @%d)", requests_end, context,
138             ctx->requests_start);
139   ++ctx->requests_count;
140   assert (!vapi_requests_empty (ctx));
141 }
142
143 #if VAPI_DEBUG_ALLOC
144 struct to_be_freed_s;
145 struct to_be_freed_s
146 {
147   void *v;
148   struct to_be_freed_s *next;
149 };
150
151 static struct to_be_freed_s *to_be_freed = NULL;
152
153 void
154 vapi_add_to_be_freed (void *v)
155 {
156   struct to_be_freed_s *prev = NULL;
157   struct to_be_freed_s *tmp;
158   tmp = to_be_freed;
159   while (tmp && tmp->v)
160     {
161       prev = tmp;
162       tmp = tmp->next;
163     }
164   if (!tmp)
165     {
166       if (!prev)
167         {
168           tmp = to_be_freed = calloc (1, sizeof (*to_be_freed));
169         }
170       else
171         {
172           tmp = prev->next = calloc (1, sizeof (*to_be_freed));
173         }
174     }
175   VAPI_DBG ("To be freed %p", v);
176   tmp->v = v;
177 }
178
179 void
180 vapi_trace_free (void *v)
181 {
182   struct to_be_freed_s *tmp = to_be_freed;
183   while (tmp && tmp->v != v)
184     {
185       tmp = tmp->next;
186     }
187   if (tmp && tmp->v == v)
188     {
189       VAPI_DBG ("Freed %p", v);
190       tmp->v = NULL;
191     }
192   else
193     {
194       VAPI_ERR ("Trying to free untracked pointer %p", v);
195       abort ();
196     }
197 }
198
199 void
200 vapi_to_be_freed_validate ()
201 {
202   struct to_be_freed_s *tmp = to_be_freed;
203   while (tmp)
204     {
205       if (tmp->v)
206         {
207           VAPI_ERR ("Unfreed msg %p!", tmp->v);
208         }
209       tmp = tmp->next;
210     }
211 }
212
213 #endif
214
215 void *
216 vapi_msg_alloc (vapi_ctx_t ctx, size_t size)
217 {
218   if (!ctx->connected)
219     {
220       return NULL;
221     }
222   void *rv = vl_msg_api_alloc_or_null (size);
223   return rv;
224 }
225
226 void
227 vapi_msg_free (vapi_ctx_t ctx, void *msg)
228 {
229   if (!ctx->connected)
230     {
231       return;
232     }
233 #if VAPI_DEBUG_ALLOC
234   vapi_trace_free (msg);
235 #endif
236   vl_msg_api_free (msg);
237 }
238
239 vapi_msg_id_t
240 vapi_lookup_vapi_msg_id_t (vapi_ctx_t ctx, u16 vl_msg_id)
241 {
242   if (vl_msg_id <= ctx->vl_msg_id_max)
243     {
244       return ctx->vl_msg_id_to_vapi_msg_t[vl_msg_id];
245     }
246   return VAPI_INVALID_MSG_ID;
247 }
248
249 vapi_error_e
250 vapi_ctx_alloc (vapi_ctx_t * result)
251 {
252   vapi_ctx_t ctx = calloc (1, sizeof (struct vapi_ctx_s));
253   if (!ctx)
254     {
255       return VAPI_ENOMEM;
256     }
257   ctx->context_counter = 0;
258   ctx->vapi_msg_id_t_to_vl_msg_id =
259     malloc (__vapi_metadata.count *
260             sizeof (*ctx->vapi_msg_id_t_to_vl_msg_id));
261   if (!ctx->vapi_msg_id_t_to_vl_msg_id)
262     {
263       goto fail;
264     }
265   clib_memset (ctx->vapi_msg_id_t_to_vl_msg_id, ~0,
266                __vapi_metadata.count *
267                sizeof (*ctx->vapi_msg_id_t_to_vl_msg_id));
268   ctx->event_cbs = calloc (__vapi_metadata.count, sizeof (*ctx->event_cbs));
269   if (!ctx->event_cbs)
270     {
271       goto fail;
272     }
273   pthread_mutex_init (&ctx->requests_mutex, NULL);
274   *result = ctx;
275   return VAPI_OK;
276 fail:
277   vapi_ctx_free (ctx);
278   return VAPI_ENOMEM;
279 }
280
281 void
282 vapi_ctx_free (vapi_ctx_t ctx)
283 {
284   assert (!ctx->connected);
285   free (ctx->requests);
286   free (ctx->vapi_msg_id_t_to_vl_msg_id);
287   free (ctx->event_cbs);
288   free (ctx->vl_msg_id_to_vapi_msg_t);
289   pthread_mutex_destroy (&ctx->requests_mutex);
290   free (ctx);
291 }
292
293 bool
294 vapi_is_msg_available (vapi_ctx_t ctx, vapi_msg_id_t id)
295 {
296   return vapi_lookup_vl_msg_id (ctx, id) != UINT16_MAX;
297 }
298
299 vapi_error_e
300 vapi_connect (vapi_ctx_t ctx, const char *name,
301               const char *chroot_prefix,
302               int max_outstanding_requests,
303               int response_queue_size, vapi_mode_e mode,
304               bool handle_keepalives)
305 {
306   if (response_queue_size <= 0 || max_outstanding_requests <= 0)
307     {
308       return VAPI_EINVAL;
309     }
310   if (!clib_mem_get_per_cpu_heap () && !clib_mem_init (0, 1024 * 1024 * 32))
311     {
312       return VAPI_ENOMEM;
313     }
314   ctx->requests_size = max_outstanding_requests;
315   const size_t size = ctx->requests_size * sizeof (*ctx->requests);
316   void *tmp = realloc (ctx->requests, size);
317   if (!tmp)
318     {
319       return VAPI_ENOMEM;
320     }
321   ctx->requests = tmp;
322   clib_memset (ctx->requests, 0, size);
323   /* coverity[MISSING_LOCK] - 177211 requests_mutex is not needed here */
324   ctx->requests_start = ctx->requests_count = 0;
325   if (chroot_prefix)
326     {
327       VAPI_DBG ("set memory root path `%s'", chroot_prefix);
328       vl_set_memory_root_path ((char *) chroot_prefix);
329     }
330   static char api_map[] = "/vpe-api";
331   VAPI_DBG ("client api map `%s'", api_map);
332   if ((vl_client_api_map (api_map)) < 0)
333     {
334       return VAPI_EMAP_FAIL;
335     }
336   VAPI_DBG ("connect client `%s'", name);
337   if (vl_client_connect ((char *) name, 0, response_queue_size) < 0)
338     {
339       vl_client_api_unmap ();
340       return VAPI_ECON_FAIL;
341     }
342 #if VAPI_DEBUG_CONNECT
343   VAPI_DBG ("start probing messages");
344 #endif
345   int rv;
346   int i;
347   for (i = 0; i < __vapi_metadata.count; ++i)
348     {
349       vapi_message_desc_t *m = __vapi_metadata.msgs[i];
350       u8 scratch[m->name_with_crc_len + 1];
351       memcpy (scratch, m->name_with_crc, m->name_with_crc_len + 1);
352       u32 id = vl_msg_api_get_msg_index (scratch);
353       if (VAPI_INVALID_MSG_ID != id)
354         {
355           if (id > UINT16_MAX)
356             {
357               VAPI_ERR ("Returned vl_msg_id `%u' > UINT16MAX `%u'!", id,
358                         UINT16_MAX);
359               rv = VAPI_EINVAL;
360               goto fail;
361             }
362           if (id > ctx->vl_msg_id_max)
363             {
364               vapi_msg_id_t *tmp = realloc (ctx->vl_msg_id_to_vapi_msg_t,
365                                             sizeof
366                                             (*ctx->vl_msg_id_to_vapi_msg_t) *
367                                             (id + 1));
368               if (!tmp)
369                 {
370                   rv = VAPI_ENOMEM;
371                   goto fail;
372                 }
373               ctx->vl_msg_id_to_vapi_msg_t = tmp;
374               ctx->vl_msg_id_max = id;
375             }
376           ctx->vl_msg_id_to_vapi_msg_t[id] = m->id;
377           ctx->vapi_msg_id_t_to_vl_msg_id[m->id] = id;
378 #if VAPI_DEBUG_CONNECT
379           VAPI_DBG ("Message `%s' has vl_msg_id `%u'", m->name_with_crc,
380                     (unsigned) id);
381 #endif
382         }
383       else
384         {
385           ctx->vapi_msg_id_t_to_vl_msg_id[m->id] = UINT16_MAX;
386           VAPI_DBG ("Message `%s' not available", m->name_with_crc);
387         }
388     }
389 #if VAPI_DEBUG_CONNECT
390   VAPI_DBG ("finished probing messages");
391 #endif
392   if (!vapi_is_msg_available (ctx, vapi_msg_id_control_ping) ||
393       !vapi_is_msg_available (ctx, vapi_msg_id_control_ping_reply))
394     {
395       VAPI_ERR
396         ("control ping or control ping reply not available, cannot connect");
397       rv = VAPI_EINCOMPATIBLE;
398       goto fail;
399     }
400   ctx->mode = mode;
401   ctx->connected = true;
402   if (vapi_is_msg_available (ctx, vapi_msg_id_memclnt_keepalive))
403     {
404       ctx->handle_keepalives = handle_keepalives;
405     }
406   else
407     {
408       ctx->handle_keepalives = false;
409     }
410   return VAPI_OK;
411 fail:
412   vl_client_disconnect ();
413   vl_client_api_unmap ();
414   return rv;
415 }
416
417 vapi_error_e
418 vapi_disconnect (vapi_ctx_t ctx)
419 {
420   if (!ctx->connected)
421     {
422       return VAPI_EINVAL;
423     }
424   vl_client_disconnect ();
425   vl_client_api_unmap ();
426 #if VAPI_DEBUG_ALLOC
427   vapi_to_be_freed_validate ();
428 #endif
429   ctx->connected = false;
430   return VAPI_OK;
431 }
432
433 vapi_error_e
434 vapi_get_fd (vapi_ctx_t ctx, int *fd)
435 {
436   return VAPI_ENOTSUP;
437 }
438
439 vapi_error_e
440 vapi_send (vapi_ctx_t ctx, void *msg)
441 {
442   vapi_error_e rv = VAPI_OK;
443   if (!ctx || !msg || !ctx->connected)
444     {
445       rv = VAPI_EINVAL;
446       goto out;
447     }
448   int tmp;
449   svm_queue_t *q = api_main.shmem_hdr->vl_input_queue;
450 #if VAPI_DEBUG
451   unsigned msgid = be16toh (*(u16 *) msg);
452   if (msgid <= ctx->vl_msg_id_max)
453     {
454       vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[msgid];
455       if (id < __vapi_metadata.count)
456         {
457           VAPI_DBG ("send msg@%p:%u[%s]", msg, msgid,
458                     __vapi_metadata.msgs[id]->name);
459         }
460       else
461         {
462           VAPI_DBG ("send msg@%p:%u[UNKNOWN]", msg, msgid);
463         }
464     }
465   else
466     {
467       VAPI_DBG ("send msg@%p:%u[UNKNOWN]", msg, msgid);
468     }
469 #endif
470   tmp = svm_queue_add (q, (u8 *) & msg,
471                        VAPI_MODE_BLOCKING == ctx->mode ? 0 : 1);
472   if (tmp < 0)
473     {
474       rv = VAPI_EAGAIN;
475     }
476 out:
477   VAPI_DBG ("vapi_send() rv = %d", rv);
478   return rv;
479 }
480
481 vapi_error_e
482 vapi_send2 (vapi_ctx_t ctx, void *msg1, void *msg2)
483 {
484   vapi_error_e rv = VAPI_OK;
485   if (!ctx || !msg1 || !msg2 || !ctx->connected)
486     {
487       rv = VAPI_EINVAL;
488       goto out;
489     }
490   svm_queue_t *q = api_main.shmem_hdr->vl_input_queue;
491 #if VAPI_DEBUG
492   unsigned msgid1 = be16toh (*(u16 *) msg1);
493   unsigned msgid2 = be16toh (*(u16 *) msg2);
494   const char *name1 = "UNKNOWN";
495   const char *name2 = "UNKNOWN";
496   if (msgid1 <= ctx->vl_msg_id_max)
497     {
498       vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[msgid1];
499       if (id < __vapi_metadata.count)
500         {
501           name1 = __vapi_metadata.msgs[id]->name;
502         }
503     }
504   if (msgid2 <= ctx->vl_msg_id_max)
505     {
506       vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[msgid2];
507       if (id < __vapi_metadata.count)
508         {
509           name2 = __vapi_metadata.msgs[id]->name;
510         }
511     }
512   VAPI_DBG ("send two: %u[%s], %u[%s]", msgid1, name1, msgid2, name2);
513 #endif
514   int tmp = svm_queue_add2 (q, (u8 *) & msg1, (u8 *) & msg2,
515                             VAPI_MODE_BLOCKING == ctx->mode ? 0 : 1);
516   if (tmp < 0)
517     {
518       rv = VAPI_EAGAIN;
519     }
520 out:
521   VAPI_DBG ("vapi_send() rv = %d", rv);
522   return rv;
523 }
524
525 vapi_error_e
526 vapi_recv (vapi_ctx_t ctx, void **msg, size_t * msg_size,
527            svm_q_conditional_wait_t cond, u32 time)
528 {
529   if (!ctx || !ctx->connected || !msg || !msg_size)
530     {
531       return VAPI_EINVAL;
532     }
533   vapi_error_e rv = VAPI_OK;
534   api_main_t *am = &api_main;
535   uword data;
536
537   if (am->our_pid == 0)
538     {
539       return VAPI_EINVAL;
540     }
541
542   svm_queue_t *q = am->vl_input_queue;
543 again:
544   VAPI_DBG ("doing shm queue sub");
545
546   int tmp = svm_queue_sub (q, (u8 *) & data, cond, time);
547
548   if (tmp == 0)
549     {
550 #if VAPI_DEBUG_ALLOC
551       vapi_add_to_be_freed ((void *) data);
552 #endif
553       msgbuf_t *msgbuf =
554         (msgbuf_t *) ((u8 *) data - offsetof (msgbuf_t, data));
555       if (!msgbuf->data_len)
556         {
557           vapi_msg_free (ctx, (u8 *) data);
558           return VAPI_EAGAIN;
559         }
560       *msg = (u8 *) data;
561       *msg_size = ntohl (msgbuf->data_len);
562 #if VAPI_DEBUG
563       unsigned msgid = be16toh (*(u16 *) * msg);
564       if (msgid <= ctx->vl_msg_id_max)
565         {
566           vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[msgid];
567           if (id < __vapi_metadata.count)
568             {
569               VAPI_DBG ("recv msg@%p:%u[%s]", *msg, msgid,
570                         __vapi_metadata.msgs[id]->name);
571             }
572           else
573             {
574               VAPI_DBG ("recv msg@%p:%u[UNKNOWN]", *msg, msgid);
575             }
576         }
577       else
578         {
579           VAPI_DBG ("recv msg@%p:%u[UNKNOWN]", *msg, msgid);
580         }
581 #endif
582       if (ctx->handle_keepalives)
583         {
584           unsigned msgid = be16toh (*(u16 *) * msg);
585           if (msgid ==
586               vapi_lookup_vl_msg_id (ctx, vapi_msg_id_memclnt_keepalive))
587             {
588               vapi_msg_memclnt_keepalive_reply *reply = NULL;
589               do
590                 {
591                   reply = vapi_msg_alloc (ctx, sizeof (*reply));
592                 }
593               while (!reply);
594               reply->header.context = vapi_get_client_index (ctx);
595               reply->header._vl_msg_id =
596                 vapi_lookup_vl_msg_id (ctx,
597                                        vapi_msg_id_memclnt_keepalive_reply);
598               reply->payload.retval = 0;
599               vapi_msg_memclnt_keepalive_reply_hton (reply);
600               while (VAPI_EAGAIN == vapi_send (ctx, reply));
601               vapi_msg_free (ctx, *msg);
602               VAPI_DBG ("autohandled memclnt_keepalive");
603               goto again;
604             }
605         }
606     }
607   else
608     {
609       rv = VAPI_EAGAIN;
610     }
611   return rv;
612 }
613
614 vapi_error_e
615 vapi_wait (vapi_ctx_t ctx, vapi_wait_mode_e mode)
616 {
617   return VAPI_ENOTSUP;
618 }
619
620 static vapi_error_e
621 vapi_dispatch_response (vapi_ctx_t ctx, vapi_msg_id_t id,
622                         u32 context, void *msg)
623 {
624   int mrv;
625   if (0 != (mrv = pthread_mutex_lock (&ctx->requests_mutex)))
626     {
627       VAPI_DBG ("pthread_mutex_lock() failed, rv=%d:%s", mrv, strerror (mrv));
628       return VAPI_MUTEX_FAILURE;
629     }
630   int tmp = ctx->requests_start;
631   const int requests_end = vapi_requests_end (ctx);
632   while (ctx->requests[tmp].context != context && tmp != requests_end)
633     {
634       ++tmp;
635       if (tmp == ctx->requests_size)
636         {
637           tmp = 0;
638         }
639     }
640   VAPI_DBG ("dispatch, search from %d, %s at %d", ctx->requests_start,
641             ctx->requests[tmp].context == context ? "matched" : "stopped",
642             tmp);
643   vapi_error_e rv = VAPI_OK;
644   if (ctx->requests[tmp].context == context)
645     {
646       while (ctx->requests_start != tmp)
647         {
648           VAPI_ERR ("No response to req with context=%u",
649                     (unsigned) ctx->requests[tmp].context);
650           ctx->requests[ctx->requests_start].callback (ctx, ctx->requests
651                                                        [ctx->
652                                                         requests_start].callback_ctx,
653                                                        VAPI_ENORESP, true,
654                                                        NULL);
655           clib_memset (&ctx->requests[ctx->requests_start], 0,
656                        sizeof (ctx->requests[ctx->requests_start]));
657           ++ctx->requests_start;
658           --ctx->requests_count;
659           if (ctx->requests_start == ctx->requests_size)
660             {
661               ctx->requests_start = 0;
662             }
663         }
664       // now ctx->requests_start == tmp
665       int payload_offset = vapi_get_payload_offset (id);
666       void *payload = ((u8 *) msg) + payload_offset;
667       bool is_last = true;
668       if (ctx->requests[tmp].is_dump)
669         {
670           if (vapi_msg_id_control_ping_reply == id)
671             {
672               payload = NULL;
673             }
674           else
675             {
676               is_last = false;
677             }
678         }
679       if (payload_offset != -1)
680         {
681           rv =
682             ctx->requests[tmp].callback (ctx, ctx->requests[tmp].callback_ctx,
683                                          VAPI_OK, is_last, payload);
684         }
685       else
686         {
687           /* this is a message without payload, so bend the callback a little
688            */
689           rv =
690             ((vapi_error_e (*)(vapi_ctx_t, void *, vapi_error_e, bool))
691              ctx->requests[tmp].callback) (ctx,
692                                            ctx->requests[tmp].callback_ctx,
693                                            VAPI_OK, is_last);
694         }
695       if (is_last)
696         {
697           clib_memset (&ctx->requests[ctx->requests_start], 0,
698                        sizeof (ctx->requests[ctx->requests_start]));
699           ++ctx->requests_start;
700           --ctx->requests_count;
701           if (ctx->requests_start == ctx->requests_size)
702             {
703               ctx->requests_start = 0;
704             }
705         }
706       VAPI_DBG ("after dispatch, req start = %d, end = %d, count = %d",
707                 ctx->requests_start, requests_end, ctx->requests_count);
708     }
709   if (0 != (mrv = pthread_mutex_unlock (&ctx->requests_mutex)))
710     {
711       VAPI_DBG ("pthread_mutex_unlock() failed, rv=%d:%s", mrv,
712                 strerror (mrv));
713       abort ();                 /* this really shouldn't happen */
714     }
715   return rv;
716 }
717
718 static vapi_error_e
719 vapi_dispatch_event (vapi_ctx_t ctx, vapi_msg_id_t id, void *msg)
720 {
721   if (ctx->event_cbs[id].cb)
722     {
723       return ctx->event_cbs[id].cb (ctx, ctx->event_cbs[id].ctx, msg);
724     }
725   else if (ctx->generic_cb.cb)
726     {
727       return ctx->generic_cb.cb (ctx, ctx->generic_cb.ctx, id, msg);
728     }
729   else
730     {
731       VAPI_DBG
732         ("No handler/generic handler for msg id %u[%s], message ignored",
733          (unsigned) id, __vapi_metadata.msgs[id]->name);
734     }
735   return VAPI_OK;
736 }
737
738 bool
739 vapi_msg_is_with_context (vapi_msg_id_t id)
740 {
741   assert (id <= __vapi_metadata.count);
742   return __vapi_metadata.msgs[id]->has_context;
743 }
744
745 vapi_error_e
746 vapi_dispatch_one (vapi_ctx_t ctx)
747 {
748   VAPI_DBG ("vapi_dispatch_one()");
749   void *msg;
750   size_t size;
751   vapi_error_e rv = vapi_recv (ctx, &msg, &size, SVM_Q_WAIT, 0);
752   if (VAPI_OK != rv)
753     {
754       VAPI_DBG ("vapi_recv failed with rv=%d", rv);
755       return rv;
756     }
757   u16 vpp_id = be16toh (*(u16 *) msg);
758   if (vpp_id > ctx->vl_msg_id_max)
759     {
760       VAPI_ERR ("Unknown msg ID received, id `%u', out of range <0,%u>",
761                 (unsigned) vpp_id, (unsigned) ctx->vl_msg_id_max);
762       vapi_msg_free (ctx, msg);
763       return VAPI_EINVAL;
764     }
765   if (VAPI_INVALID_MSG_ID == (unsigned) ctx->vl_msg_id_to_vapi_msg_t[vpp_id])
766     {
767       VAPI_ERR ("Unknown msg ID received, id `%u' marked as not supported",
768                 (unsigned) vpp_id);
769       vapi_msg_free (ctx, msg);
770       return VAPI_EINVAL;
771     }
772   const vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[vpp_id];
773   const size_t expect_size = vapi_get_message_size (id);
774   if (size < expect_size)
775     {
776       VAPI_ERR
777         ("Invalid msg received, unexpected size `%zu' < expected min `%zu'",
778          size, expect_size);
779       vapi_msg_free (ctx, msg);
780       return VAPI_EINVAL;
781     }
782   u32 context;
783   vapi_get_swap_to_host_func (id) (msg);
784   if (vapi_msg_is_with_context (id))
785     {
786       context = *(u32 *) (((u8 *) msg) + vapi_get_context_offset (id));
787       /* is this a message originating from VAPI? */
788       VAPI_DBG ("dispatch, context is %x", context);
789       if (context & context_counter_mask)
790         {
791           rv = vapi_dispatch_response (ctx, id, context, msg);
792           goto done;
793         }
794     }
795   rv = vapi_dispatch_event (ctx, id, msg);
796
797 done:
798   vapi_msg_free (ctx, msg);
799   return rv;
800 }
801
802 vapi_error_e
803 vapi_dispatch (vapi_ctx_t ctx)
804 {
805   vapi_error_e rv = VAPI_OK;
806   while (!vapi_requests_empty (ctx))
807     {
808       rv = vapi_dispatch_one (ctx);
809       if (VAPI_OK != rv)
810         {
811           return rv;
812         }
813     }
814   return rv;
815 }
816
817 void
818 vapi_set_event_cb (vapi_ctx_t ctx, vapi_msg_id_t id,
819                    vapi_event_cb callback, void *callback_ctx)
820 {
821   vapi_event_cb_with_ctx *c = &ctx->event_cbs[id];
822   c->cb = callback;
823   c->ctx = callback_ctx;
824 }
825
826 void
827 vapi_clear_event_cb (vapi_ctx_t ctx, vapi_msg_id_t id)
828 {
829   vapi_set_event_cb (ctx, id, NULL, NULL);
830 }
831
832 void
833 vapi_set_generic_event_cb (vapi_ctx_t ctx, vapi_generic_event_cb callback,
834                            void *callback_ctx)
835 {
836   ctx->generic_cb.cb = callback;
837   ctx->generic_cb.ctx = callback_ctx;
838 }
839
840 void
841 vapi_clear_generic_event_cb (vapi_ctx_t ctx)
842 {
843   ctx->generic_cb.cb = NULL;
844   ctx->generic_cb.ctx = NULL;
845 }
846
847 u16
848 vapi_lookup_vl_msg_id (vapi_ctx_t ctx, vapi_msg_id_t id)
849 {
850   assert (id < __vapi_metadata.count);
851   return ctx->vapi_msg_id_t_to_vl_msg_id[id];
852 }
853
854 int
855 vapi_get_client_index (vapi_ctx_t ctx)
856 {
857   return api_main.my_client_index;
858 }
859
860 bool
861 vapi_is_nonblocking (vapi_ctx_t ctx)
862 {
863   return (VAPI_MODE_NONBLOCKING == ctx->mode);
864 }
865
866 size_t
867 vapi_get_max_request_count (vapi_ctx_t ctx)
868 {
869   return ctx->requests_size - 1;
870 }
871
872 int
873 vapi_get_payload_offset (vapi_msg_id_t id)
874 {
875   assert (id < __vapi_metadata.count);
876   return __vapi_metadata.msgs[id]->payload_offset;
877 }
878
879 void (*vapi_get_swap_to_host_func (vapi_msg_id_t id)) (void *msg)
880 {
881   assert (id < __vapi_metadata.count);
882   return __vapi_metadata.msgs[id]->swap_to_host;
883 }
884
885 void (*vapi_get_swap_to_be_func (vapi_msg_id_t id)) (void *msg)
886 {
887   assert (id < __vapi_metadata.count);
888   return __vapi_metadata.msgs[id]->swap_to_be;
889 }
890
891 size_t
892 vapi_get_message_size (vapi_msg_id_t id)
893 {
894   assert (id < __vapi_metadata.count);
895   return __vapi_metadata.msgs[id]->size;
896 }
897
898 size_t
899 vapi_get_context_offset (vapi_msg_id_t id)
900 {
901   assert (id < __vapi_metadata.count);
902   return __vapi_metadata.msgs[id]->context_offset;
903 }
904
905 vapi_msg_id_t
906 vapi_register_msg (vapi_message_desc_t * msg)
907 {
908   int i = 0;
909   for (i = 0; i < __vapi_metadata.count; ++i)
910     {
911       if (!strcmp
912           (msg->name_with_crc, __vapi_metadata.msgs[i]->name_with_crc))
913         {
914           /* this happens if somebody is linking together several objects while
915            * using the static inline headers, just fill in the already
916            * assigned id here so that all the objects are in sync */
917           msg->id = __vapi_metadata.msgs[i]->id;
918           return msg->id;
919         }
920     }
921   vapi_msg_id_t id = __vapi_metadata.count;
922   ++__vapi_metadata.count;
923   __vapi_metadata.msgs =
924     realloc (__vapi_metadata.msgs,
925              sizeof (*__vapi_metadata.msgs) * __vapi_metadata.count);
926   __vapi_metadata.msgs[id] = msg;
927   size_t s = strlen (msg->name_with_crc);
928   if (s > __vapi_metadata.max_len_name_with_crc)
929     {
930       __vapi_metadata.max_len_name_with_crc = s;
931     }
932   msg->id = id;
933   return id;
934 }
935
936 vapi_error_e
937 vapi_producer_lock (vapi_ctx_t ctx)
938 {
939   int mrv;
940   if (0 != (mrv = pthread_mutex_lock (&ctx->requests_mutex)))
941     {
942       VAPI_DBG ("pthread_mutex_lock() failed, rv=%d:%s", mrv, strerror (mrv));
943       (void) mrv;               /* avoid warning if the above debug is not enabled */
944       return VAPI_MUTEX_FAILURE;
945     }
946   return VAPI_OK;
947 }
948
949 vapi_error_e
950 vapi_producer_unlock (vapi_ctx_t ctx)
951 {
952   int mrv;
953   if (0 != (mrv = pthread_mutex_unlock (&ctx->requests_mutex)))
954     {
955       VAPI_DBG ("pthread_mutex_unlock() failed, rv=%d:%s", mrv,
956                 strerror (mrv));
957       (void) mrv;               /* avoid warning if the above debug is not enabled */
958       return VAPI_MUTEX_FAILURE;
959     }
960   return VAPI_OK;
961 }
962
963 size_t
964 vapi_get_message_count ()
965 {
966   return __vapi_metadata.count;
967 }
968
969 const char *
970 vapi_get_msg_name (vapi_msg_id_t id)
971 {
972   return __vapi_metadata.msgs[id]->name;
973 }
974
975 /*
976  * fd.io coding-style-patch-verification: ON
977  *
978  * Local Variables:
979  * eval: (c-set-style "gnu")
980  * End:
981  */