Rename relevant functions to reflect authn as opposed to authz.
[libradsec.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_SOME_ERROR, __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_SOME_ERROR, __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__,
500                                   "%s: NYI", __func__);
501 #endif  /* RS_ENABLE_TLS */
502
503     default:
504       return rs_err_conn_push_fl (conn, RSE_INTERNAL, __FILE__, __LINE__,
505                                   "%s: unknown connection type: %d", __func__,
506                                   conn->realm->type);
507     }
508
509   return RSE_OK;
510 }
511
512 static void
513 _do_connect (struct rs_connection *conn)
514 {
515   struct rs_peer *p;
516   int err;
517
518   assert (conn);
519   assert (conn->active_peer);
520   p = conn->active_peer;
521
522 #if defined (DEBUG)
523   {
524     char host[80], serv[80];
525
526     getnameinfo (p->addr->ai_addr,
527                  p->addr->ai_addrlen,
528                  host, sizeof(host), serv, sizeof(serv),
529                  0 /* NI_NUMERICHOST|NI_NUMERICSERV*/);
530     rs_debug (("%s: connecting to %s:%s\n", __func__, host, serv));
531   }
532 #endif
533
534   _set_timeout (conn);
535   err = bufferevent_socket_connect (p->conn->bev, p->addr->ai_addr,
536                                     p->addr->ai_addrlen);
537   if (err < 0)
538     rs_err_conn_push_fl (p->conn, RSE_EVENT, __FILE__, __LINE__,
539                          "bufferevent_socket_connect: %s",
540                          evutil_gai_strerror (err));
541   else
542     p->conn->is_connecting = 1;
543 }
544
545 static int
546 _conn_open(struct rs_connection *conn, struct rs_packet *pkt)
547 {
548   if (_init_evb (conn))
549     return -1;
550
551   if (!conn->active_peer)
552     _pick_peer (conn);
553   if (!conn->active_peer)
554     return rs_err_conn_push_fl (conn, RSE_NOPEER, __FILE__, __LINE__, NULL);
555
556   if (_init_socket (conn, conn->active_peer))
557     return -1;
558
559   if (_init_bev (conn, conn->active_peer))
560     return -1;
561
562   if (!conn->is_connected)
563     if (!conn->is_connecting)
564       _do_connect (conn);
565
566   return RSE_OK;
567 }
568
569 static int
570 _conn_is_open_p (struct rs_connection *conn)
571 {
572   return conn->active_peer && conn->is_connected;
573 }
574
575 /* Public functions.  */
576 int
577 rs_packet_create (struct rs_connection *conn, struct rs_packet **pkt_out)
578 {
579   struct rs_packet *p;
580   RADIUS_PACKET *rpkt;
581
582   *pkt_out = NULL;
583
584   rpkt = rad_alloc (1);
585   if (!rpkt)
586     return rs_err_conn_push (conn, RSE_NOMEM, __func__);
587   rpkt->id = conn->nextid++;
588
589   p = (struct rs_packet *) malloc (sizeof (struct rs_packet));
590   if (!p)
591     {
592       rad_free (&rpkt);
593       return rs_err_conn_push (conn, RSE_NOMEM, __func__);
594     }
595   memset (p, 0, sizeof (struct rs_packet));
596   p->conn = conn;
597   p->rpkt = rpkt;
598
599   *pkt_out = p;
600   return RSE_OK;
601 }
602
603 int
604 rs_packet_create_authn_request (struct rs_connection *conn,
605                                 struct rs_packet **pkt_out,
606                                 const char *user_name, const char *user_pw)
607 {
608   struct rs_packet *pkt;
609   struct rs_attr *attr;
610
611   if (rs_packet_create (conn, pkt_out))
612     return -1;
613   pkt = *pkt_out;
614   pkt->rpkt->code = PW_AUTHENTICATION_REQUEST;
615
616   if (user_name)
617     {
618       if (rs_attr_create (conn, &attr, "User-Name", user_name))
619         return -1;
620       rs_packet_add_attr (pkt, attr);
621
622       if (user_pw)
623         {
624           if (rs_attr_create (conn, &attr, "User-Password", user_pw))
625             return -1;
626           rs_packet_add_attr (pkt, attr);
627         }
628     }
629
630   return RSE_OK;
631 }
632
633 /* User callback used when we're dispatching for user.  */
634 static void
635 _wcb (void *user_data)
636 {
637   struct rs_packet *pkt = (struct rs_packet *) user_data;
638   assert (pkt);
639   pkt->written_flag = 1;
640   bufferevent_disable (pkt->conn->bev, EV_WRITE|EV_READ);
641 }
642
643 int
644 rs_packet_send (struct rs_packet *pkt, void *user_data)
645 {
646   struct rs_connection *conn = NULL;
647   int err = 0;
648
649   assert (pkt);
650   assert (pkt->conn);
651   conn = pkt->conn;
652
653   if (_conn_is_open_p (conn))
654     _do_send (pkt);
655   else
656     if (_conn_open (conn, pkt))
657       return -1;
658
659   assert (conn->evb);
660   assert (conn->bev);
661   assert (conn->active_peer);
662   assert (conn->fd >= 0);
663
664   conn->user_data = user_data;
665   bufferevent_setcb (conn->bev, NULL, _write_cb, _event_cb, pkt);
666   bufferevent_enable (conn->bev, EV_WRITE);
667
668   /* Do dispatch, unless the user wants to do it herself.  */
669   if (!conn->user_dispatch_flag)
670     {
671       conn->callbacks.sent_cb = _wcb;
672       conn->user_data = pkt;
673       rs_debug (("%s: entering event loop\n", __func__));
674       err = event_base_dispatch (conn->evb);
675       if (err < 0)
676         return rs_err_conn_push_fl (pkt->conn, RSE_EVENT, __FILE__, __LINE__,
677                                     "event_base_dispatch: %s",
678                                     evutil_gai_strerror (err));
679       rs_debug (("%s: event loop done\n", __func__));
680       conn->callbacks.sent_cb = NULL;
681       conn->user_data = NULL;
682
683       if (!pkt->written_flag)
684         return -1;
685     }
686
687   return RSE_OK;
688 }
689
690 static void
691 _rcb (struct rs_packet *packet, void *user_data)
692 {
693   struct rs_packet *pkt = (struct rs_packet *) user_data;
694   assert (pkt);
695   pkt->valid_flag = 1;
696   bufferevent_disable (pkt->conn->bev, EV_WRITE|EV_READ);
697 }
698
699 /* Special function used in libradsec blocking dispatching mode,
700    i.e. with socket set to block on read/write and with no libradsec
701    callbacks registered.
702
703    For any other use of libradsec, a the received_cb callback should
704    be registered in the callbacks member of struct rs_connection.
705
706    On successful reception, verification and decoding of a RADIUS
707    message, PKT_OUT will upon return point at a pointer to a struct
708    rs_packet containing the message.
709
710    If anything goes wrong or if the read times out (TODO: explain),
711    PKT_OUT will point at the NULL pointer and one or more errors are
712    pushed on the connection (available through rs_err_conn_pop()).  */
713
714 int
715 rs_conn_receive_packet (struct rs_connection *conn,
716                         struct rs_packet *request,
717                         struct rs_packet **pkt_out)
718 {
719   int err = 0;
720   struct rs_packet *pkt = NULL;
721
722   assert (conn);
723   assert (conn->realm);
724   assert (!conn->user_dispatch_flag); /* Dispatching mode only.  */
725
726   if (rs_packet_create (conn, pkt_out))
727     return -1;
728   pkt = *pkt_out;
729   pkt->conn = conn;
730   pkt->original = request;
731
732   assert (conn->evb);
733   assert (conn->bev);
734   assert (conn->active_peer);
735   assert (conn->fd >= 0);
736
737   bufferevent_setwatermark (conn->bev, EV_READ, RS_HEADER_LEN, 0);
738   bufferevent_setcb (conn->bev, _read_cb, NULL, _event_cb, pkt);
739   bufferevent_enable (conn->bev, EV_READ);
740   conn->callbacks.received_cb = _rcb;
741   conn->user_data = pkt;
742
743   /* Dispatch.  */
744   rs_debug (("%s: entering event loop\n", __func__));
745   err = event_base_dispatch (conn->evb);
746   conn->callbacks.received_cb = NULL;
747   if (err < 0)
748     return rs_err_conn_push_fl (pkt->conn, RSE_EVENT, __FILE__, __LINE__,
749                                 "event_base_dispatch: %s",
750                                 evutil_gai_strerror (err));
751   rs_debug (("%s: event loop done\n", __func__));
752
753   if (!pkt->valid_flag)
754     return -1;
755
756 #if defined (DEBUG)
757       rs_dump_packet (pkt);
758 #endif
759
760   pkt->original = NULL;         /* FIXME: Why?  */
761   return RSE_OK;
762 }
763
764 void
765 rs_packet_add_attr(struct rs_packet *pkt, struct rs_attr *attr)
766 {
767   pairadd (&pkt->rpkt->vps, attr->vp);
768   attr->pkt = pkt;
769 }
770
771 struct radius_packet *
772 rs_packet_frpkt(struct rs_packet *pkt)
773 {
774   assert (pkt);
775   return pkt->rpkt;
776 }
777
778 void
779 rs_packet_destroy(struct rs_packet *pkt)
780 {
781   if (pkt)
782     {
783       // FIXME: memory leak! TODO: free all attributes
784       rad_free (&pkt->rpkt);
785       rs_free (pkt->conn->ctx, pkt);
786     }
787 }