1 
2 #include "gs-common.h"
3 #include <sys/types.h>
4 #include <sys/socket.h>
5 #include <sys/time.h>
6 #include <netinet/in.h>
7 #include <arpa/inet.h>
8 #include <fcntl.h>
9 #include <string.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <stdbool.h>
13 #include <errno.h>
14 #include <unistd.h>
15 #include <openssl/sha.h>
16 #include <gsocket/gsocket.h>
17 #include "gsocket-engine.h"
18 #include "gsocket-sha256.h"	// Use internal SHA256 if no OpenSSL available
19 #include "gs-externs.h"
20 
21 #ifdef DEBUG
22 // # define DEBUG_SELECT	(1)
23 #endif
24 
25 #ifdef DEBUG
26 FILE *gs_dout;		/* DEBUG OUTPUT */
27 int gs_did;         // debug ID
28 int gs_debug_level;
29 fd_set *gs_debug_rfd;
30 fd_set *gs_debug_wfd;
31 fd_set *gs_debug_r;
32 fd_set *gs_debug_w;
33 #endif
34 FILE *gs_errfp;
35 
36 #define GS_NET_DEFAULT_HOST			"gs.thc.org"
37 #define GS_NET_DEFAULT_PORT			7350
38 #define GS_SOCKS_DFL_IP				"127.0.0.1"
39 #define GS_SOCKS_DFL_PORT			9050
40 #define GS_GS_HTON_DELAY			(12 * 60 * 60)	// every 12h
41 #ifdef DEBUG_SELECT
42 # define GS_DEFAULT_PING_INTERVAL	(30)
43 # define GS_RECONNECT_DELAY			(3)
44 #else
45 # define GS_DEFAULT_PING_INTERVAL	(2*60)	// Every 2 minutes
46 # define GS_RECONNECT_DELAY			(15)	// connect() not more than every 15s
47 #endif
48 
49 // #define STRESSTEST	1
50 #ifdef STRESSTEST
51 # define GS_DEFAULT_PING_INTERVAL	(1)
52 #endif
53 
54 static const char unit[] = "BKMGT";    /* Up to Exa-bytes. */
55 
56 static int gs_pkt_listen_write(GS *gsocket, struct gs_sox *sox);
57 static int gs_pkt_connect_write(GS *gsocket, struct gs_sox *sox);
58 static int gs_pkt_connect_socks(GS *gsocket, struct gs_sox *sox);
59 static void gs_close(GS *gsocket);
60 static void gs_listen_add_gs_select_by_sox(GS_SELECT_CTX *ctx, gselect_cb_t func, int fd, void *arg, int val);
61 static void gs_net_try_reconnect_by_sox(GS *gs, struct gs_sox *sox);
62 static void gs_net_init_by_sox(GS_CTX *ctx, struct gs_sox *sox);
63 static int gs_net_connect_new_socket(GS *gs, struct gs_sox *sox);
64 
65 
66 #ifndef int_ntoa
67 const char *
int_ntoa(uint32_t ip)68 int_ntoa(uint32_t ip)
69 {
70 	struct in_addr in;
71 
72 	in.s_addr = ip;
73 	return inet_ntoa(in);
74 }
75 #endif
76 
77 #define gs_set_error(gs_ctx, a...)	do { \
78 	snprintf(gs_ctx->err_buf, sizeof (gs_ctx)->err_buf, a); \
79 } while (0)
80 
81 void
gs_fds_out_fd(fd_set * fdset,char id,int fd)82 gs_fds_out_fd(fd_set *fdset, char id, int fd)
83 {
84 #ifdef DEBUG_SELECT
85 	if (FD_ISSET(fd, fdset))
86 		DEBUGF("fd=%d %c (set)\n", fd, id);
87 	else
88 		DEBUGF("fd=%d %c (not set)\n", fd, id);
89 #endif
90 }
91 
92 static int gs_lib_init_called;
93 
94 void
gs_fds_out(fd_set * fdset,int max,char id)95 gs_fds_out(fd_set *fdset, int max, char id)
96 {
97 #ifdef DEBUG_SELECT
98 	char buf[max + 1 + 1];
99 
100 	memset(buf, ' ', sizeof buf);
101 	int i;
102 
103 	for (i = 0; i <= max; i++)
104 		buf[i] = '0' + i % 10;
105 	buf[i] = '\0';
106 	xfprintf(gs_dout, "%s (max = %d)\n", buf, max);
107 	int n = 0;
108 	memset(buf, '.', sizeof buf);
109 	for (i = 0; i <= max; i++)
110 	{
111 		if (FD_ISSET(i, fdset))
112 		{
113 			n++;
114 			buf[i] = id;
115 		}
116 
117 	}
118 	buf[i] = '\0';
119 	xfprintf(gs_dout, "%s (Tracking: %d, max = %d)\n", buf, n, max);
120 #endif
121 }
122 
123 void
gs_fds_out_rwfd(GS_SELECT_CTX * ctx)124 gs_fds_out_rwfd(GS_SELECT_CTX *ctx)
125 {
126 #ifdef DEBUG_SELECT
127 	int i;
128 	char buf[ctx->max_fd + 1 + 1];
129 
130 	for (i = 0; i <= ctx->max_fd; i++)
131 		buf[i] = '0' + i % 10;
132 	buf[i] = '\0';
133 	xfprintf(gs_dout, "%s (max = %d)\n", buf, ctx->max_fd);
134 
135 	memset(buf, ' ', sizeof buf);
136 	buf[sizeof buf - 1] = '\0';
137 
138 	int c;
139 	int n = 0;
140 	for (i = 0; i <= ctx->max_fd; i++)
141 	{
142 		c = 0;
143 		if (FD_ISSET(i, ctx->rfd))
144 			c = 1;
145 		if (FD_ISSET(i, ctx->wfd))
146 			c += 2;
147 
148 		if (c == 0)
149 		{
150 			buf[i] = '.';
151 			continue;
152 		}
153 		else if (c == 1)
154 			buf[i] = 'R';
155 		else if (c == 2)
156 			buf[i] = 'W';
157 		else if (c == 3)
158 			buf[i] = 'X';	// Set of Reading _and_ Writing
159 		else
160 			buf[i] = 'E';	// Cant happen.
161 		n++;
162 	}
163 	buf[i] = '\0';
164 	xfprintf(gs_dout, "%s (Tracking: %d, max = %d)\n", buf, n, ctx->max_fd);
165 #endif
166 }
167 
168 void
GS_library_init(FILE * err_fp,FILE * dout_fp)169 GS_library_init(FILE *err_fp, FILE *dout_fp)
170 {
171 	if (gs_lib_init_called != 0)
172 		return;
173 	gs_lib_init_called = 1;
174 
175 	/* Initialize SSL */
176 	SSL_library_init();
177 	OpenSSL_add_all_algorithms();
178 	SSL_load_error_strings();
179 
180 	XASSERT(RAND_status() == 1, "RAND_status()");
181 
182 	gs_errfp = err_fp;
183 #ifdef DEBUG
184 	gs_dout = dout_fp;
185 #endif
186 }
187 
188 int
GS_CTX_init(GS_CTX * ctx,fd_set * rfd,fd_set * wfd,fd_set * r,fd_set * w,struct timeval * tv_now)189 GS_CTX_init(GS_CTX *ctx, fd_set *rfd, fd_set *wfd, fd_set *r, fd_set *w, struct timeval *tv_now)
190 {
191 	GS_library_init(stderr, stderr);
192 
193 	memset(ctx, 0, sizeof *ctx);
194 
195 	ctx->rfd = rfd;
196 	ctx->wfd = wfd;
197 	ctx->r = r;
198 	ctx->w = w;
199 	ctx->tv_now = tv_now;
200 #ifdef DEBUG_SELECT
201 	gs_debug_rfd = rfd;
202 	gs_debug_wfd = wfd;
203 	gs_debug_r = r;
204 	gs_debug_w = w;
205 #endif
206 
207 	if (ctx->rfd == NULL)
208 	{
209 		ERREXIT("Is this still being used? how about r and w == NULL?\n");
210 		ctx->rfd = calloc(1, sizeof *ctx->rfd);
211 		ctx->wfd = calloc(1, sizeof *ctx->wfd);
212 		ctx->flags |= GS_CTX_FL_RFD_INTERNAL;
213 	}
214 
215 	ctx->socks_port = htons(GS_SOCKS_DFL_PORT);
216 	char *ptr;
217 	ptr = getenv("GSOCKET_SOCKS_IP");
218 	if ((ptr != NULL) && (*ptr != '\0'))
219 		ctx->socks_ip = inet_addr(ptr);
220 
221 	ptr = getenv("GSOCKET_SOCKS_PORT");
222 	if (ptr != NULL)
223 		ctx->socks_port = htons(atoi(ptr));
224 
225 	ctx->gs_flags |= GSC_FL_USE_SRP;		// Encryption by default
226 	ctx->gs_flags |= GSC_FL_NONBLOCKING;	// Non-blocking by default
227 
228 	return 0;
229 }
230 
231 /*
232  * Make use of GS_select() subsystem.
233  */
234 void
GS_CTX_use_gselect(GS_CTX * ctx,GS_SELECT_CTX * gselect_ctx)235 GS_CTX_use_gselect(GS_CTX *ctx, GS_SELECT_CTX *gselect_ctx)
236 {
237 	ctx->gselect_ctx = gselect_ctx;
238 }
239 
240 int
GS_CTX_free(GS_CTX * ctx)241 GS_CTX_free(GS_CTX *ctx)
242 {
243 	if (ctx->flags & GS_CTX_FL_RFD_INTERNAL)
244 	{
245 		XFREE(ctx->rfd);
246 		XFREE(ctx->wfd);
247 	}
248 
249 	memset(ctx, 0, sizeof *ctx);
250 
251 	return 0;
252 }
253 
254 /*
255  * Copy over all elements of a GS to gs_new
256  * but increment gs-specific counters.
257  * This is typically used to create a GS from a listening GS.
258  */
259 static void
gs_instantiate(GS * gsocket,GS * new_gs,int new_fd)260 gs_instantiate(GS *gsocket, GS *new_gs, int new_fd)
261 {
262 
263 		new_gs->ctx = gsocket->ctx;
264 		new_gs->fd = new_fd;
265 		new_gs->flags = gsocket->flags;
266 		new_gs->ctx->gsocket_success_count++;
267 		new_gs->id = new_gs->ctx->gsocket_success_count;
268 
269 #ifdef WITH_GSOCKET_SSL
270 		new_gs->ssl_ctx = gsocket->ssl_ctx;
271 		new_gs->srpData = gsocket->srpData;
272 		memcpy(new_gs->srp_sec, gsocket->srp_sec, sizeof new_gs->srp_sec);
273 		if (new_gs->ssl != NULL)
274 			DEBUGF("*** WARNING ***: old SSL found???\n");
275 		new_gs->ssl = NULL;
276 #endif
277 }
278 
279 static int
gs_set_ip_by_hostname(GS * gs,const char * hostname)280 gs_set_ip_by_hostname(GS *gs, const char *hostname)
281 {
282 	/* No hostname specified. Perhaps using env var GSOCKET_IP */
283 	if (hostname == NULL)
284 		return GS_SUCCESS;
285 
286 	/* When Socks5 is used then TCP goes to Socks5 server */
287 	if (gs->ctx->socks_ip != 0)
288 		return GS_SUCCESS;
289 
290 	/* HERE: Socks5 not used */
291 	uint32_t gs_ip;
292 	gs_ip = GS_hton(hostname);
293 	if (gs_ip == 0xFFFFFFFF)
294 		return GS_ERROR;
295 
296 	gs->net.tv_gs_hton = GS_TV_TO_USEC(gs->ctx->tv_now);
297 	gs->net.addr = gs_ip;
298 
299 	return GS_SUCCESS;
300 }
301 
302 GS *
GS_new(GS_CTX * ctx,GS_ADDR * addr)303 GS_new(GS_CTX *ctx, GS_ADDR *addr)
304 {
305 	GS *gsocket = NULL;
306 	char *ptr;
307 	char *hostname;
308 
309 	gsocket = calloc(1, sizeof *gsocket);
310 	XASSERT(gsocket != NULL, "calloc(): %s\n", strerror(errno));
311 
312 	gsocket->ctx = ctx;
313 	gsocket->fd = -1;
314 
315 	uint16_t gs_port;
316 	ptr = getenv("GSOCKET_PORT");
317 	if (ptr != NULL)
318 		gs_port = htons(atoi(ptr));
319 	else
320 		gs_port = htons(GS_NET_DEFAULT_PORT);
321 
322 	ctx->gs_port = gs_port;	// Socks5 needs to know
323 	gsocket->net.port = gs_port;
324 
325 	ptr = getenv("GSOCKET_IP");
326 	if (ptr != NULL)
327 	{
328 		gsocket->net.addr = inet_addr(ptr);
329 	}
330 
331 	if ((ctx->socks_ip != 0) || (gsocket->net.addr == 0))
332 	{
333 		/* HERE: Use Socks5 -or- GSOCKET_IP not available */
334 		char buf[256];
335 		hostname = getenv("GSOCKET_HOST");
336 		if (hostname == NULL)
337 		{
338 			/* Connect to [a-z].gsocket.org depending on GS-address */
339 			int num = 0;
340 			int i;
341 			for (i = 0; i < sizeof addr->addr; i++)
342 				num += addr->addr[i];
343 			num = num % 26;
344 			snprintf(buf, sizeof buf, "%c.%s", 'a' + num, GS_NET_DEFAULT_HOST);
345 			hostname = buf;
346 		}
347 
348 		gsocket->net.hostname = strdup(hostname);
349 
350 		int ret;
351 		ret = gs_set_ip_by_hostname(gsocket, gsocket->net.hostname);
352 		if (ret != GS_SUCCESS)
353 		{
354 			free(gsocket);
355 			gs_set_error(ctx, "Failed to resolve '%s'", hostname);
356 			return NULL;
357 		}
358 	}
359 
360 	if (ctx->socks_ip != 0)
361 	{
362 		/* HERE: Socks5 is used */
363 		gsocket->net.addr = ctx->socks_ip;
364 		gsocket->net.port = ctx->socks_port;
365 		XASSERT(gsocket->net.hostname != NULL, "Socks5 but hostname not set\n");
366 	}
367 	gsocket->net.fd_accepted = -1;
368 
369 	gsocket->net.n_sox = 1;
370 	int i;
371 	for (i = 0; i < gsocket->net.n_sox; i++)
372 	{
373 		gsocket->net.sox[i].fd = -1;
374 	}
375 	gsocket->flags = ctx->gs_flags;
376 
377 	memcpy(&gsocket->gs_addr, addr, sizeof gsocket->gs_addr);
378 
379 	GS_srp_setpassword(gsocket, gsocket->gs_addr.b58str);
380 
381 	GS_set_token(gsocket, NULL, 0);
382 
383 	return gsocket;
384 }
385 
386 static void
gs_net_connect_complete(GS * gs,struct gs_sox * sox)387 gs_net_connect_complete(GS *gs, struct gs_sox *sox)
388 {
389 	if (gs->flags & GS_FL_IS_CLIENT)
390 		gs_pkt_connect_write(gs, sox);
391 	else
392 		gs_pkt_listen_write(gs, sox);
393 
394 	if (gs->net.conn_count >= gs->net.n_sox)
395 		gs->flags |= GS_FL_TCP_CONNECTED;	// All TCP (APP) are now connected
396 }
397 
398 /*
399  * First and completing call to 'connect()' (non-blocking).
400  * Return -2 on error (fatal, must exit)
401  * Return -1 if in progress
402  * Return 0 on success (connection actually established)
403  */
404 static int
gs_net_connect_by_sox(GS * gsocket,struct gs_sox * sox)405 gs_net_connect_by_sox(GS *gsocket, struct gs_sox *sox)
406 {
407 	struct sockaddr_in addr;
408 	int ret;
409 
410 	memset(&addr, 0, sizeof addr);
411 	addr.sin_family = AF_INET;
412 	addr.sin_addr.s_addr = gsocket->net.addr;
413 	addr.sin_port = gsocket->net.port;
414 	errno = 0;
415 	ret = connect(sox->fd, (struct sockaddr *)&addr, sizeof addr);
416 	DEBUGF("connect(%s:%d, fd = %d): %d (errno = %d, %s)\n", int_ntoa(gsocket->net.addr), ntohs(addr.sin_port), sox->fd, ret, errno, strerror(errno));
417 	gsocket->net.tv_connect = GS_TV_TO_USEC(gsocket->ctx->tv_now);
418 	if (ret != 0)
419 	{
420 		if ((errno == EINPROGRESS) || (errno == EAGAIN) || (errno == EINTR))
421 		{
422 			XFD_SET(sox->fd, gsocket->ctx->wfd);
423 			sox->state = GS_STATE_SYS_CONNECT;
424 
425 			return GS_ERR_WAITING;
426 		}
427 		if (errno != EISCONN)
428 		{
429 			/* HERE: NOT connected */
430 			if (gsocket->ctx->socks_ip == 0)
431 				gs_set_error(gsocket->ctx, "connect(%s:%d)", int_ntoa(gsocket->net.addr), ntohs(gsocket->net.port));
432 			else
433 				gs_set_error(gsocket->ctx, "connect(%s:%d). Tor not running?", int_ntoa(gsocket->net.addr), ntohs(gsocket->net.port));
434 			return GS_ERR_FATAL;
435 		}
436 	}
437 	/* HERRE: ret == 0 or errno == EISCONN (Socket is already connected) */
438 	DEBUGF("connect(fd = %d) SUCCESS (errno = %d)\n", sox->fd, errno);
439 	FD_CLR(sox->fd, gsocket->ctx->wfd);
440 	XFD_SET(sox->fd, gsocket->ctx->rfd);
441 
442 	/* SUCCESSFULLY connected */
443 	sox->state = GS_STATE_SYS_NONE;		// Not stuck in a system call (connect())
444 	gsocket->net.conn_count += 1;
445 
446 	if (gsocket->ctx->socks_ip != 0)
447 	{
448 		gs_pkt_connect_socks(gsocket, sox);
449 	} else {
450 		gs_net_connect_complete(gsocket, sox);
451 	}
452 
453 	return GS_SUCCESS;
454 }
455 
456 /*
457  * Return > 0 on success.
458  * Return 0 if write would block.
459  * Return -1 on error.
460  */
461 static int
sox_write(struct gs_sox * sox,const void * data,size_t len)462 sox_write(struct gs_sox *sox, const void *data, size_t len)
463 {
464 	int ret;
465 
466 	ret = write(sox->fd, data, len);
467 	if (ret == len)
468 	{
469 		return len;
470 	}
471 	if (ret > 0)
472 		ERREXIT("Fatal, partial write() should not happen.\n");
473 
474 	if (errno != EAGAIN)
475 		return -1;
476 
477 	/* EAGAIN */
478 	memcpy(sox->wbuf, data, len);
479 	sox->wlen = len;
480 
481 	return 0;
482 }
483 
484 static int
gs_pkt_connect_socks(GS * gs,struct gs_sox * sox)485 gs_pkt_connect_socks(GS *gs, struct gs_sox *sox)
486 {
487 	// Auth: 0x05 0x01 0x00
488 	// Conn: 0x05 0x01 0x00 0x03 [1-octet length] [domain name] [2-octet Port]
489 	char buf[512];
490 	char *ptr = &buf[0];
491 
492 	memcpy(buf, "\x05\x01\x00" "\x05\x01\x00\x03", 7);
493 	ptr += 7;
494 
495 	size_t hlen = strlen(gs->net.hostname);
496 	XASSERT(hlen <= 255, "hostname to long\n");
497 
498 	ptr[0] = hlen;
499 	ptr++;
500 
501 	memcpy(ptr, gs->net.hostname, hlen);
502 	ptr += hlen;
503 
504 	memcpy(ptr, &gs->ctx->gs_port, 2);
505 	ptr += 2;
506 
507 	int ret;
508 	ret = sox_write(sox, &buf, ptr - buf);
509 	if (ret == 0)
510 		sox->state = GS_STATE_SOCKS;	// Call write() again
511 
512 	sox->flags |= GS_SOX_FL_AWAITING_SOCKS;
513 
514 	return 0;
515 }
516 
517 static int
gs_pkt_ping_write(GS * gsocket,struct gs_sox * sox)518 gs_pkt_ping_write(GS *gsocket, struct gs_sox *sox)
519 {
520 	int ret;
521 
522 	DEBUGF("### PKT PING write(fd = %d)\n", sox->fd);
523 	// Might be 0 if SSL has not completed yet
524 	if (sox->fd < 0)
525 		return 0;
526 
527 	/* Do not send PING if there is already data in output queue */
528 	if (FD_ISSET(sox->fd, gsocket->ctx->wfd))
529 	{
530 		DEBUGF("skip PING. WANT_WRITE already set.\n");
531 		return 0;
532 	}
533 
534 	struct _gs_ping gping;
535 	memset(&gping, 0, sizeof gping);
536 	gping.type = GS_PKT_TYPE_PING;
537 
538 	ret = sox_write(sox, &gping, sizeof gping);
539 	if (ret == 0)
540 		sox->state = GS_STATE_PKT_PING;
541 
542 	/* write() will eventually complete.
543 	 * As soon as rfd is ready we are expecting a PONG
544 	 */
545 	sox->flags |= GS_SOX_FL_AWAITING_PONG;
546 
547 	return 0;
548 }
549 
550 static int
gs_pkt_listen_write(GS * gsocket,struct gs_sox * sox)551 gs_pkt_listen_write(GS *gsocket, struct gs_sox *sox)
552 {
553 	int ret;
554 
555 	DEBUGF("### PKT LISTEN write(fd = %d)\n", sox->fd);
556 	if (gsocket->flags & GS_FL_IS_CLIENT)
557 		ERREXIT("CC trying to send a listen message. Should send connect.\n");
558 
559 	struct _gs_listen glisten;
560 	memset(&glisten, 0, sizeof glisten);
561 	glisten.type = GS_PKT_TYPE_LISTEN;
562 	glisten.version_major = GS_PKT_PROTO_VERSION_MAJOR;
563 	glisten.version_minor = GS_PKT_PROTO_VERSION_MINOR;
564 
565 	memcpy(glisten.token, gsocket->token, sizeof glisten.token);
566 	memcpy(glisten.addr, gsocket->gs_addr.addr, MIN(sizeof glisten.addr, GS_ADDR_SIZE));
567 
568 	ret = sox_write(sox, &glisten, sizeof glisten);
569 	if (ret == 0)
570 		sox->state = GS_STATE_PKT_LISTEN;
571 
572 	return 0;
573 }
574 
575 static int
gs_pkt_connect_write(GS * gsocket,struct gs_sox * sox)576 gs_pkt_connect_write(GS *gsocket, struct gs_sox *sox)
577 {
578 	int ret;
579 	DEBUGF("pkt_connect_write(fd = %d)\n", sox->fd);
580 
581 	struct _gs_connect gconnect;
582 	memset(&gconnect, 0, sizeof gconnect);
583 	gconnect.type = GS_PKT_TYPE_CONNECT;
584 	gconnect.version_major = GS_PKT_PROTO_VERSION_MAJOR;
585 	gconnect.version_minor = GS_PKT_PROTO_VERSION_MINOR;
586 	gconnect.flags = gsocket->ctx->flags_proto;
587 	DEBUGF_Y("Proto Flags: %x\n", gconnect.flags);
588 
589 	memcpy(gconnect.addr, gsocket->gs_addr.addr, MIN(sizeof gconnect.addr, GS_ADDR_SIZE));
590 
591 	ret = sox_write(sox, &gconnect, sizeof gconnect);
592 	if (ret == 0)
593 		sox->state = GS_STATE_PKT_CONNECT;
594 
595 	return 0;
596 }
597 
598 static int
gs_pkt_accept_write(GS * gsocket,struct gs_sox * sox)599 gs_pkt_accept_write(GS *gsocket, struct gs_sox *sox)
600 {
601 	int ret;
602 
603 	struct _gs_accept gaccept;
604 	memset(&gaccept, 0, sizeof gaccept);
605 	gaccept.type = GS_PKT_TYPE_ACCEPT;
606 
607 	ret = sox_write(sox, &gaccept, sizeof gaccept);
608 	if (ret == 0)
609 		sox->state = GS_STATE_PKT_ACCEPT;
610 
611 	return 0;
612 }
613 
614 /*
615  * Process a GS protocol message.
616  */
617 static int
gs_pkt_dispatch(GS * gsocket,struct gs_sox * sox)618 gs_pkt_dispatch(GS *gsocket, struct gs_sox *sox)
619 {
620 	if (sox->rbuf[0] == GS_PKT_TYPE_PONG)
621 	{
622 		DEBUGF("PONG received\n");
623 		sox->flags &= ~GS_SOX_FL_AWAITING_PONG;
624 		return GS_SUCCESS;
625 	}
626 
627 	if (sox->rbuf[0] == GS_PKT_TYPE_START)
628 	{
629 		/* Called by CLIENT and SERVER. Thereafter it's up to the application
630 		 * layer.
631 		 */
632 		struct _gs_start *start = (struct _gs_start *)sox->rbuf;
633 		DEBUGF("START received. (flags = 0x%2.2x)\n", start->flags);
634 		if (start->flags & GS_FL_PROTO_START_SERVER)
635 		{
636 			DEBUGF_Y("This is SERVER\n");
637 			gsocket->flags |= GS_FL_IS_SERVER;
638 		}
639 		sox->state = GS_STATE_APP_CONNECTED;
640 		gettimeofday(gsocket->ctx->tv_now, NULL);
641 		memcpy(&gsocket->tv_connected, gsocket->ctx->tv_now, sizeof gsocket->tv_connected);
642 		/* Indicate to caller that a new GS connection has started */
643 		gsocket->net.fd_accepted = sox->fd;
644 
645 		gs_pkt_accept_write(gsocket, sox);
646 		return GS_SUCCESS;
647 	}
648 
649 	if (sox->rbuf[0] == GS_PKT_TYPE_STATUS)
650 	{
651 		struct _gs_status *status = (struct _gs_status *)sox->rbuf;
652 		DEBUGF("STATUS received. (type=%d, code=%d)\n", status->err_type, status->code);
653 		if (status->err_type == GS_STATUS_TYPE_FATAL)
654 		{
655 			const char *err_str = "FATAL";	// *Unknown* default
656 			switch (status->code)
657 			{
658 				case GS_STATUS_CODE_BAD_AUTH:
659 					err_str = "Address already in use";
660 					break;
661 				case GS_STATUS_CODE_CONNREFUSED:
662 					err_str = "Connection refused (no server listening)";
663 					break;
664 				case GS_STATUS_CODE_IDLE_TIMEOUT:
665 					err_str = "Idle-Timeout. Server did not receive any data";
666 					break;
667 			}
668 			gs_set_errorf(gsocket, "%s (%u)", err_str, status->code);
669 			return GS_ERR_FATAL;
670 		}
671 		return GS_SUCCESS;
672 	}
673 
674 	DEBUGF("Invalid Packet Type %d - Ignoring..\n", sox->rbuf[0]);
675 
676 	return GS_SUCCESS;
677 }
678 
679 /*
680  * Return length of bytes read, 0 for waiting and otherwise ERROR
681  * (treat EOF as GS_ERROR (and eventually reconnect if this is a listening socket)
682  */
683 static ssize_t
sox_read(struct gs_sox * sox,size_t len)684 sox_read(struct gs_sox *sox, size_t len)
685 {
686 	ssize_t ret;
687 
688 	ret = read(sox->fd, sox->rbuf + sox->rlen, len);
689 	if (ret == 0)	/* EOF */
690 	{
691 		/* HERE: GS-NET can not find a listening peer for this GS-addres.
692 		 * Disconnect hard.
693 		 */
694 		DEBUGF_R("EOF on GS TCP connection -> treat as ECONNRESET\n");
695 		errno = ECONNRESET;
696 		return GS_ERROR;	// ERROR
697 	}
698 	if (ret < 0)
699 	{
700 		/* This can happen when we read packets. We read 1 byte and
701 		 * then without going into select() we try to read the rest
702 		 * of the packet.
703 		 */
704 		if ((errno == EAGAIN) || (errno == EINTR))
705 		{
706 #ifdef DEBUG
707 			gs_fds_out_fd(gs_debug_rfd, 'r', sox->fd);
708 			gs_fds_out_fd(gs_debug_r, 'R', sox->fd);
709 #endif
710 			DEBUGF_R("EAGAIN [would block], wanting %zd\n", len);
711 			return 0;	// Waiting. No data read.
712 		}
713 		return GS_ERROR;
714 	}
715 
716 	sox->rlen += ret;
717 
718 	return ret;	// Return the number of bytes read.
719 }
720 
721 /*
722  * Read at least 'min' bytes or return error if waiting.
723  * Return min on SUCCESS (min bytes available in buffer)
724  * Return GS_ERR_WAITING when waiting for more data.
725  * Return GS_ERROR on error (recoverable. re-connect)
726  * Return GS_ERR_FATAL on non-recoverable errors (never?)
727  */
728 static ssize_t
sox_read_min(struct gs_sox * sox,size_t min)729 sox_read_min(struct gs_sox *sox, size_t min)
730 {
731 	size_t len_rem;
732 	int ret;
733 
734 	XASSERT(sox->rlen < min, "Data in buffer is %zu but only needing %zu\n", sox->rlen, min);
735 
736 	len_rem = min - sox->rlen;
737 	ret = sox_read(sox, len_rem);
738 	if (ret == GS_ERROR)
739 		return GS_ERROR;
740 	if (ret == GS_ERR_FATAL)
741 		return GS_ERR_FATAL;	// never happens
742 
743 	if (sox->rlen < min)
744 		return GS_ERR_WAITING;
745 
746 	/* Not enough data */
747 	return min;
748 }
749 
750 static int
gs_read_pkt(GS * gs,struct gs_sox * sox)751 gs_read_pkt(GS *gs, struct gs_sox *sox)
752 {
753 	int ret;
754 	/* Read GS message. */
755 	/* Read GS MSG header (first octet) */
756 	if (sox->rlen == 0)
757 	{
758 		ret = sox_read(sox, 1);
759 		if (ret != 1)
760 			return GS_ERROR;
761 	}
762 
763 	size_t len_pkt = sizeof (struct _gs_pong);
764 	/* Client only allowed to receive START, STATUS and PONG */
765 	switch (sox->rbuf[0])
766 	{
767 		case GS_PKT_TYPE_PONG:
768 		case GS_PKT_TYPE_START:
769 		case GS_PKT_TYPE_STATUS:
770 			break;
771 		case GS_PKT_TYPE_LISTEN:
772 		case GS_PKT_TYPE_CONNECT:
773 			len_pkt = sizeof (struct _gs_listen);
774 		case GS_PKT_TYPE_PING:
775 		default:
776 			DEBUGF_R("Packet type=%d not valid (for client)\n", sox->rbuf[0]);
777 	}
778 
779 	ret = sox_read_min(sox, len_pkt);
780 	if (ret == GS_ERR_WAITING)
781 		return GS_SUCCESS;	// Not enough data yet
782 	if (ret != len_pkt)
783 		return GS_ERROR;	// ERROR
784 
785 	ret = gs_pkt_dispatch(gs, sox);
786 	sox->rlen = 0;
787 
788 	return ret;
789 }
790 
791 /* Accept Auth: 0x05 0x00
792  * Success    : 0x05 0x00 0x00 0x01 [IP 4bytes] [PORT 2bytes]
793  */
794 struct _socks5_pkt
795 {
796 	uint8_t ver;
797 	uint8_t res;
798 	uint8_t ver2;
799 	uint8_t code;
800 	uint8_t res2;
801 	uint8_t ip_type;
802 	uint8_t ip[4];
803 	uint8_t port[2];
804 };
805 
806 /*
807  * Read reply from Socks5 and 'dispatch' (change state when done or -1 on error).
808  */
809 static int
gs_read_socks(GS * gs,struct gs_sox * sox)810 gs_read_socks(GS *gs, struct gs_sox *sox)
811 {
812 	int ret;
813 	struct _socks5_pkt spkt;
814 
815 	size_t len_pkt = sizeof (struct _socks5_pkt);
816 
817 	ret = sox_read_min(sox, len_pkt);
818 	if (ret == GS_ERR_WAITING)
819 		return GS_SUCCESS;
820 	if (ret != len_pkt)
821 		return GS_ERROR;
822 
823 	// HEXDUMPF(sox->rbuf, len_pkt, "Socks5 (%zu): ", len_pkt);
824 	memcpy(&spkt, sox->rbuf, sizeof spkt);
825 	if (spkt.code != 0)
826 		return GS_ERROR;
827 
828 	DEBUGF_M("Socks5 CONNECTED\n");
829 	/* Socks5 completed. Start GS listen/connect */
830 	sox->flags &= ~GS_SOX_FL_AWAITING_SOCKS;
831 	gs_net_connect_complete(gs, sox);
832 
833 	sox->rlen = 0;
834 
835 	return GS_SUCCESS;
836 }
837 
838 /*
839  * Socket has something to read() or write()
840  * Return 0 on success.
841  */
842 static int
gs_process_by_sox(GS * gsocket,struct gs_sox * sox)843 gs_process_by_sox(GS *gsocket, struct gs_sox *sox)
844 {
845 	int ret;
846 	GS_CTX *gs_ctx = gsocket->ctx;
847 
848 	errno = 0;
849 	if (FD_ISSET(sox->fd, gs_ctx->w))
850 	{
851 		DEBUGF("fd == %d\n", sox->fd);
852 		if (sox->state == GS_STATE_SYS_CONNECT)
853 		{
854 			ret = gs_net_connect_by_sox(gsocket, sox);
855 			if (ret != GS_SUCCESS)
856 			{
857 				DEBUGF_R("will ret = %d, errno %s\n", ret, strerror(errno));
858 				return GS_ERROR;	/* ECONNREFUSED or other */
859 			}
860 
861 			DEBUGF("GS-NET Connection (TCP) ESTABLISHED (fd = %d)\n", sox->fd);
862 			/* rfd is set in gs_net_connect_by_sox */
863 			gs_fds_out_fd(gsocket->ctx->rfd, 'r', sox->fd);
864 			gs_fds_out_fd(gsocket->ctx->wfd, 'w', sox->fd);
865 			return GS_SUCCESS;
866 		}
867 
868 		/* Complete a failed write() */
869 		if ((sox->state == GS_STATE_PKT_PING) || (sox->state == GS_STATE_PKT_LISTEN) || (sox->state == GS_STATE_SOCKS))
870 		{
871 			ret = write(sox->fd, sox->wbuf, sox->wlen);
872 			if (ret != sox->wlen)
873 			{
874 				DEBUGF("ret = %d, len = %zu, errno = %s\n", ret, sox->wlen, strerror(errno));
875 				return GS_ERROR;
876 			}
877 			FD_CLR(sox->fd, gs_ctx->wfd);
878 			XFD_SET(sox->fd, gs_ctx->rfd);
879 			sox->state = GS_STATE_SYS_NONE;
880 
881 			return GS_SUCCESS;
882 		}
883 
884 		/* write() data still in output buffer */
885 		DEBUGF("Oops. WFD ready but not in SYS_CONNECT or PKT_PING? (fd = %d, state = %d)\n", sox->fd, sox->state);
886 		return GS_ERR_FATAL;
887 	} /* gs_ctx->w was set */
888 
889 	/* HERE: rfd is set - ready to read */
890 	DEBUGF_M("rfd is set (state == %d)\n", sox->state);
891 	if (sox->flags & GS_SOX_FL_AWAITING_SOCKS)
892 	{
893 		ret = gs_read_socks(gsocket, sox);
894 	} else {
895 		ret = gs_read_pkt(gsocket, sox);
896 	}
897 
898 	return ret;
899 }
900 
901 /*
902  * Call every second to take care of house-keeping and keep
903  * alive messages.
904  */
905 void
GS_heartbeat(GS * gsocket)906 GS_heartbeat(GS *gsocket)
907 {
908 	int i;
909 
910 	if (gsocket == NULL)
911 		return;
912 	if (gsocket->fd >= 0)
913 		return;
914 
915 	/* Check if it is time to send a PING to keep the connection alive */
916 	for (i = 0; i < gsocket->net.n_sox; i++)
917 	{
918 		struct gs_sox *sox = &gsocket->net.sox[i];
919 
920 		XASSERT(sox->state != GS_STATE_APP_CONNECTED, "fd = %d but APP already CONNECTED state\n", gsocket->fd);
921 
922 		/* if connect() fails then fd is -1 */
923 		/* Skip if 'want-write' is already set. We are already trying to write data. */
924 		if ((sox->fd >= 0) && (FD_ISSET(sox->fd, gsocket->ctx->wfd)))
925 			continue;
926 
927 		/* Skip if oustanding PONG..*/
928 		if (sox->flags & GS_SOX_FL_AWAITING_PONG)
929 			continue;
930 
931 		XASSERT(sox->state != GS_STATE_PKT_ACCEPT, "APP_CONNECTED == false _and_ state == ACCEPT\n");
932 
933 		/* Skip if we are busy with any other system-call (e.g. needing to call 'connect()' again */
934 		if (sox->state == GS_STATE_SYS_CONNECT)
935 			continue;
936 
937 		if (sox->state == GS_STATE_SYS_RECONNECT)
938 		{
939 			gs_net_try_reconnect_by_sox(gsocket, sox);
940 			continue;
941 		}
942 
943 		if (sox->state == GS_STATE_SYS_NONE)
944 		{
945 			uint64_t tv_diff = GS_TV_DIFF(&sox->tv_last_data, gsocket->ctx->tv_now);
946 			// DEBUGF("diff = %llu\n", tv_diff);
947 			if (tv_diff > GS_SEC_TO_USEC(GS_DEFAULT_PING_INTERVAL))
948 			{
949 				gs_pkt_ping_write(gsocket, sox);
950 				memcpy(&sox->tv_last_data, gsocket->ctx->tv_now, sizeof sox->tv_last_data);
951 			}
952 			continue;
953 		}
954 		ERREXIT("NOT REACHED\n");
955 	}
956 }
957 
958 static void
gs_net_reconnect_by_sox(GS * gs,struct gs_sox * sox)959 gs_net_reconnect_by_sox(GS *gs, struct gs_sox *sox)
960 {
961 	gs_net_connect_new_socket(gs, sox);
962 	/* FIXME: if a connect() call succeeds and this gsocket has more
963 	 * than 1 'listen' TCP connections trying to connect() then we could
964 	 * trigger a re-connect on all sox which are in state GS_STATE_SYS_RECONNECT
965 	 * immediately without having to wait for RECONNECT_DELAY.
966 	 */
967 }
968 
969 
970 /*
971  * Try to connect() again or if this is to soon since the failed attempt then
972  * wait and let GS_heartbeat() wake us up when it is time.
973  */
974 static void
gs_net_try_reconnect_by_sox(GS * gs,struct gs_sox * sox)975 gs_net_try_reconnect_by_sox(GS *gs, struct gs_sox *sox)
976 {
977 	sox->state = GS_STATE_SYS_RECONNECT;
978 
979 	if (GS_TV_TO_USEC(gs->ctx->tv_now) <= gs->net.tv_connect + GS_SEC_TO_USEC(GS_RECONNECT_DELAY))
980 	{
981 		DEBUGF_M("To many connect() attempts... Heartbeat will wake us later...\n");
982 		return;
983 	}
984 	/* Ignore return value. If this fails then ignorning return value means
985 	 * we will re-use old IP (which is what we want).
986 	 */
987 	/* Only update IP from hostname like every 12h or so (this should never change) */
988 	if (GS_TV_TO_USEC(gs->ctx->tv_now) > gs->net.tv_gs_hton + GS_SEC_TO_USEC(GS_GS_HTON_DELAY))
989 	{
990 		if (gs->net.hostname != NULL)
991 		{
992 			DEBUGF_Y("Newly resolving %s\n", gs->net.hostname);
993 			gs_set_ip_by_hostname(gs, gs->net.hostname);
994 		}
995 	}
996 
997 	gs_net_reconnect_by_sox(gs, sox);
998 }
999 
1000 /*
1001  * Only called while APP is not yet connected and managing GS-packets.
1002  * Check "fd_accepted" for any fd that can be passed to app-layer.
1003  *
1004  * Return 0 on success.
1005  */
1006 static int
gs_process(GS * gsocket)1007 gs_process(GS *gsocket)
1008 {
1009 	int ret;
1010 	int i;
1011 
1012 	if (gsocket->fd >= 0)
1013 	{
1014 		DEBUGF("*** WARNING ***: No more GS-Net messages after accept please..\n");
1015 		ERREXIT("Should not happen\n");
1016 		return GS_ERR_FATAL;	// NOT REACHED
1017 	}
1018 
1019 	for (i = 0; i < gsocket->net.n_sox; i++)
1020 	{
1021 		struct gs_sox *sox = &gsocket->net.sox[i];
1022 		/* No PING/PONG (KeepAlive) and no further processing of any
1023 		 * GS Protocol messages once the GS-SOCKET is connected.
1024 		 * Instead forward all read() data to application via GS_read().
1025 		 */
1026 		if (sox->state == GS_STATE_APP_CONNECTED)
1027 		{
1028 			ERREXIT("Should not happen\n");	/* GS is disengaged from GS-Net..*/
1029 			continue;
1030 		}
1031 
1032 		if (FD_ISSET(sox->fd, gsocket->ctx->r) || FD_ISSET(sox->fd, gsocket->ctx->w))
1033 		{
1034 			ret = gs_process_by_sox(gsocket, sox);
1035 			DEBUGF("gs_process_by_sox() = %d\n", ret);
1036 			if (ret == GS_ERROR)
1037 			{
1038 				/* GS_connect() shall not auto reconnect */
1039 				if (!(gsocket->flags & GS_FL_AUTO_RECONNECT))
1040 					return GS_ERR_FATAL;
1041 
1042 				/* HERE: Auto-Reconnect. Failed in connect() or write(). */
1043 				DEBUGF_M("GS-NET error. Re-connecting...\n");
1044 				if (!gsocket->net.is_connect_error_warned)
1045 				{
1046 					gsocket->net.is_connect_error_warned = 1;
1047 					xfprintf(gs_errfp, "%s GS-NET: %s. Re-connecting...\n", GS_logtime(), strerror(errno));
1048 				}
1049 				close(sox->fd);
1050 				gs_net_init_by_sox(gsocket->ctx, sox);
1051 				gs_net_try_reconnect_by_sox(gsocket, sox);
1052 				continue;
1053 			}
1054 			if (ret != GS_SUCCESS)
1055 			{
1056 				DEBUGF_R("FATAL errno(%d) = %s\n", errno, strerror(errno));
1057 				return GS_ERR_FATAL;
1058 			}
1059 
1060 			// HERE: connect() succeeded
1061 			gsocket->net.is_connect_error_warned = 0;
1062 
1063 			memcpy(&sox->tv_last_data, gsocket->ctx->tv_now, sizeof sox->tv_last_data);
1064 			/* Immediatly let app know that a new gs-connection has been accepted */
1065 			if (gsocket->net.fd_accepted >= 0)
1066 				break;
1067 			/* We must CLEAR currently processed fd. Otherwise it can happen
1068 			 * that another fd of this listening socket is also ready for r/w
1069 			 * and we would process _this_ fd again (it's a sequential for-loop
1070 			 * over all fd's of a listening gsocket.
1071 			 */
1072 			FD_CLR(sox->fd, gsocket->ctx->r);
1073 			FD_CLR(sox->fd, gsocket->ctx->w);
1074 			/* 'break' here. The calling function's 'select' loop will call us again.
1075 			 * Otherwise the 'n = select()' counter will be off (if we process multiple
1076 			 * fd's at once without n-- the counter.
1077 			 */
1078 			// break;
1079 		}
1080 
1081 	}
1082 
1083 	DEBUGF("Returning 0 (fd_accepted == %d)\n", gsocket->net.fd_accepted);
1084 	return 0;
1085 }
1086 
1087 int
GS_get_fd(GS * gsocket)1088 GS_get_fd(GS *gsocket)
1089 {
1090 	/* If socket is connected already (APP layer) */
1091 	if (gsocket->fd >= 0)
1092 		return gsocket->fd;
1093 
1094 	/* Connecting socket.
1095 	 * Note: We may accidentially return a Accepting-socket here
1096 	 * which is bad (GS_get_fd() is only valid on connecting
1097 	 * or established socket but not on accpepting sockets (because
1098 	 * accepting sockets operate on an array of accepting sockets rather
1099 	 * than a single socket.
1100   	 */
1101 	if (gsocket->net.n_sox > 1)
1102 		return -1;
1103 
1104 	return gsocket->net.sox[0].fd;
1105 }
1106 
1107 
1108 /*
1109  * Return 0 on success.
1110  * Called from gs_net_connect
1111  */
1112 static int
gs_net_new_socket(GS * gsocket,struct gs_sox * sox)1113 gs_net_new_socket(GS *gsocket, struct gs_sox *sox)
1114 {
1115 	int s;
1116 	int ret;
1117 
1118 	gsocket->flags |= GS_FL_CALLED_NET_NEW_SOCKET;
1119 
1120 	s = socket(PF_INET, SOCK_STREAM, 0);
1121 	DEBUGF_W("socket() == %d (LIB)\n", s);
1122 	if (s < 0)
1123 		return -1;
1124 
1125 	ret = fcntl(s, F_SETFL, O_NONBLOCK | fcntl(s, F_GETFL, 0));
1126 	if (ret != 0)
1127 		return -1;
1128 
1129 	gsocket->ctx->max_sox = MAX(s, gsocket->ctx->max_sox);
1130 	sox->fd = s;
1131 
1132 	return 0;
1133 }
1134 
1135 /*
1136  * Create a new socket and connect to GS-NET.
1137  */
1138 static int
gs_net_connect_new_socket(GS * gs,struct gs_sox * sox)1139 gs_net_connect_new_socket(GS *gs, struct gs_sox *sox)
1140 {
1141 	int ret;
1142 
1143 	if (sox->fd >= 0)
1144 		return GS_SUCCESS;	// Skip existing (valid) TCP sockets
1145 
1146 	/*
1147 	 * If we use the GS_select() subsystem:
1148 	 * After GS_accept() a new TCP connection is established to
1149 	 * the GS-NET. We must track the new fd of that new TCP connection
1150 	 * with GS_select(). Here: Find out the call-back for original listening
1151 	 * socket and assign it to new TCP connection (GS-NET).
1152 	 */
1153 	/* GS_select-HACK-1-START */
1154 	gselect_cb_t func;
1155 	int cb_val;
1156 	func = gs->ctx->func_listen;
1157 	cb_val = gs->ctx->cb_val_listen;
1158 	DEBUGF("gs_net_connect called (GS_select() cb_func = %p\n", func);
1159 	GS_SELECT_CTX *gselect_ctx = gs->ctx->gselect_ctx;
1160 	/* GS_select_HACK-1-END */
1161 
1162 	/* HERE: socket() does not exist yet. Create it. */
1163 	ret = gs_net_new_socket(gs, sox);
1164 	if (ret != GS_SUCCESS)
1165 		return GS_ERROR;
1166 
1167 	/* Connect TCP */
1168 	ret = gs_net_connect_by_sox(gs, sox);
1169 	DEBUGF("gs_net_connect_by_sox(fd = %d): %d, %s\n", sox->fd, ret, strerror(errno));
1170 	if (ret == GS_ERR_FATAL)
1171 		ERREXIT("%s\n", GS_CTX_strerror(gs->ctx));
1172 
1173 	/* GS_select-HACK-1-START */
1174 	if (gs->ctx->gselect_ctx != NULL)
1175 	{
1176 		DEBUGF_B("Using GS_select() with new fd = %d, func = %p\n", sox->fd, func);
1177 		/* HERE: We are using GS_select(). Track new fd. */
1178 		gs_listen_add_gs_select_by_sox(gselect_ctx, func, sox->fd, gs, cb_val);
1179 	}
1180 	/* GS_select-HACK-1-END */
1181 
1182 	return GS_SUCCESS;
1183 }
1184 
1185 /*
1186  * Connect to the GS-NET (non-blocking).
1187  * Return 0 on success.
1188  * Return -1 on fatal error (must exist).
1189  */
1190 static int
gs_net_connect(GS * gsocket)1191 gs_net_connect(GS *gsocket)
1192 {
1193 	int ret;
1194 	int i;
1195 	GS_CTX *gs_ctx;
1196 
1197 	if (gsocket == NULL)
1198 		return -1;
1199 
1200 	gs_ctx = gsocket->ctx;
1201 
1202 	if (gs_ctx == NULL)
1203 		return -1;
1204 
1205 	if (gsocket->flags & GS_FL_TCP_CONNECTED)
1206 		return 0;	/* Already connected */
1207 
1208 	for (i = 0; i < gsocket->net.n_sox; i++)
1209 	{
1210 		struct gs_sox *sox = &gsocket->net.sox[i];
1211 
1212 		ret = gs_net_connect_new_socket(gsocket, sox);
1213 
1214 		if (ret != GS_SUCCESS)
1215 			return ret;
1216 	}	/* FOR loop over all sockets */
1217 
1218 	return 0;
1219 }
1220 
1221 static void
gs_net_init_by_sox(GS_CTX * ctx,struct gs_sox * sox)1222 gs_net_init_by_sox(GS_CTX *ctx, struct gs_sox *sox)
1223 {
1224 	XFD_CLR(sox->fd, ctx->wfd);
1225 	XFD_CLR(sox->fd, ctx->rfd);
1226 	// FD_CLR(sox->fd, ctx->w);
1227 	// FD_CLR(sox->fd, ctx->r);
1228 	memset(sox, 0, sizeof *sox);
1229 	sox->fd = -1;
1230 }
1231 
1232 static void
gs_net_init(GS * gsocket,int backlog)1233 gs_net_init(GS *gsocket, int backlog)
1234 {
1235 	int i;
1236 
1237 	backlog = MIN(backlog, GS_MAX_SOX_BACKLOG);
1238 	gsocket->net.n_sox = backlog;
1239 	for (i = 0; i < gsocket->net.n_sox; i++)
1240 	{
1241 		gs_net_init_by_sox(gsocket->ctx, &gsocket->net.sox[i]);
1242 	}
1243 }
1244 
1245 /*
1246  * Free fd from GS-NET structure and pass to application layer.
1247  * Return 0 on success.
1248  *
1249  * This function is called by GS_accept() and GS_connect()
1250  * GS_connect() is gsocket == new_gs because the same GS is used
1251  * whereas for GS_accept() the gsocket is the listening socket (that will
1252  * continue to listen) and new_gs is a newly created GS.
1253  */
1254 static int
gs_net_disengage_tcp_fd(GS * gsocket,GS * new_gs)1255 gs_net_disengage_tcp_fd(GS *gsocket, GS *new_gs)
1256 {
1257 	int i;
1258 	int new_fd = -1;
1259 
1260 	for (i = 0; i < gsocket->net.n_sox; i++)
1261 	{
1262 		struct gs_sox * sox = &gsocket->net.sox[i];
1263 
1264 		if (sox->fd != gsocket->net.fd_accepted)
1265 			continue;
1266 
1267 		/*
1268 		 * Return GS-connected socket fd to app (and stop processing any PKT on that fd...).
1269 		 */
1270 		new_fd = gsocket->net.fd_accepted;
1271 
1272 		gsocket->net.fd_accepted = -1;
1273 		gsocket->flags &= ~GS_FL_TCP_CONNECTED;
1274 		gsocket->net.conn_count -= 1;
1275 		if (gsocket->net.conn_count < 0)
1276 			ERREXIT("FATAL: conn_count dropped to %d\n", gsocket->net.conn_count);
1277 		sox->state = GS_STATE_SYS_NONE;
1278 		sox->fd = -1;
1279 
1280 		gs_instantiate(gsocket, new_gs, new_fd);
1281 
1282 		return 0;
1283 	}
1284 
1285 	DEBUGF("*** WARNING ***: Can This happen???\n");
1286 	return -2;
1287 }
1288 
1289 /*
1290  * non-blocking.
1291  * Return -1 for waiting.
1292  * Return -2 on error
1293  * Return 0 on success.
1294  */
1295 static int
gs_connect(GS * gsocket)1296 gs_connect(GS *gsocket)
1297 {
1298 	int ret;
1299 	DEBUGF("gs_connect(fd = %d)\n", gsocket->fd);
1300 	/* Connect to GS-NET if not already connected */
1301 	if (!(gsocket->flags & GS_FL_CALLED_NET_CONNECT))
1302 	{
1303 		gsocket->flags |= GS_FL_CALLED_NET_CONNECT;
1304 		gsocket->flags |= GS_FL_IS_CLIENT;
1305 		gs_net_init(gsocket, 1);
1306 		DEBUGF("Connecting to GS-Net...\n");
1307 		ret = gs_net_connect(gsocket);
1308 		DEBUGF("gs_net_connect() = %d\n", ret);
1309 		if (ret != 0)
1310 			return GS_ERR_FATAL;
1311 
1312 		return GS_ERR_WAITING;
1313 	}
1314 
1315 	ret = gs_process(gsocket);
1316 	DEBUGF("gs_process() = %d, error(%d) = %s\n", ret, errno, errno?strerror(errno):"");
1317 	if (ret != 0)
1318 		return GS_ERR_FATAL;
1319 
1320 	if (gsocket->net.fd_accepted >= 0)
1321 	{
1322 		DEBUGF_B("New GS connection SUCCESS (fd = %d)\n", gsocket->net.fd_accepted);
1323 		/* On connect() we do not create a new socket but assign existing
1324 		 * tcp-socket to this connection.
1325 		 */
1326 		ret = gs_net_disengage_tcp_fd(gsocket, gsocket);
1327 
1328 		if (ret != 0)
1329 			return GS_ERR_FATAL;
1330 
1331 		return 0;
1332 	}
1333 
1334 	return GS_ERR_WAITING;
1335 }
1336 
1337 /*
1338  * Return 0 on success.
1339  */
1340 static int
gs_connect_blocking(GS * gsocket)1341 gs_connect_blocking(GS *gsocket)
1342 {
1343 	int ret;
1344 	int n;
1345 
1346 	ret = gs_connect(gsocket);
1347 	GS_CTX *ctx = gsocket->ctx;
1348 	while (1)
1349 	{
1350 
1351 		struct timeval tv = {1, 0};
1352 		// FIXME: there could be many other fd's set here from other CTX. We really
1353 		// should only set our fd's from this gsocket (either ->fd or ->gs_net).
1354 		memcpy(ctx->r, ctx->rfd, sizeof *ctx->r);
1355 		memcpy(ctx->w, ctx->wfd, sizeof *ctx->w);
1356 		n = select(gsocket->ctx->max_sox + 1, ctx->r, ctx->w, NULL, &tv);
1357 		if ((n < 0) && (errno == EINTR))
1358 			continue;
1359 		gettimeofday(gsocket->ctx->tv_now, NULL);
1360 		GS_heartbeat(gsocket);
1361 		if (n == 0)
1362 			continue;
1363 
1364 		ret = gs_connect(gsocket);
1365 		DEBUGF("gs_connect() = %d, gsocket->fd = %d\n", ret, gsocket->fd);
1366 		if (ret == GS_ERR_WAITING)
1367 			continue;
1368 		if (ret == GS_ERR_FATAL)
1369 			return GS_ERR_FATAL;
1370 
1371 		DEBUGF("Setting FD BLOCKING\n");
1372 		int tcp_fd = gsocket->fd;
1373 		/* Make tcp fd 'blocking' for caller. */
1374 		fcntl(tcp_fd, F_SETFL, ~O_NONBLOCK & fcntl(tcp_fd, F_GETFL, 0));
1375 
1376 		return ret;
1377 	}
1378 
1379 	ERREXIT("Oops. This should not happen\n");
1380 	return GS_ERR_FATAL;
1381 }
1382 
1383 /*
1384  * Return 0 on success.
1385  * Return -1 if still waiting for connection to be established.
1386  * Return -2 on error.
1387  */
1388 int
GS_connect(GS * gsocket)1389 GS_connect(GS *gsocket)
1390 {
1391 	int ret;
1392 
1393 	DEBUG_SETID(gsocket);
1394 
1395 	if (gsocket->net.fd_accepted >= 0)
1396 	{
1397 		/* This GS-socket is already connected.... */
1398 		errno = EBUSY;
1399 		return GS_ERR_FATAL;
1400 	}
1401 
1402 	/* For auto-reconnecting client side (is it needed?) consider:
1403 	 * - How to handle when no listening server is available
1404 	 * - Warn user if GSRN is unavailable.
1405 	 */
1406 	// gsocket->flags |= GS_FL_AUTO_RECONNECT;
1407 	if (gsocket->flags & GSC_FL_NONBLOCKING)
1408 		ret = gs_connect(gsocket);
1409 	else
1410 		ret = gs_connect_blocking(gsocket);
1411 
1412 	if (ret < 0)
1413 	{
1414 		DEBUGF("GS_connect() will ret = %d (%s)\n", ret, ret==GS_ERR_WAITING?"WAITING":"FATAL");
1415 		return ret;
1416 	}
1417 
1418 #ifdef WITH_GSOCKET_SSL
1419 	if (gsocket->flags & GSC_FL_USE_SRP)
1420 	{
1421 		ret = gs_srp_init(gsocket);
1422 		if (ret >= 0)
1423 			ret = 0;	/* SUCCESS */
1424 	}
1425 #endif
1426 
1427 	return ret;
1428 }
1429 
1430 /*
1431  * Return 0 on success. This can not fail.
1432  */
1433 int
GS_listen(GS * gsocket,int backlog)1434 GS_listen(GS *gsocket, int backlog)
1435 {
1436 	DEBUG_SETID(gsocket);
1437 
1438 	gsocket->flags |= GS_FL_AUTO_RECONNECT;
1439 	gs_net_init(gsocket, backlog);
1440 	gs_net_connect(gsocket);
1441 
1442 	return 0;
1443 }
1444 
1445 static void
gs_listen_add_gs_select_by_sox(GS_SELECT_CTX * ctx,gselect_cb_t func,int fd,void * arg,int val)1446 gs_listen_add_gs_select_by_sox(GS_SELECT_CTX *ctx, gselect_cb_t func, int fd, void *arg, int val)
1447 {
1448 	/* There might be some PING/PONG keepalive going on. Set both RW-fds
1449 	 * and let GS_accept() figure it out.
1450 	 * WARNING: If you change this also look for GS_select-HACK-1
1451 	 */
1452 	GS_SELECT_add_cb_r(ctx, func, fd, arg, val);
1453 	GS_SELECT_add_cb_w(ctx, func, fd, arg, val);
1454 }
1455 
1456 /*
1457  * Helper function to set all fd's that the listening gsocket
1458  * is using for calling accept() on. Listening gsocket's
1459  * listen on more than just 1 fd to allow for gs-peers to connect
1460  * rapidly. There usually is only 1 listening gsocket per process.
1461  */
1462 void
GS_listen_add_gs_select(GS * gs,GS_SELECT_CTX * ctx,gselect_cb_t func,void * arg,int val)1463 GS_listen_add_gs_select(GS *gs, GS_SELECT_CTX *ctx, gselect_cb_t func, void *arg, int val)
1464 {
1465 	gs->ctx->func_listen = func;
1466 	gs->ctx->cb_val_listen = val;
1467 
1468 	int i;
1469 	for (i = 0; i < gs->net.n_sox; i++)
1470 	{
1471 		int fd = gs->net.sox[i].fd;
1472 		gs_listen_add_gs_select_by_sox(ctx, func, fd, arg, val);
1473 	}
1474 }
1475 
1476 /*
1477  * Return a GS on accept or NULL if still waiting.
1478  */
1479 /*
1480  * Return -1 on waiting
1481  * Return -2 on fatal
1482  * Return 0 on success.
1483  */
1484 static int
gs_accept(GS * gsocket,GS * new_gs)1485 gs_accept(GS *gsocket, GS *new_gs)
1486 {
1487 	int ret;
1488 
1489 	DEBUGF("Called gs_accept(%p, %p)\n", gsocket, new_gs);
1490 	ret = gs_process(gsocket);
1491 	if (ret != 0)
1492 	{
1493 		DEBUGF("ERROR: in gs_process(), ret = %d\n", ret);
1494 		return GS_ERR_FATAL;
1495 	}
1496 
1497 	/* Check if there is a new gs-connection waiting */
1498 	if (gsocket->net.fd_accepted >= 0)
1499 	{
1500 		DEBUGF("New GS Connection accepted (fd = %d, n_sox = %d)\n", gsocket->net.fd_accepted, gsocket->net.n_sox);
1501 
1502 		ret = gs_net_disengage_tcp_fd(gsocket, new_gs);
1503 		XASSERT(ret == 0, "ret = %d\n", ret);
1504 
1505 		if (!(gsocket->flags & GS_FL_SINGLE_SHOT))
1506 		{
1507 			/* Start new TCP to GS-Net to listen for more incoming connections */
1508 			gs_net_connect(gsocket);
1509 		}
1510 
1511 		return GS_SUCCESS;
1512 	}
1513 
1514 	return GS_ERR_WAITING; /* Waiting for socket */
1515 }
1516 
1517 /*
1518  * Return -1 on waiting
1519  * Return -2 on fatal
1520  * Return 0 on success.
1521  */
1522 int
gs_accept_blocking(GS * gsocket,GS * new_gs)1523 gs_accept_blocking(GS *gsocket, GS *new_gs)
1524 {
1525 	int ret;
1526 	int n;
1527 
1528 	while (1)
1529 	{
1530 		struct timeval tv = {1, 0};
1531 		memcpy(gsocket->ctx->r, gsocket->ctx->rfd, sizeof *gsocket->ctx->r);
1532 		memcpy(gsocket->ctx->w, gsocket->ctx->wfd, sizeof *gsocket->ctx->w);
1533 		n = select(gsocket->ctx->max_sox + 1, gsocket->ctx->r, gsocket->ctx->w, NULL, &tv);
1534 		if ((n < 0) && (errno == EINTR))
1535 			continue;
1536 		if (n < 0)
1537 			DEBUGF_R("select(): %s\n", strerror(errno));
1538 		gettimeofday(gsocket->ctx->tv_now, NULL);
1539 		GS_heartbeat(gsocket);
1540 		if (n == 0)
1541 			continue;
1542 
1543 		ret = gs_accept(gsocket, new_gs);
1544 		if (ret == -2)
1545 			return -2;
1546 		if (ret == GS_ERR_WAITING)
1547 			continue;
1548 
1549 		/* Make tcp fd 'blocking' for caller. */
1550 		fcntl(new_gs->fd, F_SETFL, ~O_NONBLOCK & fcntl(new_gs->fd, F_GETFL, 0));
1551 		return 0;
1552 	}
1553 
1554 	ERREXIT("Oops. This should not happen\n");
1555 	return -2;	/* NOT REACHED */
1556 }
1557 
1558 /*
1559  * Return NULL on Waiting
1560  * Return GS otherwise.
1561  *
1562  * This function can not return 'fatal' as any error such
1563  * as SRP failure is recoverable by this sub-system (by for example
1564  * opening a new connection and trying again).
1565  */
1566 GS *
GS_accept(GS * gsocket,int * err)1567 GS_accept(GS *gsocket, int *err)
1568 {
1569 	GS gs_tmp;
1570 	int ret;
1571 
1572 	DEBUG_SETID(gsocket);
1573 
1574 	if (err != NULL)
1575 		*err = 0;
1576 
1577 	memset(&gs_tmp, 0, sizeof gs_tmp);
1578 	if (gsocket->flags & GSC_FL_NONBLOCKING)
1579 		ret = gs_accept(gsocket, &gs_tmp);
1580 	else
1581 		ret = gs_accept_blocking(gsocket, &gs_tmp);
1582 
1583 	if (ret < 0)
1584 	{
1585 		if (err != NULL)
1586 			*err = ret;
1587 		return NULL;	/* WAITING or FATAL */
1588 	}
1589 
1590 	/* HERE: gs_accept() SUCCESS */
1591 	/* Instantiate gs */
1592 	GS *new_gs = calloc(1, sizeof *new_gs);
1593 	XASSERT(new_gs != NULL, "calloc()\n");
1594 	memcpy(new_gs, &gs_tmp, sizeof *new_gs);
1595 	memcpy(&new_gs->tv_connected, gsocket->ctx->tv_now, sizeof new_gs->tv_connected);
1596 
1597 	new_gs->flags |= GS_FL_IS_SERVER;
1598 #ifdef WITH_GSOCKET_SSL
1599 	if (new_gs->flags & GSC_FL_USE_SRP)
1600 	{
1601 		ret = gs_srp_init(new_gs);
1602 		if (ret < 0)
1603 		{
1604 			DEBUGF("gs_srp_init() = %d (FAILED), Closing gs...\n", ret);
1605 			gs_close(new_gs);	/* Free SSL and close socket */
1606 			if (err != NULL)
1607 				*err = -2;
1608 			return NULL;
1609 		}
1610 	}
1611 #endif
1612 
1613 	/* All further will be handled by calls to GS_write() or GS_read() */
1614 
1615 	return new_gs;
1616 }
1617 
1618 /*
1619  * as GS_close() but without call to free().
1620  */
1621 static void
gs_close(GS * gsocket)1622 gs_close(GS *gsocket)
1623 {
1624 	XASSERT(gsocket != NULL, "gsocket == NULL\n");
1625 
1626 	if (gsocket->fd >= 0)
1627 	{
1628 		DEBUGF_B("Closing I/O socket (fd = %d)\n", gsocket->fd);
1629 		FD_CLR(gsocket->fd, gsocket->ctx->rfd);
1630 		FD_CLR(gsocket->fd, gsocket->ctx->wfd);
1631 		FD_CLR(gsocket->fd, gsocket->ctx->r);
1632 		FD_CLR(gsocket->fd, gsocket->ctx->w);
1633 		/* HERE: This was not listening socket */
1634 		XCLOSE(gsocket->fd);
1635 		return;
1636 	}
1637 
1638 	/* HERE: There are GS-Net connections that need to be cleaned.*/
1639 	int i;
1640 	/* Close all TCP connections to GS-Network */
1641 	DEBUGF_B("Closing %d GSN connections\n", gsocket->net.n_sox);
1642 	for (i = 0; i < gsocket->net.n_sox; i++)
1643 	{
1644 		struct gs_sox * sox = &gsocket->net.sox[i];
1645 		if (sox->fd < 0)
1646 			continue;
1647 		DEBUGF_B("Closing I/O socket (sox->fd = %d)\n", sox->fd);
1648 		FD_CLR(sox->fd, gsocket->ctx->rfd);
1649 		FD_CLR(sox->fd, gsocket->ctx->wfd);
1650 		FD_CLR(sox->fd, gsocket->ctx->r);
1651 		FD_CLR(sox->fd, gsocket->ctx->w);
1652 		XCLOSE(sox->fd);
1653 	}
1654 	gsocket->net.n_sox = 0;
1655 
1656 	return;
1657 }
1658 
1659 /*
1660  * Return 0 on success.
1661  * Return -2 on fatal error.
1662  */
1663 int
GS_close(GS * gsocket)1664 GS_close(GS *gsocket)
1665 {
1666 	DEBUG_SETID(gsocket);
1667 
1668 	DEBUGF_B("read: %"PRId64", written: %"PRId64"\n", gsocket->bytes_read, gsocket->bytes_written);
1669 	if (gsocket == NULL)
1670 		return -2;
1671 
1672 #ifdef WITH_GSOCKET_SSL
1673 	if (gsocket->flags & GSC_FL_USE_SRP)
1674 	{
1675 		if (gsocket->ssl != NULL)
1676 		{
1677 			DEBUGF_G("Calling SSL_free()\n");
1678 			SSL_free(gsocket->ssl);
1679 			gsocket->ssl = NULL;
1680 		} else {
1681 			DEBUGF_R("gs->ssl == NULL, This must be the listening socket.\n");
1682 		}
1683 	}
1684 #endif
1685 	gs_close(gsocket);
1686 	memset(gsocket, 0, sizeof *gsocket);
1687 
1688 	free(gsocket);
1689 
1690 	return 0;
1691 }
1692 
1693 /*
1694  * Return ERR_WAITING if I/O needs attention (blocking) [Will Trigger CALL-AGAIN]
1695  * Return GS_SUCCESS if gsocket is still alive (for reading, but not writing)
1696  * Return ERR_FATAL if gsocket is DONE (destroy connection).
1697  * Return ERR_FATAL on fatal error (destroy connection).
1698  */
1699 int
GS_shutdown(GS * gsocket)1700 GS_shutdown(GS *gsocket)
1701 {
1702 	int ret;
1703 	DEBUG_SETID(gsocket);
1704 
1705 	if (gsocket->flags & GSC_FL_USE_SRP)
1706 	{
1707 		if (gsocket->ssl_state != GS_SSL_STATE_RW)
1708 		{
1709 			/* Return if the SSL is not yet connected. We can not shut down
1710 			 * unless it's connected. Shutdown triggered after SRP completion.
1711 			 */
1712 			gsocket->is_want_shutdown = 1;
1713 			return GS_SUCCESS;
1714 		}
1715 		ret = gs_ssl_shutdown(gsocket);
1716 		return ret;
1717 	} else {
1718 		gsocket->is_sent_shutdown = 1;
1719 		if (gsocket->eof_count >= 1)
1720 			ret = shutdown(gsocket->fd, SHUT_RDWR);
1721 		else
1722 			ret = shutdown(gsocket->fd, SHUT_WR);
1723 		DEBUGF_B("tcp shutdown() = %d\n", ret);
1724 		if (gsocket->eof_count == 0)
1725 			return GS_SUCCESS;
1726 		return GS_ERR_FATAL;
1727 	}
1728 
1729 	return GS_ERR_FATAL;	/* NOT REACHED */
1730 }
1731 
1732 /*
1733  * Return error string (0-terminated).
1734  * Format: [<errno-str> - ]<Internal Error Buffer>[[SSL-Error string]]
1735  */
1736 const char *
GS_CTX_strerror(GS_CTX * gs_ctx)1737 GS_CTX_strerror(GS_CTX *gs_ctx)
1738 {
1739 	char *dst = gs_ctx->err_buf2;
1740 	int dlen = sizeof gs_ctx->err_buf2;
1741 
1742 	*dst = 0;
1743 
1744 	// First record 'errno' (if set)
1745 	if (errno != 0)
1746 		snprintf(dst, dlen, "%s", strerror(errno));
1747 
1748 	// Then add everything from our internal error buffer
1749 	if (strlen(gs_ctx->err_buf) > 0)
1750 	{
1751 		if (errno != 0)
1752 			snprintf(dst + strlen(dst), dlen - strlen(dst), " - "); // strlcat(dst, " - ", dlen);
1753 		snprintf(dst + strlen(dst), dlen - strlen(dst), "%s", gs_ctx->err_buf);
1754 	}
1755 
1756 	/* Get the last SSL error only. Clear the error-queue */
1757 	int err = 0;
1758 	int err2;
1759 	while (1)
1760 	{
1761 		err2 = ERR_get_error();
1762 		DEBUGF_Y("err2 = %d\n", err2);
1763 		if (err2 == 0)
1764 			break;
1765 		err = err2;
1766 	}
1767 	if (err != 0)
1768 	{
1769 		snprintf(dst + strlen(dst), dlen - strlen(dst), " [%s]", ERR_error_string(err, NULL));
1770 	}
1771 
1772 	return gs_ctx->err_buf2;
1773 }
1774 
1775 const char *
GS_strerror(GS * gsocket)1776 GS_strerror(GS *gsocket)
1777 {
1778 	return GS_CTX_strerror(gsocket->ctx);
1779 }
1780 
1781 /*
1782  * Called after CTX has been created. Set template flags for GS.
1783  * Flags are copied to GS on GS_new().
1784  */
1785 int
GS_CTX_setsockopt(GS_CTX * ctx,int level,const void * opt_value,size_t opt_len)1786 GS_CTX_setsockopt(GS_CTX *ctx, int level, const void *opt_value, size_t opt_len)
1787 {
1788 
1789 	/* PROTOCOL FLAGS -> copied into pkt's flags 1:1 */
1790 	if (level == GS_OPT_SOCKWAIT)
1791 		ctx->flags_proto |= GS_FL_PROTO_WAIT;
1792 	else if (level == GS_OPT_CLIENT_OR_SERVER)
1793 		ctx->flags_proto |= GS_FL_PROTO_CLIENT_OR_SERVER;
1794 	/* FLAGS */
1795 	else if (level == GS_OPT_BLOCK)
1796 		ctx->gs_flags &= ~GSC_FL_NONBLOCKING;
1797 	else if (level == GS_OPT_NO_ENCRYPTION)
1798 		ctx->gs_flags &= ~GSC_FL_USE_SRP;
1799 	else if (level == GS_OPT_SINGLESHOT)
1800 		ctx->gs_flags |= GS_FL_SINGLE_SHOT;
1801 	/* OPTIONS */
1802 	else if (level == GS_OPT_USE_SOCKS)
1803 	{
1804 		/* Set if not already set from GS_CTX_init() */
1805 		if (ctx->socks_ip == 0)
1806 			ctx->socks_ip = inet_addr(GS_SOCKS_DFL_IP);
1807 	} else
1808 		return -1;
1809 
1810 	return 0;	// Success
1811 }
1812 
1813 
1814 void
GS_FD_CLR_R(GS * gs)1815 GS_FD_CLR_R(GS *gs)
1816 {
1817 	GS_SELECT_CTX *sctx = gs->ctx->gselect_ctx;
1818 	int fd = gs->fd;
1819 
1820 	if (sctx->is_rw_state_saved[fd])
1821 	{
1822 		// DEBUGF_R("Clearing fd=%d in SAVES state\n", fd);
1823 		/* Add to saved state */
1824 		sctx->saved_rw_state[fd] &= ~0x01;	/* clear READ */
1825 	} else {
1826 		// DEBUGF_R("Clearing fd=%d in rfd state\n", fd);
1827 		FD_CLR(fd, sctx->rfd);
1828 	}
1829 
1830 }
1831 
1832 /*
1833  * Return 0 on WOULD_BLOCK
1834  * Return FATAL on error
1835  * Return EOF
1836  * Return length on SUCCESS
1837  */
1838 ssize_t
GS_read(GS * gsocket,void * buf,size_t count)1839 GS_read(GS *gsocket, void *buf, size_t count)
1840 {
1841 	ssize_t len;
1842 	int err = 0;
1843 	// DEBUGF("GS_read(fd = %d)...\n", gsocket->fd);
1844 	GS_SELECT_CTX *sctx = gsocket->ctx->gselect_ctx;
1845 	DEBUG_SETID(gsocket);
1846 
1847 	if (gsocket->flags & GSC_FL_USE_SRP)
1848 	{
1849 #ifndef WITH_GSOCKET_SSL
1850 		return GS_ERR_FATAL;
1851 #else
1852 		len = gs_ssl_continue(gsocket, GS_CAN_READ);
1853 		// DEBUGF("gs_ssl_continue()==%zd, ssl-state=%d\n", len, gsocket->ssl_state);
1854 		if (len <= 0)
1855 			return len;
1856 
1857 		len = SSL_read(gsocket->ssl, buf, count);
1858 
1859 		if (len <= 0)
1860 		{
1861 			err = SSL_get_error(gsocket->ssl, len);
1862 			DEBUGF_Y("fd=%d, SSL Error: ret = %zd, err = %d (%s)\n", gsocket->fd, len, err, GS_SSL_strerror(err));
1863 			ERR_print_errors_fp(stderr);
1864 		}
1865 #endif
1866 	} else {
1867 		len = read(gsocket->fd, buf, count);
1868 		// DEBUGF_M("read(fd=%d) = %zd, errno = %d\n", gsocket->fd, len, errno);
1869 
1870 		if (len == 0)
1871 		{
1872 			/* See BUG-TCP-SHUTDOWN: We must stop calling read() if we received
1873 			 * a shutdown() or close() [can not differentiate]. Stop receiving
1874 			 * but still allow sending until write() fails or stdin closes (for gs-pipe)
1875 			 */
1876 			/* Must clear both so to never ever read() again (cleartext) */
1877 			GS_FD_CLR_R(gsocket);
1878 			FD_CLR(GS_get_fd(gsocket), gsocket->ctx->rfd);
1879 			err = SSL_ERROR_ZERO_RETURN;
1880 		}
1881 
1882 		if (len < 0)
1883 		{
1884 			if ((errno != EAGAIN) && (errno != EINTR))
1885 				return GS_ERR_FATAL;
1886 			err = SSL_ERROR_WANT_READ;
1887 		}
1888 	}
1889 
1890 	/* SSL_ERROR_ZERO_RETURNS successfully read from socket (an error message, but
1891 	 * nevertheless...we can get out of our saved state gain)
1892 	 */
1893 	if ((len > 0) || (err == SSL_ERROR_ZERO_RETURN))
1894 	{
1895 		errno = 0;
1896 		gsocket->ts_net_io = GS_TV_TO_USEC(gsocket->ctx->tv_now);
1897 		gsocket->bytes_read += len;
1898 		// DEBUGF("write_pending=%d\n", gsocket->write_pending);
1899 		if (gsocket->write_pending == 0)
1900 			gs_ssl_want_io_finished(gsocket);
1901 		gsocket->read_pending = 0;
1902 		gsocket->ctx->gselect_ctx->blocking_func[gsocket->fd] &= ~GS_CALLREAD;
1903 		// gsocket->ctx->gselect_ctx->current_func[gsocket->fd] = 0;
1904 		/* Mark if there is still data in the input buffer so another cb is done */
1905 #ifdef WITH_GSOCKET_SSL
1906 		if ((gsocket->ssl) && (SSL_pending(gsocket->ssl) > 0))
1907 		{
1908 			DEBUGF("rdata-pending\n");
1909 			gs_select_set_rdata_pending(gsocket->ctx->gselect_ctx, gsocket->fd, SSL_pending(gsocket->ssl));
1910 		}
1911 #endif
1912 	}
1913 
1914 	if (len > 0)
1915 		return len;	// HERE: len > 0
1916 
1917 	/* ERROR */
1918 	if (err == SSL_ERROR_ZERO_RETURN)
1919 	{
1920 		gsocket->eof_count++;
1921 		DEBUGF_R("%d. EOF received by gs (fd = %d).\n", gsocket->eof_count, gsocket->fd);
1922 		/* Second EOF means that the underlying transport was shut (TCP). It's a hard fail. */
1923 		if (gsocket->eof_count >= 2)
1924 			return GS_ERR_FATAL;
1925 		/* We sent shutdown already and now we receive a shutdown => Destroy connection. */
1926 		if (gsocket->is_sent_shutdown)
1927 		{
1928 			DEBUGF_B("I sent a shutdown already. Destroy connection now.\n");
1929 			return GS_ERR_FATAL;
1930 		}
1931 		return GS_ERR_EOF;
1932 	}
1933 
1934 	gsocket->read_pending = 1;
1935 
1936 	int ret;
1937 	ret = 0;
1938 	if (err == SSL_ERROR_WANT_WRITE)
1939 	{
1940 		sctx->blocking_func[gsocket->fd] |= GS_CALLREAD;
1941 		ret = gs_ssl_want_io_rw(sctx, gsocket->fd, err);
1942 	}
1943 
1944 	if (err != SSL_ERROR_WANT_READ)
1945 		return GS_ERR_FATAL;	// Any other error
1946 
1947 	return ret;
1948 }
1949 
1950 
1951 void
GS_SELECT_FD_SET_W(GS * gs)1952 GS_SELECT_FD_SET_W(GS *gs)
1953 {
1954 	GS_SELECT_CTX *sctx = gs->ctx->gselect_ctx;
1955 	int fd = gs->fd;
1956 
1957 	if (sctx->is_rw_state_saved[fd])
1958 	{
1959 		/* Add to saved state */
1960 		sctx->saved_rw_state[fd] |= 0x02;	/* add WRITE */
1961 	} else {
1962 		XFD_SET(fd, sctx->wfd);
1963 	}
1964 }
1965 
1966 /*
1967  * Return 0 on WOULD_BLOCK
1968  * Return -1 on error
1969  * Return -2 nothing to be done.
1970  * Return lengh on SUCCESS
1971  */
1972 ssize_t
GS_write(GS * gsocket,const void * buf,size_t count)1973 GS_write(GS *gsocket, const void *buf, size_t count)
1974 {
1975 	ssize_t len;
1976 	int err;
1977 
1978 	DEBUG_SETID(gsocket);
1979 	// If already in a stored state then modify the stored state and return to caller
1980 	// that to be called again (caller must not modify rfd/wfd as this is used by SSL...)
1981 	GS_SELECT_CTX *sctx = gsocket->ctx->gselect_ctx;
1982 	// DEBUGF("fd=%d, count=%zu is_state_saved=%d(==%d), pending=%d\n", gsocket->fd, count, sctx->is_rw_state_saved[gsocket->fd], sctx->saved_rw_state[gsocket->fd], gsocket->write_pending);
1983 	if (sctx->is_rw_state_saved[gsocket->fd])
1984 	{
1985 		/* HERE: *write() blocked previously or SSL_read() WANTS-WRITE */
1986 		if (gsocket->write_pending == 0)
1987 		{
1988 			/* HERE: GS_write() was called but SSL still busy with SSL_read/SSL_accpet/SSL_connect.
1989 			 * Set wfd in saved state so that when state is restored this function
1990 			 * is triggered.
1991 			 */
1992 			DEBUGF_R("*** WARNING **** Wanting to write app data (%zu) while SSL is busy..\n", count);
1993 			GS_SELECT_FD_SET_W(gsocket);
1994 			/* This should never be called again because we disable cmd's FD-IN */
1995 
1996 			return 0;	/* WOULD BLOCK */
1997 		}
1998 		/* HERE: w-fd became writeable while in saved state */
1999 	}
2000 
2001 	// DEBUGF("GS_write(%zu) to fd = %d, ssl = %p\n", count, gsocket->fd, gsocket->ssl);
2002 
2003 	if (gsocket->flags & GSC_FL_USE_SRP)
2004 	{
2005 #ifndef WITH_GSOCKET_SSL
2006 		return -1;
2007 #else
2008 		len = gs_ssl_continue(gsocket, GS_CAN_WRITE);
2009 		if (len <= 0)
2010 		{
2011 			// HERE: ssl-state continued. Return.
2012 			DEBUGF("gs_ssl_continue()==%zd\n", len);
2013 			return len;
2014 		}
2015 
2016 		// No state to continue
2017 		if (count == 0)
2018 		{
2019 			// This can happen if we receive an app-ping. This sets
2020 			// wfd (for writing) to wake up to send the pong-reply.
2021 			// The write-callback is called and does not know if the SSL-state
2022 			// has to continue (wanted write?) or if it is an outstanding pong-reply.
2023 			// Thus the callback calls GS_write() and _here_ we determine that no
2024 			// SSL-state needed attention. The caller then sends the pong.
2025 			DEBUGF_C("GS_write() with no data. NO stuck state either.\n");
2026 			return -2;
2027 		}
2028 
2029 		len = SSL_write(gsocket->ssl, buf, count);
2030 		// DEBUGF_M("SSL_write(%zu) == %zd\n", count, len);
2031 		if (len <= 0)
2032 		{
2033 			err = SSL_get_error(gsocket->ssl, len);
2034 			DEBUGF_Y("fd=%d (count=%zu), SSL Error: ret = %zd, err = %d (%s)\n", gsocket->fd, count, len, err, GS_SSL_strerror(err));
2035 		}
2036 #endif
2037 	} else {
2038 		len = write(gsocket->fd, buf, count);
2039 		// DEBUGF("write(%zu) = %zd (%s)\n", count, len, errno==0?"ok":strerror(errno));
2040 
2041 		if (len <= 0)
2042 		{
2043 			if ((errno != EAGAIN) & (errno != EINTR))
2044 				return -1;
2045 			err = SSL_ERROR_WANT_WRITE;
2046 		}
2047 	}
2048 
2049 	if (len > 0)
2050 	{
2051 			errno = 0;
2052 			gsocket->bytes_written += len;
2053 			if (gsocket->read_pending == 0)
2054 				gs_ssl_want_io_finished(gsocket);
2055 			gsocket->write_pending = 0;
2056 			sctx->blocking_func[gsocket->fd] &= ~GS_CALLWRITE;
2057 			FD_CLR(gsocket->fd, sctx->wfd);
2058 
2059 			return len;
2060 	}
2061 
2062 	/* ERROR */
2063 	int ret;
2064 	ret = 0;
2065 #if 1
2066 	sctx->blocking_func[gsocket->fd] |= GS_CALLWRITE;
2067 	ret = gs_ssl_want_io_rw(sctx, gsocket->fd, err);
2068 #endif
2069 	gsocket->write_pending = 1;
2070 
2071 	// DEBUGF("write = %zd %s\n", len, strerror(errno));
2072 	return ret;
2073 }
2074 
2075 /******************************************************************************
2076  * GS UTILS                                                                   *
2077  ******************************************************************************/
2078 
2079 static const char       b58digits_ordered[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
2080 static const int8_t b58digits_map[] = {
2081 	-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
2082 	-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
2083 	-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
2084 	-1, 0, 1, 2, 3, 4, 5, 6,  7, 8,-1,-1,-1,-1,-1,-1,
2085 	-1, 9,10,11,12,13,14,15, 16,-1,17,18,19,20,21,-1,
2086 	22,23,24,25,26,27,28,29, 30,31,32,-1,-1,-1,-1,-1,
2087 	-1,33,34,35,36,37,38,39, 40,41,42,43,-1,44,45,46,
2088 	47,48,49,50,51,52,53,54, 55,56,57,-1,-1,-1,-1,-1,
2089 };
2090 
2091 
2092 /*
2093  * Convert usec into human readable string of duration.
2094  * '123hrs 59min 59.283sec'
2095  */
2096 char *
GS_usecstr(char * buf,size_t len,uint64_t usec)2097 GS_usecstr(char *buf, size_t len, uint64_t usec)
2098 {
2099 	static char buf2[64];
2100 	char *ptr = buf;
2101 
2102 	if (buf == NULL)
2103 	{
2104 		len = sizeof buf2;
2105 		ptr = buf2;
2106 	}
2107 
2108 	int sec;
2109 	int min;
2110 	int msec;
2111 	int hr;
2112 
2113 	// usec = (uint64_t)((2*60*60+61)*1000 + 123) * 1000;
2114 	msec = (usec / 1000) % 1000;
2115 	sec = usec / 1000000;
2116 
2117 	hr = sec / 3600;
2118 	sec -= hr * 3600;
2119 	min = sec / 60;
2120 	sec -= min * 60;
2121 
2122 	*ptr = 0;
2123 
2124 	if (hr != 0)
2125 		snprintf(ptr, len, "%dhrs %2dmin %2d.%03dsec", hr, min, sec, msec);
2126 	else
2127 		snprintf(ptr, len, "%2d min %2d.%03d sec", min, sec, msec);
2128 	return ptr;
2129 
2130 }
2131 
2132 /*
2133  * Convert bytes into human readable string (TB, MB, KB or B).
2134  */
2135 char *
GS_bytesstr(char * dst,size_t len,int64_t bytes)2136 GS_bytesstr(char *dst, size_t len, int64_t bytes)
2137 {
2138 	static char buf2[64];
2139 	char *ptr = dst;
2140 
2141 	if (dst == NULL)
2142 	{
2143 		len = sizeof buf2;
2144 		ptr = buf2;
2145 	}
2146 
2147 	int i;
2148 
2149 	bytes *= 100;
2150 	for (i = 0; bytes >= 100*1000 && unit[i] != 'T'; i++)
2151 		bytes = (bytes + 512) / 1024;
2152 
2153 	snprintf(ptr, len, "%3lld.%1lld%c%s",
2154 		(long long) (bytes + 5) / 100,
2155 		(long long) (bytes + 5) / 10 % 10,
2156 		unit[i],
2157 		i ? "B" : " ");
2158 
2159 	return ptr;
2160 }
2161 
2162 /*
2163  * Convert bytes into full length string with thousands seperation ','
2164  */
2165 char *
GS_bytesstr_long(char * dst,size_t len,int64_t bytes)2166 GS_bytesstr_long(char *dst, size_t len, int64_t bytes)
2167 {
2168 	if (dst == NULL)
2169 		return NULL;
2170 
2171 	int m = bytes / 1000 / 1000;
2172 	bytes -= m * 1000 * 1000;
2173 	int k = bytes / 1000;
2174 	bytes -= k * 1000;
2175 
2176 	if (m > 0)
2177 		snprintf(dst, len, "%d,%03d,%03d", m, k, (int)bytes);
2178 	else if (k > 0)
2179 		snprintf(dst, len, "%d,%03d", k, (int)bytes);
2180 	else
2181 		snprintf(dst, len, "%d", (int)bytes);
2182 
2183 	return dst;
2184 }
2185 
2186 /*
2187  * Create 'local' timestamp logfile style.
2188  */
2189 const char *
GS_logtime(void)2190 GS_logtime(void)
2191 {
2192 	static char tbuf[32];
2193 
2194 	time_t t = time(NULL);
2195 	strftime(tbuf, sizeof tbuf, "%c", localtime(&t));
2196 
2197 	return tbuf;
2198 }
2199 
2200 bool
b58tobin(void * bin,size_t * binszp,const char * b58,size_t b58sz)2201 b58tobin(void *bin, size_t *binszp, const char *b58, size_t b58sz)
2202 {
2203 
2204 	size_t binsz = *binszp;
2205 	const unsigned char *b58u = (void*)b58;
2206 	unsigned char *binu = bin;
2207 	size_t outisz = (binsz + 3) / 4;
2208 	uint32_t outi[outisz];
2209 	uint64_t t;
2210 	uint32_t c;
2211 	size_t i, j;
2212 	uint8_t bytesleft = binsz % 4;
2213 	uint32_t zeromask = bytesleft ? (0xffffffff << (bytesleft * 8)) : 0;
2214 	unsigned zerocount = 0;
2215 
2216 	if (!b58sz)
2217 		b58sz = strlen(b58);
2218 
2219 	memset(outi, 0, outisz * sizeof(*outi));
2220 
2221 	// Leading zeros, just count
2222 	for (i = 0; i < b58sz && b58u[i] == '1'; ++i)
2223 		++zerocount;
2224 
2225 	for ( ; i < b58sz; ++i)
2226 	{
2227 		if (b58u[i] & 0x80)
2228 			// High-bit set on invalid digit
2229 			return false;
2230 		if (b58digits_map[b58u[i]] == -1)
2231 			// Invalid base58 digit
2232 			return false;
2233 		c = (unsigned)b58digits_map[b58u[i]];
2234 		for (j = outisz; j--; )
2235 		{
2236 			t = ((uint64_t)outi[j]) * 58 + c;
2237 			c = (t & 0x3f00000000) >> 32;
2238 			outi[j] = t & 0xffffffff;
2239 		}
2240 		if (c)
2241 			// Output number too big (carry to the next int32)
2242 			return false;
2243 		if (outi[0] & zeromask)
2244 			// Output number too big (last int32 filled too far)
2245 			return false;
2246 	}
2247 
2248 	j = 0;
2249 	switch (bytesleft) {
2250 		case 3:
2251 			*(binu++) = (outi[0] &   0xff0000) >> 16;
2252 		case 2:
2253 			*(binu++) = (outi[0] &     0xff00) >>  8;
2254 		case 1:
2255 			*(binu++) = (outi[0] &       0xff);
2256 			++j;
2257 		default:
2258 			break;
2259 	}
2260 
2261 	for (; j < outisz; ++j)
2262 	{
2263 		*(binu++) = (outi[j] >> 0x18) & 0xff;
2264 		*(binu++) = (outi[j] >> 0x10) & 0xff;
2265 		*(binu++) = (outi[j] >>    8) & 0xff;
2266 		*(binu++) = (outi[j] >>    0) & 0xff;
2267 	}
2268 
2269 	// Count canonical base58 byte count
2270 	binu = bin;
2271 	for (i = 0; i < binsz; ++i)
2272 	{
2273 		if (binu[i])
2274 			break;
2275 		--*binszp;
2276 	}
2277 	*binszp += zerocount;
2278 
2279 	return true;
2280 }
2281 
2282 #if 0
2283 /* Convert Base58 address to binary. Check CRC.
2284  */
2285 static int
2286 b58dec(void *dst, char *str)
2287 {
2288 	return 0;
2289 }
2290 #endif
2291 
2292 /* Convert 128 bit binary into base58 + CRC
2293  */
2294 static int
b58enc(char * b58,size_t * b58sz,uint8_t * src,size_t binsz)2295 b58enc(char *b58, size_t *b58sz, uint8_t *src, size_t binsz)
2296 {
2297     const uint8_t *bin = src;
2298     int carry;
2299     size_t i, j, high, zcount = 0;
2300     size_t size;
2301 
2302     /* Find out the length. Count leading 0's. */
2303     while (zcount < binsz && !bin[zcount])
2304             ++zcount;
2305 
2306     size = (binsz - zcount) * 138 / 100 + 1;
2307     uint8_t buf[size];
2308     memset(buf, 0, size);
2309 
2310     for (i = zcount, high = size - 1; i < binsz; ++i, high = j)
2311     {
2312             for (carry = bin[i], j = size - 1; (j > high) || carry; --j)
2313             {
2314                     carry += 256 * buf[j];
2315                     buf[j] = carry % 58;
2316                     carry /= 58;
2317                     if (!j)
2318                     {
2319                             break;
2320                     }
2321             }
2322     }
2323 
2324     for (j = 0; j < size && !buf[j]; ++j);
2325 
2326     if (*b58sz <= zcount + size - j)
2327     {
2328             ERREXIT("Wrong size...%zu\n", zcount + size - j + 1);
2329             *b58sz = zcount + size - j + 1;
2330             return -1;
2331     }
2332     if (zcount)
2333     	memset(b58, '1', zcount);
2334 
2335     for (i = zcount; j < size; ++i, ++j)
2336     {
2337             b58[i] = b58digits_ordered[buf[j]];
2338     }
2339     b58[i] = '\0';
2340     *b58sz = i + 1;
2341 
2342 	return 0;
2343 }
2344 
2345 
2346 /*
2347  * Convert a binary to a GS address.
2348  */
2349 GS_ADDR *
GS_ADDR_bin2addr(GS_ADDR * addr,const void * data,size_t len)2350 GS_ADDR_bin2addr(GS_ADDR *addr, const void *data, size_t len)
2351 {
2352 	unsigned char md[SHA256_DIGEST_LENGTH];
2353 	char b58[GS_ADDR_B58_LEN + 1];
2354 	size_t b58sz = sizeof b58;
2355 
2356 	memset(addr, 0, sizeof *addr);
2357 	GS_SHA256(data, len, md);
2358 	memcpy(addr->addr, md, sizeof addr->addr);
2359 
2360 	HEXDUMP(addr->addr, sizeof addr->addr);
2361 
2362 	b58enc(b58, &b58sz, md, GS_ADDR_SIZE);
2363 	DEBUGF("b58 (%lu): %s\n", b58sz, b58);
2364 	addr->b58sz = b58sz;
2365 	snprintf(addr->b58str, sizeof addr->b58str, "%s", b58);
2366 
2367 	return addr;
2368 }
2369 
2370 /*
2371  * Convert a human readable string (password) to GS address.
2372  */
2373 GS_ADDR *
GS_ADDR_str2addr(GS_ADDR * addr,const char * str)2374 GS_ADDR_str2addr(GS_ADDR *addr, const char *str)
2375 {
2376 	addr = GS_ADDR_bin2addr(addr, str, strlen(str));
2377 
2378 	return addr;
2379 }
2380 
2381 /*
2382  * Derive a GS-Address from IPv4 + Port tuple.
2383  * Use at your own risk. GS-Address can easily be guessed.
2384  */
2385 GS_ADDR *
GS_ADDR_ipport2addr(GS_ADDR * addr,uint32_t ip,uint16_t port)2386 GS_ADDR_ipport2addr(GS_ADDR *addr, uint32_t ip, uint16_t port)
2387 {
2388 	struct in_addr in;
2389 	char buf[128];
2390 
2391 	in.s_addr = ip;
2392 
2393 	snprintf(buf, sizeof buf, "%s:%d", inet_ntoa(in), ntohs(port));
2394 	//DEBUGF("%s\n", buf);
2395 	GS_ADDR_str2addr(addr, buf);
2396 
2397 	return addr;
2398 }
2399 
2400 /*
2401  * Set the 'listen' token. This will stop a client (who knows the secret) to
2402  * impersonate a server (while the server is connected).
2403  *
2404  * A User might decide to use the same 'token' as a kind of master password
2405  * for all its servers. We like not to be able to track the User. Thus the
2406  * token is a has over TOKEN-STRING + GS-ADDRESS. This makes every token unique
2407  * per GS-ADDRESS.
2408  *
2409  * FIXME: extend this later to use as an auth-token:
2410  * - store token on GS-net server side
2411  * - Any 'server' connecting must present same token to be allowed
2412  *   to send pkt-listen message.
2413  * - User can control this with e.g. '-a <Any Server Listen Password>'
2414  */
2415 void
GS_set_token(GS * gs,const void * data,size_t len)2416 GS_set_token(GS *gs, const void *data, size_t len)
2417 {
2418 	unsigned char md[SHA256_DIGEST_LENGTH];
2419 	uint8_t *input;
2420 
2421 	if (data == NULL)
2422 		RAND_bytes(gs->token, sizeof gs->token);
2423 	else {
2424 		input = malloc(len + sizeof gs->gs_addr.addr);
2425 		memcpy(input, data, len);
2426 		memcpy(input + len, gs->gs_addr.addr, sizeof gs->gs_addr.addr);
2427 		GS_SHA256(input, len + sizeof gs->gs_addr.addr, md);
2428 		memcpy(gs->token, md, sizeof gs->token);
2429 		free(input);
2430 	}
2431 	HEXDUMPF(gs->token, sizeof gs->token, "Token:\n");
2432 }
2433 
2434 int
GS_is_server(GS * gs)2435 GS_is_server(GS *gs)
2436 {
2437 	return gs->flags & GS_FL_IS_SERVER;
2438 }
2439 
2440