]> git.meshlink.io Git - utcp/blob - selftest.c
Start of UTCP.
[utcp] / selftest.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <time.h>
5 #include <errno.h>
6
7 #include "utcp.h"
8
9 struct utcp *a;
10 struct utcp *b;
11 struct utcp_connection *c;
12
13 int do_recv(struct utcp_connection *x, void *data, size_t len) {
14         if(!len) {
15                 if(errno)
16                         fprintf(stderr, "%p Error: %s\n", x->utcp, strerror(errno));
17                 else
18                         fprintf(stderr, "%p Connection closed by peer\n", x->utcp);
19                 if(x != c) {
20                         fprintf(stderr, "closing my side too...\n");
21                         utcp_close(x);
22                 }
23                 return -1;
24         }
25
26         if(x == c)
27                 write(0, data, len);
28         else
29                 utcp_send(x, data, len);
30
31         return 0;
32 }
33
34 bool do_pre_accept(struct utcp *utcp, void *data, size_t len) {
35         fprintf(stderr, "pre-accept\n");
36         if(len != 2 || strncmp(data, "oi", 2))
37                 return false;
38         return true;
39 }
40
41 void do_accept(struct utcp_connection *c, void *data, size_t len) {
42         fprintf(stderr, "accept\n");
43         utcp_accept(c, do_recv, NULL);
44 }
45
46 int do_send(struct utcp *utcp, void *data, size_t len) {
47         static int count = 0;
48         if(++count > 1000) {
49                 fprintf(stderr, "Too many packets!\n");
50                 abort();
51         }
52
53         if(utcp == a)
54                 return utcp_recv(b, data, len);
55         else
56                 return utcp_recv(a, data, len);
57 }
58
59
60 int main(int argc, char *argv[]) {
61         srand(time(NULL));
62
63         a = utcp_init(do_accept, do_pre_accept, do_send, NULL);
64         b = utcp_init(NULL, NULL, do_send, NULL);
65
66         fprintf(stderr, "Testing connection to closed port\n\n");
67         c = utcp_connect(b, "zomg", 4, do_recv, NULL);
68
69         fprintf(stderr, "\nTesting conection to non-listening side\n\n");
70         c = utcp_connect(a, "oi", 2, do_recv, NULL);
71
72         fprintf(stderr, "\nTesting connection to open port, close\n\n");
73         c = utcp_connect(b, "oi", 2, do_recv, NULL);
74         fprintf(stderr, "closing...\n");
75         utcp_close(c);
76
77         fprintf(stderr, "\nTesting connection to open port, abort\n\n");
78         c = utcp_connect(b, "oi", 2, do_recv, NULL);
79         fprintf(stderr, "aborting...\n");
80         utcp_abort(c);
81
82         fprintf(stderr, "\nTesting connection with data transfer\n\n");
83
84         c = utcp_connect(b, "oi", 2, do_recv, NULL);
85         utcp_send(c, "Hello world!\n", 13);
86         utcp_send(c, "This is a test.\n", 16);
87         fprintf(stderr, "closing...\n");
88         utcp_close(c);
89
90         return 0;
91 }