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