6760ceeced34630fbf977f4098ad1501b8b9bf52
[radsecproxy.git] / lib / packet.c
1 /* See the file COPYING for licensing information.  */
2
3 #if defined HAVE_CONFIG_H
4 #include <config.h>
5 #endif
6
7 #include <stdlib.h>
8 #include <string.h>
9 #include <errno.h>
10 #include <sys/time.h>
11 #include <assert.h>
12 #include <freeradius/libradius.h>
13 #include <event2/event.h>
14 #include <event2/bufferevent.h>
15 #include <radsec/radsec.h>
16 #include <radsec/radsec-impl.h>
17 #include "tls.h"
18 #include "debug.h"
19 #if defined (RS_ENABLE_TLS)
20 #include <event2/bufferevent_ssl.h>
21 #include <openssl/err.h>
22 #endif
23 #if defined (DEBUG)
24 #include <netdb.h>
25 #include <sys/socket.h>
26 #include <event2/buffer.h>
27 #endif
28
29 static int
30 _loopbreak (struct rs_connection *conn)
31 {
32   int err = event_base_loopbreak (conn->evb);
33   if (err < 0)
34     rs_err_conn_push_fl (conn, RSE_EVENT, __FILE__, __LINE__,
35                          "event_base_loopbreak: %s",
36                          evutil_gai_strerror (err));
37   return err;
38 }
39
40 static int
41 _do_send (struct rs_packet *pkt)
42 {
43   int err;
44   VALUE_PAIR *vp;
45
46   assert (pkt->rpkt);
47   assert (!pkt->original);
48
49   vp = paircreate (PW_MESSAGE_AUTHENTICATOR, PW_TYPE_OCTETS);
50   if (!vp)
51     return rs_err_conn_push_fl (pkt->conn, RSE_NOMEM, __FILE__, __LINE__,
52                                 "paircreate: %s", fr_strerror ());
53   pairadd (&pkt->rpkt->vps, vp);
54
55   if (rad_encode (pkt->rpkt, NULL, pkt->conn->active_peer->secret))
56     return rs_err_conn_push_fl (pkt->conn, RSE_FR, __FILE__, __LINE__,
57                                 "rad_encode: %s", fr_strerror ());
58   if (rad_sign (pkt->rpkt, NULL, pkt->conn->active_peer->secret))
59     return rs_err_conn_push_fl (pkt->conn, RSE_FR, __FILE__, __LINE__,
60                                 "rad_sign: %s", fr_strerror ());
61 #if defined (DEBUG)
62   {
63     char host[80], serv[80];
64
65     getnameinfo (pkt->conn->active_peer->addr->ai_addr,
66                  pkt->conn->active_peer->addr->ai_addrlen,
67                  host, sizeof(host), serv, sizeof(serv),
68                  0 /* NI_NUMERICHOST|NI_NUMERICSERV*/);
69     rs_debug (("%s: about to send this to %s:%s:\n", __func__, host, serv));
70     rs_dump_packet (pkt);
71   }
72 #endif
73
74   err = bufferevent_write (pkt->conn->bev, pkt->rpkt->data,
75                            pkt->rpkt->data_len);
76   if (err < 0)
77     return rs_err_conn_push_fl (pkt->conn, RSE_EVENT, __FILE__, __LINE__,
78                                 "bufferevent_write: %s",
79                                 evutil_gai_strerror (err));
80   return RSE_OK;
81 }
82
83 static void
84 _on_connect (struct rs_connection *conn)
85 {
86   conn->is_connected = 1;
87   rs_debug (("%s: %p connected\n", __func__, conn->active_peer));
88   evtimer_del (conn->tev);
89   if (conn->callbacks.connected_cb)
90     conn->callbacks.connected_cb (conn->user_data);
91 }
92
93 static void
94 _on_disconnect (struct rs_connection *conn)
95 {
96   conn->is_connecting = 0;
97   conn->is_connected = 0;
98   rs_debug (("%s: %p disconnected\n", __func__, conn->active_peer));
99   if (conn->callbacks.disconnected_cb)
100     conn->callbacks.disconnected_cb (conn->user_data);
101 }
102
103 static void
104 _event_cb (struct bufferevent *bev, short events, void *ctx)
105 {
106   struct rs_packet *pkt = (struct rs_packet *)ctx;
107   struct rs_connection *conn = NULL;
108   struct rs_peer *p = NULL;
109   int sockerr = 0;
110 #if defined (RS_ENABLE_TLS)
111   unsigned long tlserr = 0;
112 #endif
113
114   assert (pkt);
115   assert (pkt->conn);
116   assert (pkt->conn->active_peer);
117   conn = pkt->conn;
118   p = conn->active_peer;
119
120   conn->is_connecting = 0;
121   if (events & BEV_EVENT_CONNECTED)
122     {
123       _on_connect (conn);
124       if (_do_send (pkt))
125         rs_debug (("%s: error sending\n", __func__));
126     }
127   else if (events & BEV_EVENT_EOF)
128     {
129       _on_disconnect (conn);
130     }
131   else if (events & BEV_EVENT_TIMEOUT)
132     {
133       rs_debug (("%s: %p times out on %s\n", __func__, p,
134                  (events & BEV_EVENT_READING) ? "read" : "write"));
135       rs_err_conn_push_fl (pkt->conn, RSE_IOTIMEOUT, __FILE__, __LINE__, NULL);
136     }
137   else if (events & BEV_EVENT_ERROR)
138     {
139       sockerr = evutil_socket_geterror (conn->active_peer->fd);
140       if (sockerr == 0) /* FIXME: True that errno == 0 means closed? */
141         {
142           _on_disconnect (conn);
143         }
144       else
145         {
146           rs_err_conn_push_fl (pkt->conn, RSE_SOCKERR, __FILE__, __LINE__,
147                                "%d: socket error %d (%s)",
148                                conn->fd,
149                                sockerr,
150                                evutil_socket_error_to_string (sockerr));
151           rs_debug (("%s: socket error on fd %d: %s (%d)\n", __func__,
152                      conn->fd,
153                      evutil_socket_error_to_string (sockerr),
154                      sockerr));
155         }
156 #if defined (RS_ENABLE_TLS)
157       if (conn->tls_ssl)        /* FIXME: correct check?  */
158         {
159           for (tlserr = bufferevent_get_openssl_error (conn->bev);
160                tlserr;
161                tlserr = bufferevent_get_openssl_error (conn->bev))
162             {
163               rs_debug (("%s: openssl error: %s\n", __func__,
164                          ERR_error_string (tlserr, NULL)));
165               rs_err_conn_push_fl (pkt->conn, RSE_SSLERR, __FILE__, __LINE__,
166                                    ERR_error_string (tlserr, NULL));
167             }
168         }
169 #endif  /* RS_ENABLE_TLS */
170       _loopbreak (conn);
171     }
172
173 #if defined (DEBUG)
174   if (events & BEV_EVENT_ERROR && events != BEV_EVENT_ERROR)
175     rs_debug (("%s: BEV_EVENT_ERROR and more: 0x%x\n", __func__, events));
176 #endif
177 }
178
179 static void
180 _write_cb (struct bufferevent *bev, void *ctx)
181 {
182   struct rs_packet *pkt = (struct rs_packet *) ctx;
183
184   assert (pkt);
185   assert (pkt->conn);
186
187   if (pkt->conn->callbacks.sent_cb)
188     pkt->conn->callbacks.sent_cb (pkt->conn->user_data);
189 }
190
191 /* Read one RADIUS packet header.  Return !0 on error.  A return value
192    of 0 means that we need more data.  */
193 static int
194 _read_header (struct rs_packet *pkt)
195 {
196   size_t n = 0;
197
198   n = bufferevent_read (pkt->conn->bev, pkt->hdr, RS_HEADER_LEN);
199   if (n == RS_HEADER_LEN)
200     {
201       pkt->hdr_read_flag = 1;
202       pkt->rpkt->data_len = (pkt->hdr[2] << 8) + pkt->hdr[3];
203       if (pkt->rpkt->data_len < 20 || pkt->rpkt->data_len > 4096)
204         {
205           bufferevent_free (pkt->conn->bev); /* Close connection.  */
206           return rs_err_conn_push (pkt->conn, RSE_INVALID_PKT,
207                                    "invalid packet length: %d",
208                                    pkt->rpkt->data_len);
209         }
210       pkt->rpkt->data = rs_malloc (pkt->conn->ctx, pkt->rpkt->data_len);
211       if (!pkt->rpkt->data)
212         {
213           bufferevent_free (pkt->conn->bev); /* Close connection.  */
214           return rs_err_conn_push_fl (pkt->conn, RSE_NOMEM, __FILE__, __LINE__,
215                                       NULL);
216         }
217       memcpy (pkt->rpkt->data, pkt->hdr, RS_HEADER_LEN);
218       bufferevent_setwatermark (pkt->conn->bev, EV_READ,
219                                 pkt->rpkt->data_len - RS_HEADER_LEN, 0);
220       rs_debug (("%s: packet header read, total pkt len=%d\n",
221                  __func__, pkt->rpkt->data_len));
222     }
223   else if (n < 0)
224     {
225       rs_debug (("%s: buffer frozen while reading header\n", __func__));
226     }
227   else      /* Error: libevent gave us less than the low watermark. */
228     {
229       bufferevent_free (pkt->conn->bev); /* Close connection.  */
230       return rs_err_conn_push_fl (pkt->conn, RSE_INTERNAL, __FILE__, __LINE__,
231                                   "got %d octets reading header", n);
232     }
233
234   return 0;
235 }
236
237 static int
238 _read_packet (struct rs_packet *pkt)
239 {
240   size_t n = 0;
241
242   rs_debug (("%s: trying to read %d octets of packet data\n", __func__,
243              pkt->rpkt->data_len - RS_HEADER_LEN));
244
245   n = bufferevent_read (pkt->conn->bev,
246                         pkt->rpkt->data + RS_HEADER_LEN,
247                         pkt->rpkt->data_len - RS_HEADER_LEN);
248
249   rs_debug (("%s: read %ld octets of packet data\n", __func__, n));
250
251   if (n == pkt->rpkt->data_len - RS_HEADER_LEN)
252     {
253       bufferevent_disable (pkt->conn->bev, EV_READ);
254       rs_debug (("%s: complete packet read\n", __func__));
255       pkt->hdr_read_flag = 0;
256       memset (pkt->hdr, 0, sizeof(*pkt->hdr));
257
258       /* Checks done by rad_packet_ok:
259          - lenghts (FIXME: checks really ok for tcp?)
260          - invalid code field
261          - attribute lengths >= 2
262          - attribute sizes adding up correctly  */
263       if (!rad_packet_ok (pkt->rpkt, 0) != 0)
264         {
265           bufferevent_free (pkt->conn->bev); /* Close connection.  */
266           return rs_err_conn_push_fl (pkt->conn, RSE_FR, __FILE__, __LINE__,
267                                       "invalid packet: %s", fr_strerror ());
268         }
269
270       /* TODO: Verify that reception of an unsolicited response packet
271          results in connection being closed.  */
272
273       /* If we have a request to match this response against, verify
274          and decode the response.  */
275       if (pkt->original)
276         {
277           /* Verify header and message authenticator.  */
278           if (rad_verify (pkt->rpkt, pkt->original->rpkt,
279                           pkt->conn->active_peer->secret))
280             {
281               bufferevent_free (pkt->conn->bev); /* Close connection.  */
282               return rs_err_conn_push_fl (pkt->conn, RSE_FR, __FILE__, __LINE__,
283                                           "rad_verify: %s", fr_strerror ());
284             }
285
286           /* Decode and decrypt.  */
287           if (rad_decode (pkt->rpkt, pkt->original->rpkt,
288                           pkt->conn->active_peer->secret))
289             {
290               bufferevent_free (pkt->conn->bev); /* Close connection.  */
291               return rs_err_conn_push_fl (pkt->conn, RSE_FR, __FILE__, __LINE__,
292                                           "rad_decode: %s", fr_strerror ());
293             }
294         }
295
296 #if defined (DEBUG)
297       /* Find out what happens if there's data left in the buffer.  */
298       {
299         size_t rest = 0;
300         rest = evbuffer_get_length (bufferevent_get_input (pkt->conn->bev));
301         if (rest)
302           rs_debug (("%s: returning with %d octets left in buffer\n", __func__,
303                      rest));
304       }
305 #endif
306
307       /* Hand over message to user, changes ownership of pkt.  Don't
308          touch it afterwards -- it might have been freed.  */
309       if (pkt->conn->callbacks.received_cb)
310         pkt->conn->callbacks.received_cb (pkt, pkt->conn->user_data);
311     }
312   else if (n < 0)               /* Buffer frozen.  */
313     rs_debug (("%s: buffer frozen when reading packet\n", __func__));
314   else                          /* Short packet.  */
315     rs_debug (("%s: waiting for another %d octets\n", __func__,
316                pkt->rpkt->data_len - RS_HEADER_LEN - n));
317
318   return 0;
319 }
320
321 /* Read callback for TCP.
322
323    Read exactly one RADIUS message from BEV and store it in struct
324    rs_packet passed in CTX (hereby called 'pkt').
325
326    Verify the received packet against pkt->original, if !NULL.
327
328    Inform upper layer about successful reception of valid RADIUS
329    message by invoking conn->callbacks.recevied_cb(), if !NULL.  */
330 static void
331 _read_cb (struct bufferevent *bev, void *ctx)
332 {
333   struct rs_packet *pkt = (struct rs_packet *) ctx;
334
335   assert (pkt);
336   assert (pkt->conn);
337   assert (pkt->rpkt);
338
339   pkt->rpkt->sockfd = pkt->conn->fd;
340   pkt->rpkt->vps = NULL;
341
342   if (!pkt->hdr_read_flag)
343     if (_read_header (pkt))
344       return;
345   _read_packet (pkt);
346 }
347
348 static void
349 _evlog_cb (int severity, const char *msg)
350 {
351   const char *sevstr;
352   switch (severity)
353     {
354     case _EVENT_LOG_DEBUG:
355 #if !defined (DEBUG_LEVENT)
356       return;
357 #endif
358       sevstr = "debug";
359       break;
360     case _EVENT_LOG_MSG:
361       sevstr = "msg";
362       break;
363     case _EVENT_LOG_WARN:
364       sevstr = "warn";
365       break;
366     case _EVENT_LOG_ERR:
367       sevstr = "err";
368       break;
369     default:
370       sevstr = "???";
371       break;
372     }
373   fprintf (stderr, "libevent: [%s] %s\n", sevstr, msg); /* FIXME: stderr?  */
374 }
375
376 static int
377 _init_evb (struct rs_connection *conn)
378 {
379   if (conn->evb)
380     return RSE_OK;
381
382 #if defined (DEBUG)
383   event_enable_debug_mode ();
384 #endif
385   event_set_log_callback (_evlog_cb);
386   conn->evb = event_base_new ();
387   if (!conn->evb)
388     return rs_err_conn_push_fl (conn, RSE_EVENT, __FILE__, __LINE__,
389                                 "event_base_new");
390
391   return RSE_OK;
392 }
393
394 static int
395 _init_socket (struct rs_connection *conn, struct rs_peer *p)
396 {
397   if (conn->fd != -1)
398     return RSE_OK;
399
400   assert (p->addr);
401   conn->fd = socket (p->addr->ai_family, p->addr->ai_socktype,
402                      p->addr->ai_protocol);
403   if (conn->fd < 0)
404     return rs_err_conn_push_fl (conn, RSE_SOCKERR, __FILE__, __LINE__,
405                                 strerror (errno));
406   if (evutil_make_socket_nonblocking (conn->fd) < 0)
407     {
408       evutil_closesocket (conn->fd);
409       conn->fd = -1;
410       return rs_err_conn_push_fl (conn, RSE_SOCKERR, __FILE__, __LINE__,
411                                   strerror (errno));
412     }
413   return RSE_OK;
414 }
415
416 static struct rs_peer *
417 _pick_peer (struct rs_connection *conn)
418 {
419   assert (conn);
420
421   if (conn->active_peer)
422     conn->active_peer = conn->active_peer->next; /* Next.  */
423   if (!conn->active_peer)
424     conn->active_peer = conn->peers; /* From the top.  */
425
426   return conn->active_peer;
427 }
428
429 static void
430 _conn_timeout_cb (int fd, short event, void *data)
431 {
432   struct rs_connection *conn;
433
434   assert (data);
435   conn = (struct rs_connection *) data;
436
437   if (event & EV_TIMEOUT)
438     {
439       rs_debug (("%s: connection timeout on %p (fd %d) connecting to %p\n",
440                  __func__, conn, conn->fd, conn->active_peer));
441       conn->is_connecting = 0;
442       rs_err_conn_push_fl (conn, RSE_IOTIMEOUT, __FILE__, __LINE__, NULL);
443       _loopbreak (conn);
444     }
445 }
446 static int
447 _set_timeout (struct rs_connection *conn)
448 {
449   struct timeval tv;
450
451   if (!conn->tev)
452     conn->tev = evtimer_new (conn->evb, _conn_timeout_cb, conn);
453   if (!conn->tev)
454     return rs_err_conn_push_fl (conn, RSE_EVENT, __FILE__, __LINE__,
455                                 "event_new");
456   tv.tv_sec = conn->realm->timeout;
457   tv.tv_usec = 0;
458   evtimer_add (conn->tev, &tv);
459
460   return RSE_OK;
461 }
462
463 static int
464 _init_bev (struct rs_connection *conn, struct rs_peer *peer)
465 {
466   if (conn->bev)
467     return RSE_OK;
468
469   switch (conn->realm->type)
470     {
471     case RS_CONN_TYPE_UDP:
472       /* Fall through.  */
473       /* NOTE: We know this is wrong for several reasons, most notably
474          because libevent doesn't work as expected with UDP.  The
475          timeout handling is wrong too.  */
476     case RS_CONN_TYPE_TCP:
477       conn->bev = bufferevent_socket_new (conn->evb, conn->fd, 0);
478       if (!conn->bev)
479         return rs_err_conn_push_fl (conn, RSE_EVENT, __FILE__, __LINE__,
480                                     "bufferevent_socket_new");
481       break;
482
483 #if defined (RS_ENABLE_TLS)
484     case RS_CONN_TYPE_TLS:
485       if (rs_tls_init (conn))
486         return -1;
487       /* Would be convenient to pass BEV_OPT_CLOSE_ON_FREE but things
488          seem to break when be_openssl_ctrl() (in libevent) calls
489          SSL_set_bio() after BIO_new_socket() with flag=1.  */
490       conn->bev =
491         bufferevent_openssl_socket_new (conn->evb, conn->fd, conn->tls_ssl,
492                                         BUFFEREVENT_SSL_CONNECTING, 0);
493       if (!conn->bev)
494         return rs_err_conn_push_fl (conn, RSE_EVENT, __FILE__, __LINE__,
495                                     "bufferevent_openssl_socket_new");
496       break;
497
498     case RS_CONN_TYPE_DTLS:
499       return rs_err_conn_push_fl (conn, RSE_NOSYS, __FILE__, __LINE__, NULL);
500 #endif  /* RS_ENABLE_TLS */
501
502     default:
503       return rs_err_conn_push_fl (conn, RSE_INTERNAL, __FILE__, __LINE__,
504                                   "%s: unknown connection type: %d", __func__,
505                                   conn->realm->type);
506     }
507
508   return RSE_OK;
509 }
510
511 static void
512 _do_connect (struct rs_connection *conn)
513 {
514   struct rs_peer *p;
515   int err;
516
517   assert (conn);
518   assert (conn->active_peer);
519   p = conn->active_peer;
520
521 #if defined (DEBUG)
522   {
523     char host[80], serv[80];
524
525     getnameinfo (p->addr->ai_addr,
526                  p->addr->ai_addrlen,
527                  host, sizeof(host), serv, sizeof(serv),
528                  0 /* NI_NUMERICHOST|NI_NUMERICSERV*/);
529     rs_debug (("%s: connecting to %s:%s\n", __func__, host, serv));
530   }
531 #endif
532
533   _set_timeout (conn);
534   err = bufferevent_socket_connect (p->conn->bev, p->addr->ai_addr,
535                                     p->addr->ai_addrlen);
536   if (err < 0)
537     rs_err_conn_push_fl (p->conn, RSE_EVENT, __FILE__, __LINE__,
538                          "bufferevent_socket_connect: %s",
539                          evutil_gai_strerror (err));
540   else
541     p->conn->is_connecting = 1;
542 }
543
544 static int
545 _conn_open(struct rs_connection *conn, struct rs_packet *pkt)
546 {
547   if (_init_evb (conn))
548     return -1;
549
550   if (!conn->active_peer)
551     _pick_peer (conn);
552   if (!conn->active_peer)
553     return rs_err_conn_push_fl (conn, RSE_NOPEER, __FILE__, __LINE__, NULL);
554
555   if (_init_socket (conn, conn->active_peer))
556     return -1;
557
558   if (_init_bev (conn, conn->active_peer))
559     return -1;
560
561   if (!conn->is_connected)
562     if (!conn->is_connecting)
563       _do_connect (conn);
564
565   return RSE_OK;
566 }
567
568 static int
569 _conn_is_open_p (struct rs_connection *conn)
570 {
571   return conn->active_peer && conn->is_connected;
572 }
573
574 /* Public functions.  */
575 int
576 rs_packet_create (struct rs_connection *conn, struct rs_packet **pkt_out)
577 {
578   struct rs_packet *p;
579   RADIUS_PACKET *rpkt;
580
581   *pkt_out = NULL;
582
583   rpkt = rad_alloc (1);
584   if (!rpkt)
585     return rs_err_conn_push (conn, RSE_NOMEM, __func__);
586   rpkt->id = conn->nextid++;
587
588   p = (struct rs_packet *) malloc (sizeof (struct rs_packet));
589   if (!p)
590     {
591       rad_free (&rpkt);
592       return rs_err_conn_push (conn, RSE_NOMEM, __func__);
593     }
594   memset (p, 0, sizeof (struct rs_packet));
595   p->conn = conn;
596   p->rpkt = rpkt;
597
598   *pkt_out = p;
599   return RSE_OK;
600 }
601
602 int
603 rs_packet_create_authn_request (struct rs_connection *conn,
604                                 struct rs_packet **pkt_out,
605                                 const char *user_name, const char *user_pw)
606 {
607   struct rs_packet *pkt;
608   struct rs_attr *attr;
609
610   if (rs_packet_create (conn, pkt_out))
611     return -1;
612   pkt = *pkt_out;
613   pkt->rpkt->code = PW_AUTHENTICATION_REQUEST;
614
615   if (user_name)
616     {
617       if (rs_attr_create (conn, &attr, "User-Name", user_name))
618         return -1;
619       rs_packet_add_attr (pkt, attr);
620
621       if (user_pw)
622         {
623           if (rs_attr_create (conn, &attr, "User-Password", user_pw))
624             return -1;
625           rs_packet_add_attr (pkt, attr);
626         }
627     }
628
629   return RSE_OK;
630 }
631
632 /* User callback used when we're dispatching for user.  */
633 static void
634 _wcb (void *user_data)
635 {
636   struct rs_packet *pkt = (struct rs_packet *) user_data;
637   assert (pkt);
638   pkt->written_flag = 1;
639   bufferevent_disable (pkt->conn->bev, EV_WRITE|EV_READ);
640 }
641
642 int
643 rs_packet_send (struct rs_packet *pkt, void *user_data)
644 {
645   struct rs_connection *conn = NULL;
646   int err = 0;
647
648   assert (pkt);
649   assert (pkt->conn);
650   conn = pkt->conn;
651
652   if (_conn_is_open_p (conn))
653     _do_send (pkt);
654   else
655     if (_conn_open (conn, pkt))
656       return -1;
657
658   assert (conn->evb);
659   assert (conn->bev);
660   assert (conn->active_peer);
661   assert (conn->fd >= 0);
662
663   conn->user_data = user_data;
664   bufferevent_setcb (conn->bev, NULL, _write_cb, _event_cb, pkt);
665   bufferevent_enable (conn->bev, EV_WRITE);
666
667   /* Do dispatch, unless the user wants to do it herself.  */
668   if (!conn->user_dispatch_flag)
669     {
670       conn->callbacks.sent_cb = _wcb;
671       conn->user_data = pkt;
672       rs_debug (("%s: entering event loop\n", __func__));
673       err = event_base_dispatch (conn->evb);
674       if (err < 0)
675         return rs_err_conn_push_fl (pkt->conn, RSE_EVENT, __FILE__, __LINE__,
676                                     "event_base_dispatch: %s",
677                                     evutil_gai_strerror (err));
678       rs_debug (("%s: event loop done\n", __func__));
679       conn->callbacks.sent_cb = NULL;
680       conn->user_data = NULL;
681
682       if (!pkt->written_flag)
683         return -1;
684     }
685
686   return RSE_OK;
687 }
688
689 static void
690 _rcb (struct rs_packet *packet, void *user_data)
691 {
692   struct rs_packet *pkt = (struct rs_packet *) user_data;
693   assert (pkt);
694   pkt->valid_flag = 1;
695   bufferevent_disable (pkt->conn->bev, EV_WRITE|EV_READ);
696 }
697
698 /* Special function used in libradsec blocking dispatching mode,
699    i.e. with socket set to block on read/write and with no libradsec
700    callbacks registered.
701
702    For any other use of libradsec, a the received_cb callback should
703    be registered in the callbacks member of struct rs_connection.
704
705    On successful reception, verification and decoding of a RADIUS
706    message, PKT_OUT will upon return point at a pointer to a struct
707    rs_packet containing the message.
708
709    If anything goes wrong or if the read times out (TODO: explain),
710    PKT_OUT will point at the NULL pointer and one or more errors are
711    pushed on the connection (available through rs_err_conn_pop()).  */
712
713 int
714 rs_conn_receive_packet (struct rs_connection *conn,
715                         struct rs_packet *request,
716                         struct rs_packet **pkt_out)
717 {
718   int err = 0;
719   struct rs_packet *pkt = NULL;
720
721   assert (conn);
722   assert (conn->realm);
723   assert (!conn->user_dispatch_flag); /* Dispatching mode only.  */
724
725   if (rs_packet_create (conn, pkt_out))
726     return -1;
727   pkt = *pkt_out;
728   pkt->conn = conn;
729   pkt->original = request;
730
731   assert (conn->evb);
732   assert (conn->bev);
733   assert (conn->active_peer);
734   assert (conn->fd >= 0);
735
736   bufferevent_setwatermark (conn->bev, EV_READ, RS_HEADER_LEN, 0);
737   bufferevent_setcb (conn->bev, _read_cb, NULL, _event_cb, pkt);
738   bufferevent_enable (conn->bev, EV_READ);
739   conn->callbacks.received_cb = _rcb;
740   conn->user_data = pkt;
741
742   /* Dispatch.  */
743   rs_debug (("%s: entering event loop\n", __func__));
744   err = event_base_dispatch (conn->evb);
745   conn->callbacks.received_cb = NULL;
746   if (err < 0)
747     return rs_err_conn_push_fl (pkt->conn, RSE_EVENT, __FILE__, __LINE__,
748                                 "event_base_dispatch: %s",
749                                 evutil_gai_strerror (err));
750   rs_debug (("%s: event loop done\n", __func__));
751
752   if (!pkt->valid_flag)
753     return -1;
754
755 #if defined (DEBUG)
756       rs_dump_packet (pkt);
757 #endif
758
759   pkt->original = NULL;         /* FIXME: Why?  */
760   return RSE_OK;
761 }
762
763 void
764 rs_packet_add_attr(struct rs_packet *pkt, struct rs_attr *attr)
765 {
766   pairadd (&pkt->rpkt->vps, attr->vp);
767   attr->pkt = pkt;
768 }
769
770 struct radius_packet *
771 rs_packet_frpkt(struct rs_packet *pkt)
772 {
773   assert (pkt);
774   return pkt->rpkt;
775 }
776
777 void
778 rs_packet_destroy(struct rs_packet *pkt)
779 {
780   if (pkt)
781     {
782       // FIXME: memory leak! TODO: free all attributes
783       rad_free (&pkt->rpkt);
784       rs_free (pkt->conn->ctx, pkt);
785     }
786 }