Cosmetic changes.
[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 *user_data)
334 {
335   struct rs_packet *pkt = (struct rs_packet *) user_data;
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                                 "socket: %d (%s)",
408                                 errno, strerror (errno));
409   if (evutil_make_socket_nonblocking (conn->fd) < 0)
410     {
411       evutil_closesocket (conn->fd);
412       conn->fd = -1;
413       return rs_err_conn_push_fl (conn, RSE_SOCKERR, __FILE__, __LINE__,
414                                   "evutil_make_socket_nonblocking: %d (%s)",
415                                   errno, strerror (errno));
416     }
417   return RSE_OK;
418 }
419
420 static struct rs_peer *
421 _pick_peer (struct rs_connection *conn)
422 {
423   assert (conn);
424
425   if (conn->active_peer)
426     conn->active_peer = conn->active_peer->next; /* Next.  */
427   if (!conn->active_peer)
428     conn->active_peer = conn->peers; /* From the top.  */
429
430   return conn->active_peer;
431 }
432
433 static void
434 _conn_timeout_cb (int fd, short event, void *data)
435 {
436   struct rs_connection *conn;
437
438   assert (data);
439   conn = (struct rs_connection *) data;
440
441   if (event & EV_TIMEOUT)
442     {
443       rs_debug (("%s: connection timeout on %p (fd %d) connecting to %p\n",
444                  __func__, conn, conn->fd, conn->active_peer));
445       conn->is_connecting = 0;
446       rs_err_conn_push_fl (conn, RSE_TIMEOUT_IO, __FILE__, __LINE__, NULL);
447       _loopbreak (conn);
448     }
449 }
450 static int
451 _set_timeout (struct rs_connection *conn)
452 {
453   struct timeval tv;
454
455   if (!conn->tev)
456     conn->tev = evtimer_new (conn->evb, _conn_timeout_cb, conn);
457   if (!conn->tev)
458     return rs_err_conn_push_fl (conn, RSE_EVENT, __FILE__, __LINE__,
459                                 "evtimer_new");
460   tv.tv_sec = conn->realm->timeout;
461   tv.tv_usec = 0;
462   evtimer_add (conn->tev, &tv);
463
464   return RSE_OK;
465 }
466
467 static int
468 _init_bev (struct rs_connection *conn, struct rs_peer *peer)
469 {
470   if (conn->bev)
471     return RSE_OK;
472
473   switch (conn->realm->type)
474     {
475     case RS_CONN_TYPE_UDP:
476       /* Fall through.  */
477       /* NOTE: We know this is wrong for several reasons, most notably
478          because libevent doesn't work as expected with UDP.  The
479          timeout handling is wrong too.  */
480     case RS_CONN_TYPE_TCP:
481       conn->bev = bufferevent_socket_new (conn->evb, conn->fd, 0);
482       if (!conn->bev)
483         return rs_err_conn_push_fl (conn, RSE_EVENT, __FILE__, __LINE__,
484                                     "bufferevent_socket_new");
485       break;
486
487 #if defined (RS_ENABLE_TLS)
488     case RS_CONN_TYPE_TLS:
489       if (rs_tls_init (conn))
490         return -1;
491       /* Would be convenient to pass BEV_OPT_CLOSE_ON_FREE but things
492          seem to break when be_openssl_ctrl() (in libevent) calls
493          SSL_set_bio() after BIO_new_socket() with flag=1.  */
494       conn->bev =
495         bufferevent_openssl_socket_new (conn->evb, conn->fd, conn->tls_ssl,
496                                         BUFFEREVENT_SSL_CONNECTING, 0);
497       if (!conn->bev)
498         return rs_err_conn_push_fl (conn, RSE_EVENT, __FILE__, __LINE__,
499                                     "bufferevent_openssl_socket_new");
500       break;
501
502     case RS_CONN_TYPE_DTLS:
503       return rs_err_conn_push_fl (conn, RSE_NOSYS, __FILE__, __LINE__, NULL);
504 #endif  /* RS_ENABLE_TLS */
505
506     default:
507       return rs_err_conn_push_fl (conn, RSE_INTERNAL, __FILE__, __LINE__,
508                                   "%s: unknown connection type: %d", __func__,
509                                   conn->realm->type);
510     }
511
512   return RSE_OK;
513 }
514
515 static void
516 _do_connect (struct rs_connection *conn)
517 {
518   struct rs_peer *p;
519   int err;
520
521   assert (conn);
522   assert (conn->active_peer);
523   p = conn->active_peer;
524
525 #if defined (DEBUG)
526   {
527     char host[80], serv[80];
528
529     getnameinfo (p->addr->ai_addr,
530                  p->addr->ai_addrlen,
531                  host, sizeof(host), serv, sizeof(serv),
532                  0 /* NI_NUMERICHOST|NI_NUMERICSERV*/);
533     rs_debug (("%s: connecting to %s:%s\n", __func__, host, serv));
534   }
535 #endif
536
537   _set_timeout (conn);
538   err = bufferevent_socket_connect (p->conn->bev, p->addr->ai_addr,
539                                     p->addr->ai_addrlen);
540   if (err < 0)
541     rs_err_conn_push_fl (p->conn, RSE_EVENT, __FILE__, __LINE__,
542                          "bufferevent_socket_connect: %s",
543                          evutil_gai_strerror (err));
544   else
545     p->conn->is_connecting = 1;
546 }
547
548 static int
549 _conn_open(struct rs_connection *conn, struct rs_packet *pkt)
550 {
551   if (_init_evb (conn))
552     return -1;
553
554   if (!conn->active_peer)
555     _pick_peer (conn);
556   if (!conn->active_peer)
557     return rs_err_conn_push_fl (conn, RSE_NOPEER, __FILE__, __LINE__, NULL);
558
559   if (_init_socket (conn, conn->active_peer))
560     return -1;
561
562   if (_init_bev (conn, conn->active_peer))
563     return -1;
564
565   if (!conn->is_connected)
566     if (!conn->is_connecting)
567       _do_connect (conn);
568
569   return RSE_OK;
570 }
571
572 static int
573 _conn_is_open_p (struct rs_connection *conn)
574 {
575   return conn->active_peer && conn->is_connected;
576 }
577
578 /* Public functions.  */
579 int
580 rs_packet_create (struct rs_connection *conn, struct rs_packet **pkt_out)
581 {
582   struct rs_packet *p;
583   RADIUS_PACKET *rpkt;
584
585   *pkt_out = NULL;
586
587   rpkt = rad_alloc (1);
588   if (!rpkt)
589     return rs_err_conn_push (conn, RSE_NOMEM, __func__);
590   rpkt->id = conn->nextid++;
591
592   p = (struct rs_packet *) malloc (sizeof (struct rs_packet));
593   if (!p)
594     {
595       rad_free (&rpkt);
596       return rs_err_conn_push (conn, RSE_NOMEM, __func__);
597     }
598   memset (p, 0, sizeof (struct rs_packet));
599   p->conn = conn;
600   p->rpkt = rpkt;
601
602   *pkt_out = p;
603   return RSE_OK;
604 }
605
606 int
607 rs_packet_create_authn_request (struct rs_connection *conn,
608                                 struct rs_packet **pkt_out,
609                                 const char *user_name, const char *user_pw)
610 {
611   struct rs_packet *pkt;
612   struct rs_attr *attr;
613
614   if (rs_packet_create (conn, pkt_out))
615     return -1;
616   pkt = *pkt_out;
617   pkt->rpkt->code = PW_AUTHENTICATION_REQUEST;
618
619   if (user_name)
620     {
621       if (rs_attr_create (conn, &attr, "User-Name", user_name))
622         return -1;
623       rs_packet_add_attr (pkt, attr);
624
625       if (user_pw)
626         {
627           if (rs_attr_create (conn, &attr, "User-Password", user_pw))
628             return -1;
629           rs_packet_add_attr (pkt, attr);
630         }
631     }
632
633   return RSE_OK;
634 }
635
636 /* User callback used when we're dispatching for user.  */
637 static void
638 _wcb (void *user_data)
639 {
640   struct rs_packet *pkt = (struct rs_packet *) user_data;
641   assert (pkt);
642   pkt->written_flag = 1;
643   bufferevent_disable (pkt->conn->bev, EV_WRITE|EV_READ);
644 }
645
646 int
647 rs_packet_send (struct rs_packet *pkt, void *user_data)
648 {
649   struct rs_connection *conn = NULL;
650   int err = 0;
651
652   assert (pkt);
653   assert (pkt->conn);
654   conn = pkt->conn;
655
656   if (_conn_is_open_p (conn))
657     _do_send (pkt);
658   else
659     if (_conn_open (conn, pkt))
660       return -1;
661
662   assert (conn->evb);
663   assert (conn->bev);
664   assert (conn->active_peer);
665   assert (conn->fd >= 0);
666
667   conn->user_data = user_data;
668   bufferevent_setcb (conn->bev, NULL, _write_cb, _event_cb, pkt);
669   bufferevent_enable (conn->bev, EV_WRITE);
670
671   /* Do dispatch, unless the user wants to do it herself.  */
672   if (!conn->user_dispatch_flag)
673     {
674       conn->callbacks.sent_cb = _wcb;
675       conn->user_data = pkt;
676       rs_debug (("%s: entering event loop\n", __func__));
677       err = event_base_dispatch (conn->evb);
678       if (err < 0)
679         return rs_err_conn_push_fl (pkt->conn, RSE_EVENT, __FILE__, __LINE__,
680                                     "event_base_dispatch: %s",
681                                     evutil_gai_strerror (err));
682       rs_debug (("%s: event loop done\n", __func__));
683       conn->callbacks.sent_cb = NULL;
684       conn->user_data = NULL;
685
686       if (!pkt->written_flag)
687         return -1;
688     }
689
690   return RSE_OK;
691 }
692
693 static void
694 _rcb (struct rs_packet *packet, void *user_data)
695 {
696   struct rs_packet *pkt = (struct rs_packet *) user_data;
697   assert (pkt);
698   pkt->valid_flag = 1;
699   bufferevent_disable (pkt->conn->bev, EV_WRITE|EV_READ);
700 }
701
702 /* Special function used in libradsec blocking dispatching mode,
703    i.e. with socket set to block on read/write and with no libradsec
704    callbacks registered.
705
706    For any other use of libradsec, a the received_cb callback should
707    be registered in the callbacks member of struct rs_connection.
708
709    On successful reception, verification and decoding of a RADIUS
710    message, PKT_OUT will upon return point at a pointer to a struct
711    rs_packet containing the message.
712
713    If anything goes wrong or if the read times out (TODO: explain),
714    PKT_OUT will point at the NULL pointer and one or more errors are
715    pushed on the connection (available through rs_err_conn_pop()).  */
716
717 int
718 rs_conn_receive_packet (struct rs_connection *conn,
719                         struct rs_packet *request,
720                         struct rs_packet **pkt_out)
721 {
722   int err = 0;
723   struct rs_packet *pkt = NULL;
724
725   assert (conn);
726   assert (conn->realm);
727   assert (!conn->user_dispatch_flag); /* Dispatching mode only.  */
728
729   if (rs_packet_create (conn, pkt_out))
730     return -1;
731   pkt = *pkt_out;
732   pkt->conn = conn;
733   pkt->original = request;
734
735   assert (conn->evb);
736   assert (conn->bev);
737   assert (conn->active_peer);
738   assert (conn->fd >= 0);
739
740   bufferevent_setwatermark (conn->bev, EV_READ, RS_HEADER_LEN, 0);
741   bufferevent_setcb (conn->bev, _read_cb, NULL, _event_cb, pkt);
742   bufferevent_enable (conn->bev, EV_READ);
743   conn->callbacks.received_cb = _rcb;
744   conn->user_data = pkt;
745
746   /* Dispatch.  */
747   rs_debug (("%s: entering event loop\n", __func__));
748   err = event_base_dispatch (conn->evb);
749   conn->callbacks.received_cb = NULL;
750   if (err < 0)
751     return rs_err_conn_push_fl (pkt->conn, RSE_EVENT, __FILE__, __LINE__,
752                                 "event_base_dispatch: %s",
753                                 evutil_gai_strerror (err));
754   rs_debug (("%s: event loop done\n", __func__));
755
756   if (!pkt->valid_flag)
757     return -1;
758
759 #if defined (DEBUG)
760       rs_dump_packet (pkt);
761 #endif
762
763   pkt->original = NULL;         /* FIXME: Why?  */
764   return RSE_OK;
765 }
766
767 void
768 rs_packet_add_attr (struct rs_packet *pkt, struct rs_attr *attr)
769 {
770   pairadd (&pkt->rpkt->vps, attr->vp);
771   attr->pkt = pkt;
772 }
773
774 struct radius_packet *
775 rs_packet_frpkt (struct rs_packet *pkt)
776 {
777   assert (pkt);
778   return pkt->rpkt;
779 }
780
781 void
782 rs_packet_destroy (struct rs_packet *pkt)
783 {
784   if (pkt)
785     {
786       // FIXME: memory leak! TODO: free all attributes
787       rad_free (&pkt->rpkt);
788       rs_free (pkt->conn->ctx, pkt);
789     }
790 }