Enable tls psk
[libradsec.git] / examples / blocking.c
1 /* Example usage of libradsec-base, using blocking i/o.  */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <stdint.h>
7 #include "blocking.h"
8
9 struct rs_packet *
10 next_packet (const struct rs_handle *ctx, int fd)
11 {
12   uint8_t hdr[RS_HEADER_LEN];
13   uint8_t *buf;
14   size_t len;
15   struct rs_packet *p;
16   ssize_t n;
17
18   /* Read fixed length header.  */
19   n = 0;
20   while (n < RS_HEADER_LEN)
21     n += read (fd, hdr, RS_HEADER_LEN - n);
22
23   p = rs_packet_new (ctx, hdr, &len);
24   fprintf (stderr, "DEBUG: got header, total packet len is %d\n",
25            len + RS_HEADER_LEN);
26
27   /* Read the rest of the message.  */
28   if (p)
29     {
30       buf = malloc (len);
31       if (buf)
32         {
33           n = 0;
34           while (n < len)
35             n += read (fd, buf, len - n);
36           p = rs_packet_parse (ctx, &p, buf, len);
37           free (buf);
38         }
39       else
40         rs_packet_free (ctx, &p);
41     }
42
43   return p;
44 }
45
46 int
47 send_packet(const struct rs_handle *ctx, int fd, struct rs_packet *p)
48 {
49   uint8_t *buf = NULL;
50   ssize_t n = -20;            /* Arbitrary packet size -- a guess.  */
51
52   while (n < 0)
53     {
54       buf = realloc (buf, -n);
55       if (buf == NULL)
56         return -1;
57       n = rs_packet_serialize (p, buf, -n);
58     }
59
60   while (n)
61     {
62       ssize_t count = write (fd, buf, n);
63       if (count == -1)
64         return -1;
65       n -= count;
66     }
67
68   free (buf);
69   rs_packet_free (ctx, &p);
70   return 0;
71 }