add a notice message if the expected pattern was not received
[paraslash.git] / net.c
1 /*
2 * Copyright (C) 2005-2006 Andre Noll <maan@systemlinux.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
17 */
18
19 /** \file net.c networking-related helper functions */
20
21 #include "para.h"
22 #include "net.h"
23 #include "string.h"
24 #include <netdb.h>
25 #include "error.h"
26
27 extern void (*crypt_function_recv)(unsigned long len, const unsigned char *indata, unsigned char *outdata);
28 extern void (*crypt_function_send)(unsigned long len, const unsigned char *indata, unsigned char *outdata);
29
30
31 #ifndef HAVE_UCRED
32 struct ucred {
33 uid_t uid, pid, gid;
34 };
35 #endif /* HAVE_UCRED */
36
37 /**
38 * initialize a struct sockaddr_in
39 * @param addr A pointer to the struct to be initialized
40 * @param port The port number to use
41 * @param he The address to use
42 *
43 * If \a he is null (server mode), \a addr->sin_addr is initialized with \p INADDR_ANY.
44 * Otherwise, the address given by \a he is copied to addr.
45 */
46 void init_sockaddr(struct sockaddr_in *addr, int port, const struct hostent *he)
47 {
48 /* host byte order */
49 addr->sin_family = AF_INET;
50 /* short, network byte order */
51 addr->sin_port = htons(port);
52 if (he)
53 addr->sin_addr = *((struct in_addr *)he->h_addr);
54 else
55 addr->sin_addr.s_addr = INADDR_ANY;
56 /* zero the rest of the struct */
57 memset(&addr->sin_zero, '\0', 8);
58 }
59
60 /*
61 * send out a buffer, resend on short writes
62 * @param fd the file descriptor
63 * @param buf The buffer to be sent
64 * @len The length of \a buf
65 *
66 * Due to circumstances beyond your control, the kernel might not send all the
67 * data out in one chunk, and now, my friend, it's up to us to get the data out
68 * there (Beej's Guide to Network Programming).
69 */
70 static int sendall(int fd, const char *buf, size_t *len)
71 {
72 int total = 0; /* how many bytes we've sent */
73 int bytesleft = *len; /* how many we have left to send */
74 int n = -1;
75
76 while (total < *len) {
77 n = send(fd, buf + total, bytesleft, 0);
78 if (n == -1)
79 break;
80 total += n;
81 bytesleft -= n;
82 if (total < *len)
83 PARA_DEBUG_LOG("short write (%zd byte(s) left)",
84 *len - total);
85 }
86 *len = total; /* return number actually sent here */
87 return n == -1? -E_SEND : 1; /* return 1 on success */
88 }
89
90 /**
91 * encrypt and send buffer
92 * @param fd: the file descriptor
93 * @param buf the buffer to be encrypted and sent
94 * @param len the length of \a buf
95 *
96 * Check if encrytion is available. If yes, encrypt the given buffer. Send out
97 * the buffer, encrypted or not, and try to resend the remaing part in case of
98 * short writes.
99 *
100 * @return Positive on success, \p -E_SEND on errors.
101 */
102 int send_bin_buffer(int fd, const char *buf, size_t len)
103 {
104 int ret;
105
106 if (!len)
107 PARA_CRIT_LOG("%s", "len == 0\n");
108 if (crypt_function_send) {
109 unsigned char *outbuf = para_malloc(len);
110 crypt_function_send(len, (unsigned char *)buf, outbuf);
111 ret = sendall(fd, (char *)outbuf, &len);
112 free(outbuf);
113 } else
114 ret = sendall(fd, buf, &len);
115 return ret;
116 }
117
118 /**
119 * encrypt and send null terminated buffer.
120 * @param fd the file descriptor
121 * @param buf the null-terminated buffer to be send
122 *
123 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
124 *
125 * @return Positive on success, \p -E_SEND on errors.
126 */
127 int send_buffer(int fd, const char *buf)
128 {
129 return send_bin_buffer(fd, buf, strlen(buf));
130 }
131
132
133 /**
134 * send and encrypt a buffer given by a format string
135 * @param fd the file descriptor
136 * @param fmt a format string
137 *
138 * @return Positive on success, \p -E_SEND on errors.
139 */
140 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
141 {
142 char *msg;
143 int ret;
144
145 PARA_VSPRINTF(fmt, msg);
146 ret = send_buffer(fd, msg);
147 free(msg);
148 return ret;
149 }
150
151 /**
152 * receive and decrypt.
153 *
154 * @param fd the file descriptor
155 * @param buf the buffer to write the decrypted data to
156 * @param size the size of @param buf
157 *
158 * Receive at most \a size bytes from filedescriptor fd. If encrytion is
159 * available, decrypt the received buffer.
160 *
161 * @return the number of bytes received on success. On receive errors, -E_RECV
162 * is returned. On crypt errors, the corresponding crypt error number is
163 * returned.
164 * \sa recv(2)
165 */
166 __must_check int recv_bin_buffer(int fd, char *buf, ssize_t size)
167 {
168 int n;
169
170 if (crypt_function_recv) {
171 unsigned char *tmp = para_malloc(size);
172 n = recv(fd, tmp, size, 0);
173 if (n > 0)
174 crypt_function_recv(n, tmp, (unsigned char *)buf);
175 free(tmp);
176 } else
177 n = recv(fd, buf, size, 0);
178 if (n == -1)
179 n = -E_RECV;
180 return n;
181 }
182
183 /**
184 * receive, decrypt and write terminating NULL byte
185 *
186 * @param fd the file descriptor
187 * @param buf the buffer to write the decrypted data to
188 * @param size the size of \a buf
189 *
190 * Read and decrypt at most size - 1 bytes from file descriptor \a fd and write
191 * a NULL byte at the end of the received data.
192 *
193 */
194 int recv_buffer(int fd, char *buf, ssize_t size)
195 {
196 int n;
197
198 if ((n = recv_bin_buffer(fd, buf, size - 1)) >= 0)
199 buf[n] = '\0';
200 return n;
201 }
202
203 /**
204 * wrapper around gethostbyname
205 *
206 * @param host hostname or IPv4 address
207 * \return The hostent structure or a NULL pointer if an error occurs
208 * \sa gethostbyname(2)
209 */
210 struct hostent *get_host_info(char *host)
211 {
212 PARA_INFO_LOG("getting host info of %s\n", host);
213 /* FIXME: gethostbyname() is obsolete */
214 return gethostbyname(host);
215 }
216
217 /**
218 * a wrapper around socket(2)
219 *
220 * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
221 * byte streams.
222 *
223 * @return The socket fd on success, -E_SOCKET on errors.
224 * \sa socket(2)
225 */
226 int get_socket(void)
227 {
228 int socket_fd;
229
230 if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
231 return -E_SOCKET;
232 return socket_fd;
233 }
234
235 /**
236 * a wrapper around connect(2)
237 *
238 * @param fd the file descriptor
239 * @param their_addr the address to connect
240 *
241 * @return \p -E_CONNECT on errors, 1 on success
242 * \sa connect(2)
243 */
244 int para_connect(int fd, struct sockaddr_in *their_addr)
245 {
246 int ret;
247
248 if ((ret = connect(fd, (struct sockaddr *)their_addr,
249 sizeof(struct sockaddr))) == -1)
250 return -E_CONNECT;
251 return 1;
252 }
253
254 /**
255 * paraslash's wrapper around the accept system call
256 *
257 * @param fd the listening socket
258 * @param addr structure which is filled in with the address of the peer socket
259 * @param size should contain the size of the structure pointed to by \a addr
260 *
261 * \sa accept(2).
262 */
263 int para_accept(int fd, void *addr, socklen_t size)
264 {
265 int new_fd;
266
267 new_fd = accept(fd, (struct sockaddr *) addr, &size);
268 return new_fd == -1? -E_ACCEPT : new_fd;
269 }
270
271 static int setserversockopts(int socket_fd)
272 {
273 int yes = 1;
274
275 if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes,
276 sizeof(int)) == -1)
277 return -E_SETSOCKOPT;
278 return 1;
279 }
280
281 static int do_bind(int socket_fd, struct sockaddr_in *my_addr)
282 {
283 if (bind(socket_fd, (struct sockaddr *)my_addr,
284 sizeof(struct sockaddr)) == -1)
285 return -E_BIND;
286 return 1;
287 }
288
289 /**
290 * prepare a structure for \p AF_UNIX socket addresses
291 *
292 * \param u pointer to the struct to be prepared
293 * \param name the socket pathname
294 *
295 * This just copies \a name to the sun_path component of \a u.
296 *
297 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
298 * than \p UNIX_PATH_MAX.
299 */
300 int init_unix_addr(struct sockaddr_un *u, const char *name)
301 {
302 if (strlen(name) >= UNIX_PATH_MAX)
303 return -E_NAME_TOO_LONG;
304 memset(u->sun_path, 0, UNIX_PATH_MAX);
305 u->sun_family = PF_UNIX;
306 strcpy(u->sun_path, name);
307 return 1;
308 }
309
310 /**
311 * prepare, create, and bind and socket for local communication
312 *
313 * \param name the socket pathname
314 * \param unix_addr pointer to the \p AF_UNIX socket structure
315 * \param mode the desired mode of the socket
316 *
317 * This functions creates a local socket for sequenced, reliable,
318 * two-way, connection-based byte streams.
319 * \sa socket(2)
320 * \sa bind(2)
321 * \sa chmod(2)
322 */
323 int create_pf_socket(const char *name, struct sockaddr_un *unix_addr, int mode)
324 {
325 int fd, ret;
326
327 fd = socket(PF_UNIX, SOCK_STREAM, 0);
328 if (fd < 0)
329 return -E_SOCKET;
330 // unlink(name);
331 ret = init_unix_addr(unix_addr, name);
332 if (ret < 0)
333 return ret;
334 if (bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX) < 0)
335 return -E_BIND;
336 if (chmod(name, mode) < 0)
337 return -E_CHMOD;
338 return fd;
339 }
340
341 /**
342 * send NULL terminated buffer and Unix credentials of the current process
343 *
344 * \param sock the socket file descriptor
345 * \param buf the buffer to be sent
346 *
347 * \return On success, this call returns the number of characters sent. On
348 * error, \p -E_SENDMSG ist returned.
349 * \sa okir's Black Hats Manual
350 * \sa sendmsg(2)
351 */
352 ssize_t send_cred_buffer(int sock, char *buf)
353 {
354 char control[sizeof(struct cmsghdr) + 10];
355 struct msghdr msg;
356 struct cmsghdr *cmsg;
357 static struct iovec iov;
358 struct ucred c;
359 int ret;
360
361 /* Response data */
362 iov.iov_base = buf;
363 iov.iov_len = strlen(buf);
364 c.pid = getpid();
365 c.uid = getuid();
366 c.gid = getgid();
367 /* compose the message */
368 memset(&msg, 0, sizeof(msg));
369 msg.msg_iov = &iov;
370 msg.msg_iovlen = 1;
371 msg.msg_control = control;
372 msg.msg_controllen = sizeof(control);
373 #ifdef HAVE_UCRED
374 /* attach the ucred struct */
375 cmsg = CMSG_FIRSTHDR(&msg);
376 cmsg->cmsg_level = SOL_SOCKET;
377 cmsg->cmsg_type = SCM_CREDENTIALS;
378 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
379 *(struct ucred *)CMSG_DATA(cmsg) = c;
380 msg.msg_controllen = cmsg->cmsg_len;
381 #endif
382 ret = sendmsg(sock, &msg, 0);
383 if (ret < 0)
384 ret = -E_SENDMSG;
385 return ret;
386 }
387
388 static void dispose_fds(int *fds, int num)
389 {
390 int i;
391
392 for (i = 0; i < num; i++)
393 close(fds[i]);
394 }
395
396 /**
397 * receive a buffer and the Unix credentials of the sending process
398 *
399 * \param fd the socket file descriptor
400 * \param buf the buffer to store the message
401 * \param size the size of \a buffer
402 *
403 * \return negative on errors, the user id on success.
404 *
405 * \sa okir's Black Hats Manual
406 * \sa recvmsg(2)
407 */
408 int recv_cred_buffer(int fd, char *buf, size_t size)
409 {
410 char control[255];
411 struct msghdr msg;
412 struct cmsghdr *cmsg;
413 struct iovec iov;
414 int result = 0;
415 int yes = 1;
416 struct ucred cred;
417
418 #ifdef HAVE_UCRED
419 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
420 #endif
421 memset(&msg, 0, sizeof(msg));
422 memset(buf, 0, size);
423 iov.iov_base = buf;
424 iov.iov_len = size;
425 msg.msg_iov = &iov;
426 msg.msg_iovlen = 1;
427 msg.msg_control = control;
428 msg.msg_controllen = sizeof(control);
429 if (recvmsg(fd, &msg, 0) < 0)
430 return -E_RECVMSG;
431 #ifdef HAVE_UCRED
432 result = -E_SCM_CREDENTIALS;
433 cmsg = CMSG_FIRSTHDR(&msg);
434 while (cmsg) {
435 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
436 == SCM_CREDENTIALS) {
437 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
438 result = cred.uid;
439 } else
440 if (cmsg->cmsg_level == SOL_SOCKET
441 && cmsg->cmsg_type == SCM_RIGHTS) {
442 dispose_fds((int *) CMSG_DATA(cmsg),
443 (cmsg->cmsg_len - CMSG_LEN(0))
444 / sizeof(int));
445 }
446 cmsg = CMSG_NXTHDR(&msg, cmsg);
447 }
448 #endif
449 return result;
450 }
451
452 /** how many pending connections queue will hold */
453 #define BACKLOG 10
454
455 /**
456 * create a socket, bind it and listen
457 * \param port the tcp port to listen on
458 *
459 * \return The file descriptor of the created socket, negative
460 * on errors.
461 *
462 * \sa get_socket()
463 * \sa setsockopt(2)
464 * \sa bind(2)
465 * \sa listen(2)
466 */
467 int init_tcp_socket(int port)
468 {
469 int sockfd, ret;
470 struct sockaddr_in my_addr;
471
472 if ((sockfd = get_socket()) < 0)
473 return sockfd;
474 ret = setserversockopts(sockfd);
475 if (ret < 0)
476 return ret;
477 init_sockaddr(&my_addr, port, NULL);
478 ret = do_bind(sockfd, &my_addr);
479 if (ret < 0)
480 return ret;
481 if (listen(sockfd, BACKLOG) == -1)
482 return -E_LISTEN;
483 PARA_INFO_LOG("listening on port %d, fd %d\n", port, sockfd);
484 return sockfd;
485 }
486
487 /**
488 * receive a buffer and check for a pattern
489 *
490 * \param fd the file descriptor to receive from
491 * \param pattern the expected pattern
492 * \param bufsize the size of the internal buffer
493 *
494 * \return Positive if \a pattern was received, negative otherwise.
495 *
496 * This function creates a buffer of size \a bufsize and tries
497 * to receive at most \a bufsize bytes from file descriptor \a fd.
498 * If at least \p strlen(\a pattern) bytes were received, the beginning of
499 * the received buffer is compared with \a pattern, ignoring case.
500 * \sa recv_buffer()
501 * \sa strncasecmp(3)
502 */
503 int recv_pattern(int fd, const char *pattern, size_t bufsize)
504 {
505 size_t len = strlen(pattern);
506 char *buf = para_malloc(bufsize + 1);
507 int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
508
509 if (n < len)
510 goto out;
511 if (strncasecmp(buf, pattern, len))
512 goto out;
513 ret = 1;
514 out:
515 free(buf);
516 if (ret < 0)
517 PARA_NOTICE_LOG("did not receive pattern '%s'\n", buf);
518 return ret;
519 }