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