api: refactor api data storage
[vpp.git] / src / vlibapi / api_shared.c
1 /*
2  *------------------------------------------------------------------
3  * api_shared.c - API message handling, common code for both clients
4  * and the vlib process itself.
5  *
6  *
7  * Copyright (c) 2009 Cisco and/or its affiliates.
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at:
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *------------------------------------------------------------------
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stddef.h>
25 #include <string.h>
26 #include <vppinfra/format.h>
27 #include <vppinfra/byte_order.h>
28 #include <vppinfra/error.h>
29 #include <vlib/vlib.h>
30 #include <vlib/unix/unix.h>
31 #include <vlibapi/api.h>
32 #include <vppinfra/elog.h>
33 #include <vppinfra/callback.h>
34
35 /* *INDENT-OFF* */
36 static api_main_t api_global_main = {
37   .region_name = "/unset",
38   .api_uid = -1,
39   .api_gid = -1,
40 };
41 /* *INDENT-ON* */
42
43 /* Please use vlibapi_get_main() to access my_api_main */
44 __thread api_main_t *my_api_main = &api_global_main;
45
46 void
47 vl_msg_api_set_global_main (void *am_arg)
48 {
49   ASSERT (am_arg);
50   my_api_main = (api_main_t *) am_arg;
51 }
52
53 void
54 vl_msg_api_increment_missing_client_counter (void)
55 {
56   api_main_t *am = vlibapi_get_main ();
57   am->missing_clients++;
58 }
59
60 int
61 vl_msg_api_rx_trace_enabled (api_main_t * am)
62 {
63   return (am->rx_trace && am->rx_trace->enabled);
64 }
65
66 int
67 vl_msg_api_tx_trace_enabled (api_main_t * am)
68 {
69   return (am->tx_trace && am->tx_trace->enabled);
70 }
71
72 /*
73  * vl_msg_api_trace
74  */
75 void
76 vl_msg_api_trace (api_main_t * am, vl_api_trace_t * tp, void *msg)
77 {
78   u8 **this_trace;
79   u8 **old_trace;
80   u8 *msg_copy;
81   u32 length;
82   u16 msg_id = clib_net_to_host_u16 (*((u16 *) msg));
83   vl_api_msg_data_t *m = vl_api_get_msg_data (am, msg_id);
84   msgbuf_t *header = (msgbuf_t *) (((u8 *) msg) - offsetof (msgbuf_t, data));
85
86   if (!m || !m->trace_enable)
87     return;
88
89   msg_copy = 0;
90
91   if (tp->nitems == 0)
92     {
93       clib_warning ("tp->nitems is 0");
94       return;
95     }
96
97   if (vec_len (tp->traces) < tp->nitems)
98     {
99       vec_add1 (tp->traces, 0);
100       this_trace = tp->traces + vec_len (tp->traces) - 1;
101     }
102   else
103     {
104       tp->wrapped = 1;
105       old_trace = tp->traces + tp->curindex++;
106       if (tp->curindex == tp->nitems)
107         tp->curindex = 0;
108       /* Reuse the trace record, may save some memory allocator traffic */
109       msg_copy = *old_trace;
110       vec_reset_length (msg_copy);
111       this_trace = old_trace;
112     }
113
114   length = clib_net_to_host_u32 (header->data_len);
115
116   vec_validate (msg_copy, length - 1);
117   clib_memcpy_fast (msg_copy, msg, length);
118   *this_trace = msg_copy;
119 }
120
121 int
122 vl_msg_api_trace_onoff (api_main_t * am, vl_api_trace_which_t which,
123                         int onoff)
124 {
125   vl_api_trace_t *tp;
126   int rv;
127
128   switch (which)
129     {
130     case VL_API_TRACE_TX:
131       tp = am->tx_trace;
132       if (tp == 0)
133         {
134           vl_msg_api_trace_configure (am, which, 1024);
135           tp = am->tx_trace;
136         }
137       break;
138
139     case VL_API_TRACE_RX:
140       tp = am->rx_trace;
141       if (tp == 0)
142         {
143           vl_msg_api_trace_configure (am, which, 1024);
144           tp = am->rx_trace;
145         }
146       break;
147
148     default:
149       /* duh? */
150       return -1;
151     }
152
153   /* Configured? */
154   if (tp == 0 || tp->nitems == 0)
155     return -1;
156
157   rv = tp->enabled;
158   tp->enabled = onoff;
159
160   return rv;
161 }
162
163 int
164 vl_msg_api_trace_free (api_main_t * am, vl_api_trace_which_t which)
165 {
166   vl_api_trace_t *tp;
167   int i;
168
169   switch (which)
170     {
171     case VL_API_TRACE_TX:
172       tp = am->tx_trace;
173       break;
174
175     case VL_API_TRACE_RX:
176       tp = am->rx_trace;
177       break;
178
179     default:
180       /* duh? */
181       return -1;
182     }
183
184   /* Configured? */
185   if (!tp || tp->nitems == 0)
186     return -1;
187
188   tp->curindex = 0;
189   tp->wrapped = 0;
190
191   for (i = 0; i < vec_len (tp->traces); i++)
192     {
193       vec_free (tp->traces[i]);
194     }
195   vec_free (tp->traces);
196
197   return 0;
198 }
199
200 u8 *
201 vl_api_serialize_message_table (api_main_t * am, u8 * vector)
202 {
203   serialize_main_t _sm, *sm = &_sm;
204   hash_pair_t *hp;
205   u32 nmsg = hash_elts (am->msg_index_by_name_and_crc);
206
207   serialize_open_vector (sm, vector);
208
209   /* serialize the count */
210   serialize_integer (sm, nmsg, sizeof (u32));
211
212   /* *INDENT-OFF* */
213   hash_foreach_pair (hp, am->msg_index_by_name_and_crc,
214   ({
215     serialize_likely_small_unsigned_integer (sm, hp->value[0]);
216     serialize_cstring (sm, (char *) hp->key);
217   }));
218   /* *INDENT-ON* */
219
220   return serialize_close_vector (sm);
221 }
222
223 static int
224 vl_msg_api_trace_write_one (api_main_t *am, u8 *msg, FILE *fp)
225 {
226   u8 *tmpmem = 0;
227   int tlen, slen;
228
229   u32 msg_length = vec_len (msg);
230   vec_validate (tmpmem, msg_length - 1);
231   clib_memcpy_fast (tmpmem, msg, msg_length);
232   u16 id = clib_net_to_host_u16 (*((u16 *) msg));
233   vl_api_msg_data_t *m = vl_api_get_msg_data (am, id);
234
235   m->endian_handler (tmpmem);
236
237   if (m && m->tojson_handler)
238     {
239       cJSON *o = m->tojson_handler (tmpmem);
240       char *s = cJSON_Print (o);
241       slen = strlen (s);
242       tlen = fwrite (s, 1, slen, fp);
243       cJSON_free (s);
244       cJSON_Delete (o);
245       vec_free (tmpmem);
246       if (tlen != slen)
247         {
248           fformat (stderr, "writing to file error\n");
249           return -11;
250         }
251     }
252   else
253     fformat (stderr, "  [no registered tojson fn]\n");
254
255   return 0;
256 }
257
258 #define vl_msg_fwrite(_s, _f) fwrite (_s, 1, sizeof (_s) - 1, _f)
259
260 typedef struct
261 {
262   FILE *fp;
263   u32 n_traces;
264   u32 i;
265 } vl_msg_write_json_args_t;
266
267 static int
268 vl_msg_write_json_fn (u8 *msg, void *ctx)
269 {
270   vl_msg_write_json_args_t *arg = ctx;
271   FILE *fp = arg->fp;
272   api_main_t *am = vlibapi_get_main ();
273   int rc = vl_msg_api_trace_write_one (am, msg, fp);
274   if (rc < 0)
275     return rc;
276
277   if (arg->i < arg->n_traces - 1)
278     vl_msg_fwrite (",\n", fp);
279   arg->i++;
280   return 0;
281 }
282
283 static int
284 vl_msg_api_trace_write_json (api_main_t *am, vl_api_trace_t *tp, FILE *fp)
285 {
286   vl_msg_write_json_args_t args;
287   clib_memset (&args, 0, sizeof (args));
288   args.fp = fp;
289   args.n_traces = vec_len (tp->traces);
290   vl_msg_fwrite ("[\n", fp);
291
292   int rv = vl_msg_traverse_trace (tp, vl_msg_write_json_fn, &args);
293   if (rv < 0)
294     return rv;
295
296   vl_msg_fwrite ("]", fp);
297   return 0;
298 }
299
300 int
301 vl_msg_traverse_trace (vl_api_trace_t *tp, vl_msg_traverse_trace_fn fn,
302                        void *ctx)
303 {
304   int i;
305   u8 *msg;
306   int rv = 0;
307
308   /* No-wrap case */
309   if (tp->wrapped == 0)
310     {
311       for (i = 0; i < vec_len (tp->traces); i++)
312         {
313           /*sa_ignore NO_NULL_CHK */
314           msg = tp->traces[i];
315           if (!msg)
316             continue;
317
318           rv = fn (msg, ctx);
319           if (rv < 0)
320             return rv;
321         }
322     }
323   else
324     {
325       /* Wrap case: write oldest -> end of buffer */
326       for (i = tp->curindex; i < vec_len (tp->traces); i++)
327         {
328           msg = tp->traces[i];
329           if (!msg)
330             continue;
331
332           rv = fn (msg, ctx);
333           if (rv < 0)
334             return rv;
335         }
336       /* write beginning of buffer -> oldest-1 */
337       for (i = 0; i < tp->curindex; i++)
338         {
339           /*sa_ignore NO_NULL_CHK */
340           msg = tp->traces[i];
341           if (!msg)
342             continue;
343
344           rv = fn (msg, ctx);
345           if (rv < 0)
346             return rv;
347         }
348     }
349   return 0;
350 }
351
352 static int
353 vl_api_msg_write_fn (u8 *msg, void *ctx)
354 {
355   FILE *fp = ctx;
356   u32 msg_length = clib_host_to_net_u32 (vec_len (msg));
357   if (fwrite (&msg_length, 1, sizeof (msg_length), fp) != sizeof (msg_length))
358     {
359       return (-14);
360     }
361   if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
362     {
363       return (-14);
364     }
365   return 0;
366 }
367
368 int
369 vl_msg_api_trace_save (api_main_t *am, vl_api_trace_which_t which, FILE *fp,
370                        u8 is_json)
371 {
372   vl_api_trace_t *tp;
373   vl_api_trace_file_header_t fh;
374
375   switch (which)
376     {
377     case VL_API_TRACE_TX:
378       tp = am->tx_trace;
379       break;
380
381     case VL_API_TRACE_RX:
382       tp = am->rx_trace;
383       break;
384
385     default:
386       /* duh? */
387       return -1;
388     }
389
390   /* Configured, data present? */
391   if (tp == 0 || tp->nitems == 0 || vec_len (tp->traces) == 0)
392     return -1;
393
394   /* "Dare to be stupid" check */
395   if (fp == 0)
396     {
397       return -2;
398     }
399
400   if (is_json)
401     return vl_msg_api_trace_write_json (am, tp, fp);
402
403   /* Write the file header */
404   fh.wrapped = tp->wrapped;
405   fh.nitems = clib_host_to_net_u32 (vec_len (tp->traces));
406
407   u8 *m = vl_api_serialize_message_table (am, 0);
408   fh.msgtbl_size = clib_host_to_net_u32 (vec_len (m));
409
410   if (fwrite (&fh, sizeof (fh), 1, fp) != 1)
411     {
412       return (-10);
413     }
414
415   /* Write the message table */
416   if (fwrite (m, vec_len (m), 1, fp) != 1)
417     {
418       return (-14);
419     }
420   vec_free (m);
421
422   return vl_msg_traverse_trace (tp, vl_api_msg_write_fn, fp);
423 }
424
425 int
426 vl_msg_api_trace_configure (api_main_t * am, vl_api_trace_which_t which,
427                             u32 nitems)
428 {
429   vl_api_trace_t *tp;
430   int was_on = 0;
431
432   switch (which)
433     {
434     case VL_API_TRACE_TX:
435       tp = am->tx_trace;
436       if (tp == 0)
437         {
438           vec_validate (am->tx_trace, 0);
439           tp = am->tx_trace;
440         }
441       break;
442
443     case VL_API_TRACE_RX:
444       tp = am->rx_trace;
445       if (tp == 0)
446         {
447           vec_validate (am->rx_trace, 0);
448           tp = am->rx_trace;
449         }
450
451       break;
452
453     default:
454       return -1;
455
456     }
457
458   if (tp->enabled)
459     {
460       was_on = vl_msg_api_trace_onoff (am, which, 0);
461     }
462   if (tp->traces)
463     {
464       vl_msg_api_trace_free (am, which);
465     }
466
467   clib_memset (tp, 0, sizeof (*tp));
468
469   if (clib_arch_is_big_endian)
470     {
471       tp->endian = VL_API_BIG_ENDIAN;
472     }
473   else
474     {
475       tp->endian = VL_API_LITTLE_ENDIAN;
476     }
477
478   tp->nitems = nitems;
479   if (was_on)
480     {
481       (void) vl_msg_api_trace_onoff (am, which, was_on);
482     }
483   return 0;
484 }
485
486 void
487 vl_msg_api_barrier_sync (void)
488 {
489 }
490
491 void
492 vl_msg_api_barrier_release (void)
493 {
494 }
495
496 always_inline void
497 msg_handler_internal (api_main_t *am, void *the_msg, uword msg_len,
498                       int trace_it, int do_it, int free_it)
499 {
500   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
501   vl_api_msg_data_t *m = vl_api_get_msg_data (am, id);
502
503   if (PREDICT_FALSE (am->elog_trace_api_messages))
504     {
505       /* *INDENT-OFF* */
506       ELOG_TYPE_DECLARE (e) =
507         {
508           .format = "api-msg: %s",
509           .format_args = "T4",
510         };
511       /* *INDENT-ON* */
512       struct
513       {
514         u32 c;
515       } *ed;
516       ed = ELOG_DATA (am->elog_main, e);
517       if (m && m->name)
518         ed->c = elog_string (am->elog_main, (char *) m->name);
519       else
520         ed->c = elog_string (am->elog_main, "BOGUS");
521     }
522
523   if (m && m->handler)
524     {
525       if (trace_it)
526         vl_msg_api_trace (am, am->rx_trace, the_msg);
527
528       if (am->msg_print_flag)
529         {
530           fformat (stdout, "[%d]: %s\n", id, m->name);
531           if (m->print_handler)
532             m->print_handler (the_msg, stdout);
533           else
534             fformat (stdout, "  [no registered print fn]\n");
535         }
536
537       uword calc_size = 0;
538       ASSERT (NULL != m->calc_size_func);
539       if (m->calc_size_func)
540         {
541           calc_size = m->calc_size_func (the_msg);
542           if (calc_size > msg_len)
543             {
544               clib_warning (
545                 "Truncated message '%s' (id %u) received, calculated size "
546                 "%lu is bigger than actual size %llu, message dropped.",
547                 m->name, id, calc_size, msg_len);
548             }
549         }
550       else
551         {
552           clib_warning ("Message '%s' (id %u) has NULL calc_size_func, cannot "
553                         "verify message size is correct",
554                         m->name, id);
555         }
556
557       /* don't process message if it's truncated, otherwise byte swaps
558        * and stuff could corrupt memory even beyond message if it's malicious
559        * e.g. VLA length field set to 1M elements, but VLA empty */
560       if (do_it && calc_size <= msg_len)
561         {
562
563           if (!m->is_mp_safe)
564             {
565               vl_msg_api_barrier_trace_context (am->msg_names[id]);
566               vl_msg_api_barrier_sync ();
567             }
568
569           if (m->is_autoendian)
570             m->endian_handler (the_msg);
571
572           if (PREDICT_FALSE (vec_len (am->perf_counter_cbs) != 0))
573             clib_call_callbacks (am->perf_counter_cbs, am, id,
574                                  0 /* before */ );
575
576           m->handler (the_msg);
577
578           if (PREDICT_FALSE (vec_len (am->perf_counter_cbs) != 0))
579             clib_call_callbacks (am->perf_counter_cbs, am, id,
580                                  1 /* after */ );
581
582           if (!m->is_mp_safe)
583             vl_msg_api_barrier_release ();
584         }
585     }
586   else
587     {
588       clib_warning ("no handler for msg id %d", id);
589     }
590
591   if (free_it)
592     vl_msg_api_free (the_msg);
593
594   if (PREDICT_FALSE (am->elog_trace_api_messages))
595     {
596       /* *INDENT-OFF* */
597       ELOG_TYPE_DECLARE (e) =
598         {
599           .format = "api-msg-done(%s): %s",
600           .format_args = "t4T4",
601           .n_enum_strings = 2,
602           .enum_strings =
603           {
604             "barrier",
605             "mp-safe",
606           }
607         };
608       /* *INDENT-ON* */
609
610       struct
611       {
612         u32 barrier;
613         u32 c;
614       } *ed;
615       ed = ELOG_DATA (am->elog_main, e);
616       if (m && m->name)
617         {
618           ed->c = elog_string (am->elog_main, (char *) m->name);
619           ed->barrier = !m->is_mp_safe;
620         }
621       else
622         {
623           ed->c = elog_string (am->elog_main, "BOGUS");
624           ed->barrier = 0;
625         }
626     }
627 }
628
629 void
630 vl_msg_api_handler (void *the_msg, uword msg_len)
631 {
632   api_main_t *am = vlibapi_get_main ();
633
634   msg_handler_internal (am, the_msg, msg_len,
635                         (am->rx_trace && am->rx_trace->enabled) /* trace_it */,
636                         1 /* do_it */, 1 /* free_it */);
637 }
638
639 void
640 vl_msg_api_handler_no_free (void *the_msg, uword msg_len)
641 {
642   api_main_t *am = vlibapi_get_main ();
643   msg_handler_internal (am, the_msg, msg_len,
644                         (am->rx_trace && am->rx_trace->enabled) /* trace_it */,
645                         1 /* do_it */, 0 /* free_it */);
646 }
647
648 void
649 vl_msg_api_handler_no_trace_no_free (void *the_msg, uword msg_len)
650 {
651   api_main_t *am = vlibapi_get_main ();
652   msg_handler_internal (am, the_msg, msg_len, 0 /* trace_it */, 1 /* do_it */,
653                         0 /* free_it */);
654 }
655
656 /*
657  * Add a trace record to the API message trace buffer, if
658  * API message tracing is enabled. Handy for adding sufficient
659  * data to the trace to reproduce autonomous state, as opposed to
660  * state downloaded via control-plane API messages. Example: the NAT
661  * application creates database entries based on packet traffic, not
662  * control-plane messages.
663  *
664  */
665 void
666 vl_msg_api_trace_only (void *the_msg, uword msg_len)
667 {
668   api_main_t *am = vlibapi_get_main ();
669
670   msg_handler_internal (am, the_msg, msg_len,
671                         (am->rx_trace && am->rx_trace->enabled) /* trace_it */,
672                         0 /* do_it */, 0 /* free_it */);
673 }
674
675 void
676 vl_msg_api_cleanup_handler (void *the_msg)
677 {
678   api_main_t *am = vlibapi_get_main ();
679   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
680   vl_api_msg_data_t *m = vl_api_get_msg_data (am, id);
681
682   if (PREDICT_FALSE (!m))
683     {
684       clib_warning ("_vl_msg_id too large: %d\n", id);
685       return;
686     }
687
688   if (m->cleanup_handler)
689     m->cleanup_handler (the_msg);
690
691   vl_msg_api_free (the_msg);
692 }
693
694 /*
695  * vl_msg_api_replay_handler
696  */
697 void
698 vl_msg_api_replay_handler (void *the_msg)
699 {
700   api_main_t *am = vlibapi_get_main ();
701   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
702   vl_api_msg_data_t *m = vl_api_get_msg_data (am, id);
703
704   if (PREDICT_FALSE (!m))
705     {
706       clib_warning ("_vl_msg_id too large: %d\n", id);
707       return;
708     }
709   /* do NOT trace the message... */
710   if (m->handler)
711     m->handler (the_msg);
712   /* do NOT free the message buffer... */
713 }
714
715 u32
716 vl_msg_api_get_msg_length (void *msg_arg)
717 {
718   return vl_msg_api_get_msg_length_inline (msg_arg);
719 }
720
721 /*
722  * vl_msg_api_socket_handler
723  */
724 void
725 vl_msg_api_socket_handler (void *the_msg, uword msg_len)
726 {
727   api_main_t *am = vlibapi_get_main ();
728
729   msg_handler_internal (am, the_msg, msg_len,
730                         (am->rx_trace && am->rx_trace->enabled) /* trace_it */,
731                         1 /* do_it */, 0 /* free_it */);
732 }
733
734 void
735 vl_msg_api_config (vl_msg_api_msg_config_t * c)
736 {
737   api_main_t *am = vlibapi_get_main ();
738   vl_api_msg_data_t *m;
739
740   /*
741    * This happens during the java core tests if the message
742    * dictionary is missing newly added xxx_reply_t messages.
743    * Should never happen, but since I shot myself in the foot once
744    * this way, I thought I'd make it easy to debug if I ever do
745    * it again... (;-)...
746    */
747   if (c->id == 0)
748     {
749       if (c->name)
750         clib_warning ("Trying to register %s with a NULL msg id!", c->name);
751       else
752         clib_warning ("Trying to register a NULL msg with a NULL msg id!");
753       clib_warning ("Did you forget to call setup_message_id_table?");
754       return;
755     }
756
757   vec_validate (am->msg_data, c->id);
758   m = vl_api_get_msg_data (am, c->id);
759
760   if (m->handler && m->handler != c->handler)
761     clib_warning ("BUG: re-registering 'vl_api_%s_t_handler'."
762                   "Handler was %llx, replaced by %llx",
763                   c->name, m->handler, c->handler);
764
765   m->name = c->name;
766   m->handler = c->handler;
767   m->cleanup_handler = c->cleanup;
768   m->endian_handler = c->endian;
769   m->print_handler = c->print;
770   m->print_json_handler = c->print_json;
771   m->tojson_handler = c->tojson;
772   m->fromjson_handler = c->fromjson;
773   m->calc_size_func = c->calc_size;
774   m->bounce = c->message_bounce;
775   m->is_mp_safe = c->is_mp_safe;
776   m->is_autoendian = c->is_autoendian;
777
778   m->trace_size = c->size;
779   m->trace_enable = c->traced;
780   m->replay_allowed = c->replay;
781
782   if (!am->msg_id_by_name)
783     am->msg_id_by_name = hash_create_string (0, sizeof (uword));
784
785   hash_set_mem (am->msg_id_by_name, c->name, c->id);
786 }
787
788 /*
789  * vl_msg_api_set_handlers
790  * preserve the old API for a while
791  */
792 void
793 vl_msg_api_set_handlers (int id, char *name, void *handler, void *cleanup,
794                          void *endian, void *print, int size, int traced,
795                          void *print_json, void *tojson, void *fromjson,
796                          void *calc_size)
797 {
798   vl_msg_api_msg_config_t cfg;
799   vl_msg_api_msg_config_t *c = &cfg;
800
801   clib_memset (c, 0, sizeof (*c));
802
803   c->id = id;
804   c->name = name;
805   c->handler = handler;
806   c->cleanup = cleanup;
807   c->endian = endian;
808   c->print = print;
809   c->traced = traced;
810   c->replay = 1;
811   c->message_bounce = 0;
812   c->is_mp_safe = 0;
813   c->is_autoendian = 0;
814   c->tojson = tojson;
815   c->fromjson = fromjson;
816   c->print_json = print_json;
817   c->calc_size = calc_size;
818   vl_msg_api_config (c);
819 }
820
821 void
822 vl_msg_api_clean_handlers (int msg_id)
823 {
824   vl_msg_api_msg_config_t cfg;
825   vl_msg_api_msg_config_t *c = &cfg;
826
827   clib_memset (c, 0, sizeof (*c));
828
829   c->id = msg_id;
830   vl_msg_api_config (c);
831 }
832
833 void
834 vl_msg_api_set_cleanup_handler (int msg_id, void *fp)
835 {
836   api_main_t *am = vlibapi_get_main ();
837   vl_api_msg_data_t *m = vl_api_get_msg_data (am, msg_id);
838   ASSERT (msg_id > 0);
839
840   m->cleanup_handler = fp;
841 }
842
843 void
844 vl_msg_api_queue_handler (svm_queue_t * q)
845 {
846   uword msg;
847
848   while (!svm_queue_sub (q, (u8 *) &msg, SVM_Q_WAIT, 0))
849     {
850       msgbuf_t *msgbuf = (msgbuf_t *) ((u8 *) msg - offsetof (msgbuf_t, data));
851       vl_msg_api_handler ((void *) msg, ntohl (msgbuf->data_len));
852     }
853 }
854
855 u32
856 vl_msg_api_max_length (void *mp)
857 {
858   msgbuf_t *mb;
859   u32 data_len = ~0;
860
861   /* Work out the maximum sane message length, and return it */
862   if (PREDICT_TRUE (mp != 0))
863     {
864       mb = (msgbuf_t *) (((u8 *) mp) - offsetof (msgbuf_t, data));
865       data_len = clib_net_to_host_u32 (mb->data_len);
866     }
867   return data_len;
868 }
869
870 vl_api_trace_t *
871 vl_msg_api_trace_get (api_main_t * am, vl_api_trace_which_t which)
872 {
873   switch (which)
874     {
875     case VL_API_TRACE_RX:
876       return am->rx_trace;
877     case VL_API_TRACE_TX:
878       return am->tx_trace;
879     default:
880       return 0;
881     }
882 }
883
884 void
885 vl_noop_handler (void *mp)
886 {
887 }
888
889
890 static u8 post_mortem_dump_enabled;
891
892 void
893 vl_msg_api_post_mortem_dump_enable_disable (int enable)
894 {
895   post_mortem_dump_enabled = enable;
896 }
897
898 void
899 vl_msg_api_post_mortem_dump (void)
900 {
901   api_main_t *am = vlibapi_get_main ();
902   FILE *fp;
903   char filename[64];
904   int rv;
905
906   if (post_mortem_dump_enabled == 0)
907     return;
908
909   snprintf (filename, sizeof (filename), "/tmp/api_post_mortem.%d",
910             getpid ());
911
912   fp = fopen (filename, "w");
913   if (fp == NULL)
914     {
915       rv = write (2, "Couldn't create ", 16);
916       rv = write (2, filename, strlen (filename));
917       rv = write (2, "\n", 1);
918       return;
919     }
920   rv = vl_msg_api_trace_save (am, VL_API_TRACE_RX, fp, 0);
921   fclose (fp);
922   if (rv < 0)
923     {
924       rv = write (2, "Failed to save post-mortem API trace to ", 40);
925       rv = write (2, filename, strlen (filename));
926       rv = write (2, "\n", 1);
927     }
928
929 }
930
931 /* Layered message handling support */
932
933 void
934 vl_msg_api_set_first_available_msg_id (u16 first_avail)
935 {
936   api_main_t *am = vlibapi_get_main ();
937
938   am->first_available_msg_id = first_avail;
939 }
940
941 u16
942 vl_msg_api_get_msg_ids (const char *name, int n)
943 {
944   api_main_t *am = vlibapi_get_main ();
945   u8 *name_copy;
946   vl_api_msg_range_t *rp;
947   uword *p;
948   u16 rv;
949
950   if (am->msg_range_by_name == 0)
951     am->msg_range_by_name = hash_create_string (0, sizeof (uword));
952
953   name_copy = format (0, "%s%c", name, 0);
954
955   p = hash_get_mem (am->msg_range_by_name, name_copy);
956   if (p)
957     {
958       clib_warning ("WARNING: duplicate message range registration for '%s'",
959                     name_copy);
960       vec_free (name_copy);
961       return ((u16) ~ 0);
962     }
963
964   if (n < 0 || n > 1024)
965     {
966       clib_warning
967         ("WARNING: bad number of message-IDs (%d) requested by '%s'",
968          n, name_copy);
969       vec_free (name_copy);
970       return ((u16) ~ 0);
971     }
972
973   vec_add2 (am->msg_ranges, rp, 1);
974
975   rv = rp->first_msg_id = am->first_available_msg_id;
976   am->first_available_msg_id += n;
977   rp->last_msg_id = am->first_available_msg_id - 1;
978   rp->name = name_copy;
979
980   hash_set_mem (am->msg_range_by_name, name_copy, rp - am->msg_ranges);
981
982   return rv;
983 }
984
985 void
986 vl_msg_api_add_msg_name_crc (api_main_t * am, const char *string, u32 id)
987 {
988   uword *p;
989
990   if (am->msg_index_by_name_and_crc == 0)
991     am->msg_index_by_name_and_crc = hash_create_string (0, sizeof (uword));
992
993   p = hash_get_mem (am->msg_index_by_name_and_crc, string);
994   if (p)
995     {
996       clib_warning ("attempt to redefine '%s' ignored...", string);
997       return;
998     }
999
1000   hash_set_mem (am->msg_index_by_name_and_crc, string, id);
1001 }
1002
1003 void
1004 vl_msg_api_add_version (api_main_t * am, const char *string,
1005                         u32 major, u32 minor, u32 patch)
1006 {
1007   api_version_t version = {.major = major,.minor = minor,.patch = patch };
1008   ASSERT (strlen (string) < 64);
1009   strncpy (version.name, string, 64 - 1);
1010   vec_add1 (am->api_version_list, version);
1011 }
1012
1013 u32
1014 vl_msg_api_get_msg_index (u8 * name_and_crc)
1015 {
1016   api_main_t *am = vlibapi_get_main ();
1017   uword *p;
1018
1019   if (am->msg_index_by_name_and_crc)
1020     {
1021       p = hash_get_mem (am->msg_index_by_name_and_crc, name_and_crc);
1022       if (p)
1023         return p[0];
1024     }
1025   return ~0;
1026 }
1027
1028 void *
1029 vl_msg_push_heap_w_region (svm_region_t * vlib_rp)
1030 {
1031   pthread_mutex_lock (&vlib_rp->mutex);
1032   return svm_push_data_heap (vlib_rp);
1033 }
1034
1035 void *
1036 vl_msg_push_heap (void)
1037 {
1038   api_main_t *am = vlibapi_get_main ();
1039   return vl_msg_push_heap_w_region (am->vlib_rp);
1040 }
1041
1042 void
1043 vl_msg_pop_heap_w_region (svm_region_t * vlib_rp, void *oldheap)
1044 {
1045   svm_pop_heap (oldheap);
1046   pthread_mutex_unlock (&vlib_rp->mutex);
1047 }
1048
1049 void
1050 vl_msg_pop_heap (void *oldheap)
1051 {
1052   api_main_t *am = vlibapi_get_main ();
1053   vl_msg_pop_heap_w_region (am->vlib_rp, oldheap);
1054 }
1055
1056 /* Must be nul terminated */
1057 int
1058 vl_api_c_string_to_api_string (const char *buf, vl_api_string_t * str)
1059 {
1060   /* copy without nul terminator */
1061   u32 len = strlen (buf);
1062   if (len > 0)
1063     clib_memcpy_fast (str->buf, buf, len);
1064   str->length = htonl (len);
1065   return len + sizeof (u32);
1066 }
1067
1068 /* Must NOT be nul terminated */
1069 int
1070 vl_api_vec_to_api_string (const u8 * vec, vl_api_string_t * str)
1071 {
1072   u32 len = vec_len (vec);
1073   clib_memcpy (str->buf, vec, len);
1074   str->length = htonl (len);
1075   return len + sizeof (u32);
1076 }
1077
1078 u32
1079 vl_api_string_len (vl_api_string_t * astr)
1080 {
1081   return clib_net_to_host_u32 (astr->length);
1082 }
1083
1084 u8 *
1085 vl_api_format_string (u8 * s, va_list * args)
1086 {
1087   vl_api_string_t *a = va_arg (*args, vl_api_string_t *);
1088   vec_add (s, a->buf, clib_net_to_host_u32 (a->length));
1089   return s;
1090 }
1091
1092 /*
1093  * Returns a new vector. Remember to free it after use.
1094  * NOT nul terminated.
1095  */
1096 u8 *
1097 vl_api_from_api_to_new_vec (void *mp, vl_api_string_t * astr)
1098 {
1099   u8 *v = 0;
1100
1101   if (vl_msg_api_max_length (mp) < clib_net_to_host_u32 (astr->length))
1102     return format (0, "insane astr->length %u%c",
1103                    clib_net_to_host_u32 (astr->length), 0);
1104   vec_add (v, astr->buf, clib_net_to_host_u32 (astr->length));
1105   return v;
1106 }
1107
1108 /*
1109  * Returns a new vector. Remember to free it after use.
1110  * Nul terminated.
1111  */
1112 char *
1113 vl_api_from_api_to_new_c_string (vl_api_string_t * astr)
1114 {
1115   char *v = 0;
1116   if (clib_net_to_host_u32 (astr->length) > 0)
1117     {
1118       vec_add (v, astr->buf, clib_net_to_host_u32 (astr->length));
1119       vec_add1 (v, 0);
1120     }
1121   return v;
1122 }
1123
1124 void
1125 vl_api_set_elog_main (elog_main_t * m)
1126 {
1127   api_main_t *am = vlibapi_get_main ();
1128   am->elog_main = m;
1129 }
1130
1131 int
1132 vl_api_set_elog_trace_api_messages (int enable)
1133 {
1134   int rv;
1135   api_main_t *am = vlibapi_get_main ();
1136
1137   rv = am->elog_trace_api_messages;
1138   am->elog_trace_api_messages = enable;
1139   return rv;
1140 }
1141
1142 int
1143 vl_api_get_elog_trace_api_messages (void)
1144 {
1145   api_main_t *am = vlibapi_get_main ();
1146
1147   return am->elog_trace_api_messages;
1148 }
1149
1150 /*
1151  * fd.io coding-style-patch-verification: ON
1152  *
1153  * Local Variables:
1154  * eval: (c-set-style "gnu")
1155  * End:
1156  */