summaryrefslogtreecommitdiff
path: root/net.c
blob: 032b02c3f85497724db0f7a580b5acd1d610743c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
/*
 * Copyright (C) 2005-2007 Andre Noll <maan@systemlinux.org>
 *
 * Licensed under the GPL v2. For licencing details see COPYING.
 */

/** \file net.c networking-related helper functions */

#include "para.h"
#include "net.h"
#include "string.h"
#include "error.h"


/** Information about one encrypted connection. */
struct crypt_data {
	/** Function used to decrypt received data. */
	crypt_function *recv;
	/** Function used to encrypt data to be sent. */
	crypt_function *send;
	/**
	 * Context-dependent data (crypt keys), passed verbatim to the above
	 * crypt functions.
	 */
	void *private_data;
};
/** Array holding per fd crypt data. */
static struct crypt_data *crypt_data_array;
/** Current size of the crypt data array. */
static unsigned cda_size = 0;

/**
 * activate encryption for one file descriptor
 *
 * \param fd the file descriptor
 * \param recv_f the function used for decrypting received data
 * \param send_f the function used for encrypting before sending
 * \param private_data user data supplied by the caller
 */
void enable_crypt(int fd, crypt_function *recv_f, crypt_function *send_f,
	void *private_data)
{
	if (fd + 1 > cda_size) {
		crypt_data_array = para_realloc(crypt_data_array,
			(fd + 1) * sizeof(struct crypt_data));
		memset(crypt_data_array + cda_size, 0,
			(fd + 1 - cda_size) * sizeof(struct crypt_data));
		cda_size = fd + 1;
	}
	crypt_data_array[fd].recv = recv_f;
	crypt_data_array[fd].send = send_f;
	crypt_data_array[fd].private_data = private_data;
	PARA_INFO_LOG("rc4 encryption activated for fd %d\n", fd);
}

/**
 * deactivate encryption for a given fd
 *
 * \param fd the file descriptor
 *
 * This must be called if and only if \p fd was activated via enable_crypt().
 */
void disable_crypt(int fd)
{
	if (cda_size < fd + 1)
		return;
	crypt_data_array[fd].recv = NULL;
	crypt_data_array[fd].send = NULL;
	crypt_data_array[fd].private_data = NULL;
}


/**
 * initialize a struct sockaddr_in
 *
 * \param addr A pointer to the struct to be initialized
 * \param port The port number to use
 * \param he The address to use
 *
 * If \a he is null (server mode), \a addr->sin_addr is initialized with \p
 * INADDR_ANY.  Otherwise, the address given by \a he is copied to addr.
 */
void init_sockaddr(struct sockaddr_in *addr, int port, const struct hostent *he)
{
	/* host byte order */
	addr->sin_family = AF_INET;
	/* short, network byte order */
	addr->sin_port = htons(port);
	if (he)
		addr->sin_addr = *((struct in_addr *)he->h_addr);
	else
		addr->sin_addr.s_addr = INADDR_ANY;
	/* zero the rest of the struct */
	memset(&addr->sin_zero, '\0', 8);
}

/*
 * send out a buffer, resend on short writes
 *
 * \param fd the file descriptor
 * \param buf The buffer to be sent
 * \param len The length of \a buf
 *
 * Due to circumstances beyond your control, the kernel might not send all the
 * data out in one chunk, and now, my friend, it's up to us to get the data out
 * there (Beej's Guide to Network Programming).
 *
 * \return This function returns 1 on success and \a -E_SEND on errors. The
 * number of bytes actually sent is stored upon successful return in \a len.
 */
static int sendall(int fd, const char *buf, size_t *len)
{
	size_t total = 0, bytesleft = *len; /* how many we have left to send */
	int n = -1;

	while (total < *len) {
		n = send(fd, buf + total, bytesleft, 0);
		if (n == -1)
			break;
		total += n;
		bytesleft -= n;
		if (total < *len)
			PARA_DEBUG_LOG("short write (%zd byte(s) left)\n",
				*len - total);
	}
	*len = total; /* return number actually sent here */
	return n == -1? -E_SEND : 1; /* return 1 on success */
}

/**
 * encrypt and send buffer
 *
 * \param fd:  the file descriptor
 * \param buf the buffer to be encrypted and sent
 * \param len the length of \a buf
 *
 * Check if encrytpion is available. If yes, encrypt the given buffer.  Send out
 * the buffer, encrypted or not, and try to resend the remaing part in case of
 * short writes.
 *
 * \return Positive on success, \p -E_SEND on errors.
 */
int send_bin_buffer(int fd, const char *buf, size_t len)
{
	int ret;
	crypt_function *cf = NULL;

	if (!len)
		PARA_CRIT_LOG("%s", "len == 0\n");
	if (fd + 1 <= cda_size)
		cf = crypt_data_array[fd].send;
	if (cf) {
		void *private = crypt_data_array[fd].private_data;
		/* RC4 may write more than len to the output buffer */
		unsigned char *outbuf = para_malloc(ROUND_UP(len, 8));
		(*cf)(len, (unsigned char *)buf, outbuf, private);
		ret = sendall(fd, (char *)outbuf, &len);
		free(outbuf);
	} else
		ret = sendall(fd, buf, &len);
	return ret;
}

/**
 * encrypt and send null terminated buffer.
 *
 * \param fd the file descriptor
 * \param buf the null-terminated buffer to be send
 *
 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
 *
 * \return Positive on success, \p -E_SEND on errors.
 */
int send_buffer(int fd, const char *buf)
{
	return send_bin_buffer(fd, buf, strlen(buf));
}


/**
 * send and encrypt a buffer given by a format string
 *
 * \param fd the file descriptor
 * \param fmt a format string
 *
 * \return Positive on success, \p -E_SEND on errors.
 */
__printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
{
	char *msg;
	int ret;

	PARA_VSPRINTF(fmt, msg);
	ret = send_buffer(fd, msg);
	free(msg);
	return ret;
}

/**
 * receive and decrypt.
 *
 * \param fd the file descriptor
 * \param buf the buffer to write the decrypted data to
 * \param size the size of \a buf
 *
 * Receive at most \a size bytes from filedescriptor fd. If encryption is
 * available, decrypt the received buffer.
 *
 * \return The number of bytes received on success. On receive errors, -E_RECV
 * is returned. On crypt errors, the corresponding crypt error number is
 * returned.
 *
 * \sa recv(2)
 */
__must_check int recv_bin_buffer(int fd, char *buf, size_t size)
{
	ssize_t n;
	crypt_function *cf = NULL;

	if (fd + 1 <= cda_size)
		cf = crypt_data_array[fd].recv;
	if (cf) {
		unsigned char *tmp = para_malloc(size);
		void *private = crypt_data_array[fd].private_data;
		n = recv(fd, tmp, size, 0);
		if (n > 0) {
			size_t numbytes = n;
			unsigned char *b = (unsigned char *)buf;
			(*cf)(numbytes, tmp, b, private);
		}
		free(tmp);
	} else
		n = recv(fd, buf, size, 0);
	if (n == -1)
		n = -E_RECV;
	return n;
}

/**
 * receive, decrypt and write terminating NULL byte
 *
 * \param fd the file descriptor
 * \param buf the buffer to write the decrypted data to
 * \param size the size of \a buf
 *
 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
 * write a NULL byte at the end of the received data.
 *
 * \return: The return value of the underlying call to \a recv_bin_buffer().
 *
 * \sa recv_bin_buffer()
 */
int recv_buffer(int fd, char *buf, size_t size)
{
	int n;

	if (!size)
		return -E_RECV;
	n = recv_bin_buffer(fd, buf, size - 1);
	if (n >= 0)
		buf[n] = '\0';
	else
		*buf = '\0';
	return n;
}

/**
 * wrapper around gethostbyname
 *
 * \param host hostname or IPv4 address
 * \param ret the hostent structure is returned here
 *
 * \return positive on success, negative on errors. On success, \a ret
 * contains the return value of the underlying gethostbyname() call.
 *
 * \sa gethostbyname(2)
 */
int get_host_info(char *host, struct hostent **ret)
{
	PARA_INFO_LOG("getting host info of %s\n", host);
	/* FIXME: gethostbyname() is obsolete */
	*ret = gethostbyname(host);
	return *ret? 1 : -E_HOST_INFO;
}

/**
 * a wrapper around socket(2)
 *
 * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
 * byte streams.
 *
 * \return The socket fd on success, -E_SOCKET on errors.
 *
 * \sa socket(2)
 */
int get_socket(void)
{
	int socket_fd;

	if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
		return -E_SOCKET;
	return socket_fd;
}

/**
 * a wrapper around connect(2)
 *
 * \param fd the file descriptor
 * \param their_addr the address to connect
 *
 * \return \p -E_CONNECT on errors, 1 on success
 *
 * \sa connect(2)
 */
int para_connect(int fd, struct sockaddr_in *their_addr)
{
	int ret;

	if ((ret = connect(fd, (struct sockaddr *)their_addr,
			sizeof(struct sockaddr))) == -1)
		return -E_CONNECT;
	return 1;
}

/**
 * paraslash's wrapper around the accept system call
 *
 * \param fd the listening socket
 * \param addr structure which is filled in with the address of the peer socket
 * \param size should contain the size of the structure pointed to by \a addr
 *
 * Accept incoming connections on \a addr. Retry if interrupted.
 *
 * \return The new file descriptor on success, \a -E_ACCEPT on errors.
 *
 * \sa accept(2).
 */
int para_accept(int fd, void *addr, socklen_t size)
{
	int new_fd;

	do
		new_fd = accept(fd, (struct sockaddr *) addr, &size);
	while (new_fd < 0 && errno == EINTR);
	return new_fd < 0? -E_ACCEPT : new_fd;
}

static int setserversockopts(int socket_fd)
{
	int yes = 1;

	if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes,
			sizeof(int)) == -1)
		return -E_SETSOCKOPT;
	return 1;
}

/**
 * prepare a structure for \p AF_UNIX socket addresses
 *
 * \param u pointer to the struct to be prepared
 * \param name the socket pathname
 *
 * This just copies \a name to the sun_path component of \a u.
 *
 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
 * than \p UNIX_PATH_MAX.
 */
int init_unix_addr(struct sockaddr_un *u, const char *name)
{
	if (strlen(name) >= UNIX_PATH_MAX)
		return -E_NAME_TOO_LONG;
	memset(u->sun_path, 0, UNIX_PATH_MAX);
	u->sun_family = PF_UNIX;
	strcpy(u->sun_path, name);
	return 1;
}

/**
 * Prepare, create, and bind a socket for local communication.
 *
 * \param name The socket pathname.
 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
 * \param mode The desired mode of the socket.
 *
 * This functions creates a local socket for sequenced, reliable,
 * two-way, connection-based byte streams.
 *
 * \return The file descriptor, on success, negative on errors.
 *
 * \sa socket(2)
 * \sa bind(2)
 * \sa chmod(2)
 */
int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
		mode_t mode)
{
	int fd, ret;

	ret = init_unix_addr(unix_addr, name);
	if (ret < 0)
		return ret;
	fd = socket(PF_UNIX, SOCK_STREAM, 0);
	if (fd < 0)
		return -E_SOCKET;
	ret = -E_BIND;
	if (bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX) < 0)
		goto err;
	ret = -E_CHMOD;
	if (chmod(name, mode) < 0)
		goto err;
	return fd;
err:
	close(fd);
	return ret;
}

#ifndef HAVE_UCRED
ssize_t send_cred_buffer(int sock, char *buf)
{
	return send_buffer(sock, buf);
}
int recv_cred_buffer(int fd, char *buf, size_t size)
{
	return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
}
#else /* HAVE_UCRED */
/**
 * send NULL terminated buffer and Unix credentials of the current process
 *
 * \param sock the socket file descriptor
 * \param buf the buffer to be sent
 *
 * \return On success, this call returns the number of characters sent.  On
 * error, \p -E_SENDMSG ist returned.
 *
 * \sa  okir's Black Hats Manual
 * \sa sendmsg(2)
 */
ssize_t send_cred_buffer(int sock, char *buf)
{
	char control[sizeof(struct cmsghdr) + 10];
	struct msghdr msg;
	struct cmsghdr *cmsg;
	static struct iovec iov;
	struct ucred c;
	int ret;

	/* Response data */
	iov.iov_base = buf;
	iov.iov_len  = strlen(buf);
	c.pid = getpid();
	c.uid = getuid();
	c.gid = getgid();
	/* compose the message */
	memset(&msg, 0, sizeof(msg));
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;
	msg.msg_control = control;
	msg.msg_controllen = sizeof(control);
	/* attach the ucred struct */
	cmsg = CMSG_FIRSTHDR(&msg);
	cmsg->cmsg_level = SOL_SOCKET;
	cmsg->cmsg_type = SCM_CREDENTIALS;
	cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
	*(struct ucred *)CMSG_DATA(cmsg) = c;
	msg.msg_controllen = cmsg->cmsg_len;
	ret = sendmsg(sock, &msg, 0);
	if (ret  < 0)
		ret = -E_SENDMSG;
	return ret;
}

static void dispose_fds(int *fds, unsigned num)
{
	int i;

	for (i = 0; i < num; i++)
		close(fds[i]);
}

/**
 * receive a buffer and the Unix credentials of the sending process
 *
 * \param fd the socket file descriptor
 * \param buf the buffer to store the message
 * \param size the size of \a buffer
 *
 * \return negative on errors, the user id on success.
 *
 * \sa okir's Black Hats Manual
 * \sa recvmsg(2)
 */
int recv_cred_buffer(int fd, char *buf, size_t size)
{
	char control[255];
	struct msghdr msg;
	struct cmsghdr *cmsg;
	struct iovec iov;
	int result = 0;
	int yes = 1;
	struct ucred cred;

	setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
	memset(&msg, 0, sizeof(msg));
	memset(buf, 0, size);
	iov.iov_base = buf;
	iov.iov_len = size;
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;
	msg.msg_control = control;
	msg.msg_controllen = sizeof(control);
	if (recvmsg(fd, &msg, 0) < 0)
		return -E_RECVMSG;
	result = -E_SCM_CREDENTIALS;
	cmsg = CMSG_FIRSTHDR(&msg);
	while (cmsg) {
		if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
				== SCM_CREDENTIALS) {
			memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
			result = cred.uid;
		} else
			if (cmsg->cmsg_level == SOL_SOCKET
					&& cmsg->cmsg_type == SCM_RIGHTS) {
				dispose_fds((int *) CMSG_DATA(cmsg),
					(cmsg->cmsg_len - CMSG_LEN(0))
					/ sizeof(int));
			}
		cmsg = CMSG_NXTHDR(&msg, cmsg);
	}
	return result;
}
#endif /* HAVE_UCRED */

/** how many pending connections queue will hold */
#define BACKLOG 10

/**
 * create a socket, bind it and listen
 *
 * \param port the tcp port to listen on
 *
 * \return The file descriptor of the created socket, negative
 * on errors.
 *
 * \sa get_socket()
 * \sa setsockopt(2)
 * \sa bind(2)
 * \sa listen(2)
 */
int init_tcp_socket(int port)
{
	struct sockaddr_in my_addr;
	int fd, ret = get_socket();

	if (ret < 0)
		return ret;
	fd = ret;
	ret = setserversockopts(fd);
	if (ret < 0)
		goto err;
	init_sockaddr(&my_addr, port, NULL);
	ret = -E_BIND;
	if (bind(fd, (struct sockaddr *)&my_addr,
			sizeof(struct sockaddr)) == -1) {
		PARA_CRIT_LOG("bind error: %s\n", strerror(errno));
		goto err;
	}
	ret = -E_LISTEN;
	if (listen(fd, BACKLOG) == -1)
		goto err;
	PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
	return fd;
err:
	close(fd);
	return ret;
}

/**
 * receive a buffer and check for a pattern
 *
 * \param fd the file descriptor to receive from
 * \param pattern the expected pattern
 * \param bufsize the size of the internal buffer
 *
 * \return Positive if \a pattern was received, negative otherwise.
 *
 * This function creates a buffer of size \a bufsize and tries
 * to receive at most \a bufsize bytes from file descriptor \a fd.
 * If at least \p strlen(\a pattern) bytes were received, the beginning of
 * the received buffer is compared with \a pattern, ignoring case.
 *
 * \sa recv_buffer()
 * \sa strncasecmp(3)
 */
int recv_pattern(int fd, const char *pattern, size_t bufsize)
{
	size_t len = strlen(pattern);
	char *buf = para_malloc(bufsize + 1);
	int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);

	if (n < len)
		goto out;
	if (strncasecmp(buf, pattern, len))
		goto out;
	ret = 1;
out:
	if (ret < 0) {
		PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n, pattern);
		if (n > 0)
			PARA_NOTICE_LOG("recvd: %s\n", buf);
	}
	free(buf);
	return ret;
}