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