Low level connect and read working, kind of. At least TCP.
[radsecproxy.git] / lib / 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_config *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   if (p)
27     {
28       buf = malloc (len);
29       if (buf)
30         {
31           n = 0;
32           while (n < len)
33             n += read (fd, buf, len - n);
34           p = rs_packet_parse (ctx, &p, buf, len);
35           free (buf);
36         }
37       else
38         rs_packet_free (ctx, &p);
39     }
40
41   return p;
42 }
43
44 int
45 send_packet(const struct rs_config *ctx, int fd, struct rs_packet *p)
46 {
47   uint8_t *buf = NULL;
48   ssize_t n = -20;            /* Arbitrary packet size -- a guess.  */
49
50   while (n < 0)
51     {
52       buf = realloc (buf, -n);
53       if (buf == NULL)
54         return -1;
55       n = rs_packet_serialize (p, buf, -n);
56     }
57
58   while (n)
59     {
60       ssize_t count = write (fd, buf, n);
61       if (count == -1)
62         return -1;
63       n -= count;
64     }
65
66   free (buf);
67   rs_packet_free (ctx, &p);
68   return 0;
69 }