10 #include <sys/socket.h>
20 struct utcp_connection *c;
21 int dir = DIR_READ | DIR_WRITE;
30 ssize_t do_recv(struct utcp_connection *c, const void *data, size_t len) {
33 fprintf(stderr, "Error: %s\n", strerror(errno));
37 fprintf(stderr, "Connection closed by peer\n");
41 return write(1, data, len);
44 void do_accept(struct utcp_connection *nc, uint16_t port) {
45 utcp_accept(nc, do_recv, NULL);
47 utcp_set_accept_cb(c->utcp, NULL, NULL);
50 ssize_t do_send(struct utcp *utcp, const void *data, size_t len) {
51 int s = *(int *)utcp->priv;
53 if(outpktno < dropto && outpktno >= dropfrom && drand48() < dropout)
56 ssize_t result = send(s, data, len, MSG_DONTWAIT);
58 fprintf(stderr, "Error sending UDP packet: %s\n", strerror(errno));
62 int main(int argc, char *argv[]) {
66 if(argc < 2 || argc > 3)
69 bool server = argc == 2;
70 bool connected = false;
72 dropin = atof(getenv("DROPIN") ?: "0");
73 dropout = atof(getenv("DROPOUT") ?: "0");
74 dropfrom = atoi(getenv("DROPFROM") ?: "0");
75 dropto = atoi(getenv("DROPTO") ?: "0");
78 struct addrinfo hint = {
79 .ai_flags = server ? AI_PASSIVE : 0,
80 .ai_socktype = SOCK_DGRAM,
83 getaddrinfo(server ? NULL : argv[1], server ? argv[1] : argv[2], &hint, &ai);
87 int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
92 if(bind(s, ai->ai_addr, ai->ai_addrlen))
95 if(connect(s, ai->ai_addr, ai->ai_addrlen))
102 struct utcp *u = utcp_init(server ? do_accept : NULL, NULL, do_send, &s);
106 utcp_set_mtu(u, 1300);
107 utcp_set_user_timeout(u, 10);
110 c = utcp_connect(u, 1, do_recv, NULL);
112 struct pollfd fds[2] = {
113 {.fd = 0, .events = POLLIN | POLLERR | POLLHUP},
114 {.fd = s, .events = POLLIN | POLLERR | POLLHUP},
118 struct timeval timeout = utcp_timeout(u);
120 while(!connected || utcp_is_active(u)) {
121 size_t max = c ? utcp_get_sndbuf_free(c) : 0;
125 if((dir & DIR_READ) && max)
126 poll(fds, 2, timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
128 poll(fds + 1, 1, timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
132 fprintf(stderr, "0");
133 ssize_t len = read(0, buf, max);
138 utcp_shutdown(c, SHUT_WR);
145 ssize_t sent = utcp_send(c, buf, len);
147 fprintf(stderr, "PANIEK: %zd != %zd\n", sent, len);
153 fprintf(stderr, "1");
154 struct sockaddr_storage ss;
155 socklen_t sl = sizeof ss;
156 int len = recvfrom(s, buf, sizeof buf, MSG_DONTWAIT, (struct sockaddr *)&ss, &sl);
158 fprintf(stderr, "Error receiving UDP packet: %s\n", strerror(errno));
162 if(!connect(s, (struct sockaddr *)&ss, sl))
165 if(inpktno >= dropto || inpktno < dropfrom || drand48() >= dropin)
166 utcp_recv(u, buf, len);
169 timeout = utcp_timeout(u);