xref: /haiku/src/servers/net/Services.cpp (revision 58481f0f6ef1a61ba07283f012cafbc2ed874ead)
1 /*
2  * Copyright 2006-2007, Haiku, Inc. All Rights Reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Axel Dörfler, axeld@pinc-software.de
7  */
8 
9 
10 #include "Services.h"
11 #include "NetServer.h"
12 #include "Settings.h"
13 
14 #include <Autolock.h>
15 
16 #include <errno.h>
17 #include <netdb.h>
18 #include <netinet/in.h>
19 #include <new>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/ioctl.h>
23 #include <sys/socket.h>
24 #include <vector>
25 
26 using namespace std;
27 
28 struct service_address {
29 	struct service *owner;
30 	int		socket;
31 	int		family;
32 	int		type;
33 	int		protocol;
34 	sockaddr address;
35 
36 	bool operator==(const struct service_address& other) const;
37 };
38 
39 typedef vector<service_address> AddressList;
40 
41 struct service {
42 	std::string	name;
43 	std::string	launch;
44 	uid_t		user;
45 	gid_t		group;
46 	AddressList	addresses;
47 	uint32		update;
48 
49 	~service();
50 	bool operator!=(const struct service& other) const;
51 	bool operator==(const struct service& other) const;
52 };
53 
54 
55 int
56 parse_type(const char* string)
57 {
58 	if (!strcasecmp(string, "stream"))
59 		return SOCK_STREAM;
60 
61 	return SOCK_DGRAM;
62 }
63 
64 
65 int
66 parse_protocol(const char* string)
67 {
68 	struct protoent* proto = getprotobyname(string);
69 	if (proto == NULL)
70 		return IPPROTO_TCP;
71 
72 	return proto->p_proto;
73 }
74 
75 
76 int
77 type_for_protocol(int protocol)
78 {
79 	// default determined by protocol
80 	switch (protocol) {
81 		case IPPROTO_TCP:
82 			return SOCK_STREAM;
83 
84 		case IPPROTO_UDP:
85 		default:
86 			return SOCK_DGRAM;
87 	}
88 }
89 
90 
91 //	#pragma mark -
92 
93 
94 bool
95 service_address::operator==(const struct service_address& other) const
96 {
97 	return family == other.family
98 		&& type == other.type
99 		&& protocol == other.protocol
100 		&& address.sa_len == other.address.sa_len
101 		&& !memcmp(&address, &other.address, address.sa_len);
102 }
103 
104 
105 //	#pragma mark -
106 
107 
108 service::~service()
109 {
110 	// close all open sockets
111 	AddressList::const_iterator iterator = addresses.begin();
112 	for (; iterator != addresses.end(); iterator++) {
113 		const service_address& address = *iterator;
114 
115 		close(address.socket);
116 	}
117 }
118 
119 
120 bool
121 service::operator!=(const struct service& other) const
122 {
123 	return !(*this == other);
124 }
125 
126 
127 bool
128 service::operator==(const struct service& other) const
129 {
130 	if (name != other.name
131 		|| launch != other.launch
132 		|| addresses.size() != other.addresses.size())
133 		return false;
134 
135 	// compare addresses
136 
137 	AddressList::const_iterator iterator = addresses.begin();
138 	for (; iterator != addresses.end(); iterator++) {
139 		const service_address& address = *iterator;
140 
141 		// find address in other addresses
142 
143 		AddressList::const_iterator otherIterator = other.addresses.begin();
144 		for (; otherIterator != other.addresses.end(); otherIterator++) {
145 			if (address == *otherIterator)
146 				break;
147 		}
148 
149 		if (otherIterator == other.addresses.end())
150 			return false;
151 	}
152 
153 	return true;
154 }
155 
156 
157 //	#pragma mark -
158 
159 
160 Services::Services(const BMessage& services)
161 	:
162 	fListener(-1),
163 	fUpdate(0),
164 	fMaxSocket(0)
165 {
166 	// setup pipe to communicate with the listener thread - as the listener
167 	// blocks on select(), we need a mechanism to interrupt it
168 	if (pipe(&fReadPipe) < 0) {
169 		fReadPipe = -1;
170 		return;
171 	}
172 
173 	fcntl(fReadPipe, F_SETFD, FD_CLOEXEC);
174 	fcntl(fWritePipe, F_SETFD, FD_CLOEXEC);
175 
176 	FD_ZERO(&fSet);
177 	FD_SET(fReadPipe, &fSet);
178 
179 	fMinSocket = fWritePipe + 1;
180 	fMaxSocket = fWritePipe + 1;
181 
182 	_Update(services);
183 
184 	fListener = spawn_thread(_Listener, "services listener", B_NORMAL_PRIORITY, this);
185 	if (fListener >= B_OK)
186 		resume_thread(fListener);
187 }
188 
189 
190 Services::~Services()
191 {
192 	wait_for_thread(fListener, NULL);
193 
194 	close(fReadPipe);
195 	close(fWritePipe);
196 
197 	// stop all services
198 
199 	while (!fNameMap.empty()) {
200 		_StopService(*fNameMap.begin()->second);
201 	}
202 }
203 
204 
205 status_t
206 Services::InitCheck() const
207 {
208 	return fListener >= B_OK ? B_OK : fListener;
209 }
210 
211 
212 void
213 Services::MessageReceived(BMessage* message)
214 {
215 	switch (message->what) {
216 		case kMsgUpdateServices:
217 			_Update(*message);
218 			break;
219 
220 		default:
221 			BHandler::MessageReceived(message);
222 	}
223 }
224 
225 
226 void
227 Services::_NotifyListener(bool quit)
228 {
229 	write(fWritePipe, quit ? "q" : "u", 1);
230 }
231 
232 
233 void
234 Services::_UpdateMinMaxSocket(int socket)
235 {
236 	if (socket >= fMaxSocket)
237 		fMaxSocket = socket + 1;
238 	if (socket < fMinSocket)
239 		fMinSocket = socket;
240 }
241 
242 
243 status_t
244 Services::_StartService(struct service& service)
245 {
246 	// create socket
247 
248 	bool failed = false;
249 	AddressList::iterator iterator = service.addresses.begin();
250 	for (; iterator != service.addresses.end(); iterator++) {
251 		service_address& address = *iterator;
252 
253 		address.socket = socket(address.family, address.type, address.protocol);
254 		if (address.socket < 0
255 			|| bind(address.socket, &address.address, address.address.sa_len) < 0
256 			|| fcntl(address.socket, F_SETFD, FD_CLOEXEC) < 0) {
257 			failed = true;
258 			break;
259 		}
260 
261 		if (address.type == SOCK_STREAM && listen(address.socket, 50) < 0) {
262 			failed = true;
263 			break;
264 		}
265 	}
266 
267 	if (failed) {
268 		// open sockets will be closed when the service is deleted
269 		return errno;
270 	}
271 
272 	// add service to maps and activate it
273 
274 	fNameMap[service.name] = &service;
275 	service.update = fUpdate;
276 
277 	iterator = service.addresses.begin();
278 	for (; iterator != service.addresses.end(); iterator++) {
279 		service_address& address = *iterator;
280 
281 		fSocketMap[address.socket] = &address;
282 		_UpdateMinMaxSocket(address.socket);
283 		FD_SET(address.socket, &fSet);
284 	}
285 
286 	_NotifyListener();
287 	printf("Starting service '%s'\n", service.name.c_str());
288 	return B_OK;
289 }
290 
291 
292 status_t
293 Services::_StopService(struct service& service)
294 {
295 	// remove service from maps
296 	{
297 		ServiceNameMap::iterator iterator = fNameMap.find(service.name);
298 		if (iterator != fNameMap.end())
299 			fNameMap.erase(iterator);
300 	}
301 	{
302 		AddressList::const_iterator iterator = service.addresses.begin();
303 		for (; iterator != service.addresses.end(); iterator++) {
304 			const service_address& address = *iterator;
305 
306 			ServiceSocketMap::iterator socketIterator
307 				= fSocketMap.find(address.socket);
308 			if (socketIterator != fSocketMap.end())
309 				fSocketMap.erase(socketIterator);
310 
311 			close(address.socket);
312 			FD_CLR(address.socket, &fSet);
313 		}
314 	}
315 
316 	delete &service;
317 	return B_OK;
318 }
319 
320 
321 status_t
322 Services::_ToService(const BMessage& message, struct service*& service)
323 {
324 	// get mandatory fields
325 	const char* name;
326 	const char* launch;
327 	if (message.FindString("name", &name) != B_OK
328 		|| message.FindString("launch", &launch) != B_OK)
329 		return B_BAD_VALUE;
330 
331 	service = new (std::nothrow) ::service;
332 	if (service == NULL)
333 		return B_NO_MEMORY;
334 
335 	service->name = name;
336 	service->launch = launch;
337 
338 	// TODO: user/group is currently ignored!
339 
340 	// Default family/port/protocol/type for all addresses
341 
342 	// we default to inet/tcp/port-from-service-name if nothing is specified
343 	const char* string;
344 	int32 serviceFamilyIndex;
345 	int32 serviceFamily = -1;
346 	if (message.FindString("family", &string) != B_OK)
347 		string = "inet";
348 
349 	if (get_family_index(string, serviceFamilyIndex))
350 		serviceFamily = family_at_index(serviceFamilyIndex);
351 
352 	int32 serviceProtocol;
353 	if (message.FindString("protocol", &string) == B_OK)
354 		serviceProtocol = parse_protocol(string);
355 	else {
356 		string = "tcp";
357 			// we set 'string' here for an eventual call to getservbyname() below
358 		serviceProtocol = IPPROTO_TCP;
359 	}
360 
361 	int32 servicePort;
362 	if (message.FindInt32("port", &servicePort) != B_OK) {
363 		struct servent* servent = getservbyname(name, string);
364 		if (servent != NULL)
365 			servicePort = servent->s_port;
366 		else
367 			servicePort = -1;
368 	}
369 
370 	int32 serviceType = -1;
371 	if (message.FindString("type", &string) == B_OK) {
372 		serviceType = parse_type(string);
373 	} else {
374 		serviceType = type_for_protocol(serviceProtocol);
375 	}
376 
377 	BMessage address;
378 	int32 i = 0;
379 	for (; message.FindMessage("address", i, &address) == B_OK; i++) {
380 		// TODO: dump problems in the settings to syslog
381 		service_address serviceAddress;
382 		if (address.FindString("family", &string) != B_OK)
383 			continue;
384 
385 		int32 familyIndex;
386 		if (!get_family_index(string, familyIndex))
387 			continue;
388 
389 		serviceAddress.family = family_at_index(familyIndex);
390 
391 		if (address.FindString("protocol", &string) == B_OK)
392 			serviceAddress.protocol = parse_protocol(string);
393 		else
394 			serviceAddress.protocol = serviceProtocol;
395 
396 		if (message.FindString("type", &string) == B_OK)
397 			serviceAddress.type = parse_type(string);
398 		else if (serviceAddress.protocol != serviceProtocol)
399 			serviceAddress.type = type_for_protocol(serviceAddress.protocol);
400 		else
401 			serviceAddress.type = serviceType;
402 
403 		if (address.FindString("address", &string) == B_OK) {
404 			if (!parse_address(familyIndex, string, serviceAddress.address))
405 				continue;
406 		} else
407 			set_any_address(familyIndex, serviceAddress.address);
408 
409 		int32 port;
410 		if (address.FindInt32("port", &port) != B_OK)
411 			port = servicePort;
412 
413 		set_port(familyIndex, serviceAddress.address, port);
414 		serviceAddress.socket = -1;
415 
416 		serviceAddress.owner = service;
417 		service->addresses.push_back(serviceAddress);
418 	}
419 
420 	if (i == 0 && (serviceFamily < 0 || servicePort < 0)) {
421 		// no address specified
422 		delete service;
423 		return B_BAD_VALUE;
424 	}
425 
426 	if (i == 0) {
427 		// no address specified, but family/port were given; add empty address
428 		service_address serviceAddress;
429 		serviceAddress.family = serviceFamily;
430 		serviceAddress.type = serviceType;
431 		serviceAddress.protocol = serviceProtocol;
432 
433 		set_any_address(serviceFamilyIndex, serviceAddress.address);
434 		set_port(serviceFamilyIndex, serviceAddress.address, servicePort);
435 		serviceAddress.socket = -1;
436 
437 		serviceAddress.owner = service;
438 		service->addresses.push_back(serviceAddress);
439 	}
440 
441 	return B_OK;
442 }
443 
444 
445 void
446 Services::_Update(const BMessage& services)
447 {
448 	BAutolock locker(fLock);
449 	fUpdate++;
450 
451 	BMessage message;
452 	for (int32 index = 0; services.FindMessage("service", index,
453 			&message) == B_OK; index++) {
454 		const char* name;
455 		if (message.FindString("name", &name) != B_OK)
456 			continue;
457 
458 		struct service* service;
459 		if (_ToService(message, service) != B_OK)
460 			continue;
461 
462 		ServiceNameMap::iterator iterator = fNameMap.find(name);
463 		if (iterator == fNameMap.end()) {
464 			// this service does not exist yet, start it
465 			_StartService(*service);
466 		} else {
467 			// this service does already exist - check for any changes
468 
469 			if (*service != *iterator->second) {
470 				_StopService(*iterator->second);
471 				_StartService(*service);
472 			} else
473 				service->update = fUpdate;
474 		}
475 	}
476 
477 	// stop all services that are not part of the update message
478 
479 	ServiceNameMap::iterator iterator = fNameMap.begin();
480 	while (iterator != fNameMap.end()) {
481 		struct service* service = iterator->second;
482 		iterator++;
483 
484 		if (service->update != fUpdate) {
485 			// this service has to be removed
486 			_StopService(*service);
487 		}
488 	}
489 }
490 
491 
492 status_t
493 Services::_LaunchService(struct service& service, int socket)
494 {
495 	printf("LAUNCH: %s\n", service.launch.c_str());
496 
497 	if (fcntl(socket, F_SETFD, 0) < 0) {
498 		// could not clear FD_CLOEXEC on socket
499 		return errno;
500 	}
501 
502 	pid_t child = fork();
503 	if (child == 0) {
504 		setsid();
505 			// make sure we're in our own session, and don't accidently quit
506 			// the net_server
507 
508 		// We're the child, replace standard input/output
509 		dup2(socket, STDIN_FILENO);
510 		dup2(socket, STDOUT_FILENO);
511 		dup2(socket, STDERR_FILENO);
512 		close(socket);
513 
514 		// build argument array
515 
516 		const char** args = (const char**)malloc(2 * sizeof(void *));
517 		if (args == NULL)
518 			exit(1);
519 
520 		args[0] = service.launch.c_str();
521 		args[1] = NULL;
522 		if (execv(service.launch.c_str(), (char* const*)args) < 0)
523 			exit(1);
524 
525 		// we'll never trespass here
526 	} else {
527 		// the server does not need the socket anymore
528 		close(socket);
529 	}
530 
531 	// TODO: make sure child started successfully...
532 	return B_OK;
533 }
534 
535 
536 status_t
537 Services::_Listener()
538 {
539 	while (true) {
540 		fLock.Lock();
541 		fd_set set = fSet;
542 		fLock.Unlock();
543 
544 		if (select(fMaxSocket, &set, NULL, NULL, NULL) < 0) {
545 			// sleep a bit before trying again
546 			snooze(1000000LL);
547 		}
548 
549 		if (FD_ISSET(fReadPipe, &set)) {
550 			char command;
551 			if (read(fReadPipe, &command, 1) == 1 && command == 'q')
552 				break;
553 		}
554 
555 		BAutolock locker(fLock);
556 
557 		for (int i = fMinSocket; i < fMaxSocket; i++) {
558 			if (!FD_ISSET(i, &set))
559 				continue;
560 
561 			ServiceSocketMap::iterator iterator = fSocketMap.find(i);
562 			if (iterator == fSocketMap.end())
563 				continue;
564 
565 			struct service_address& address = *iterator->second;
566 			int socket;
567 
568 			if (address.type == SOCK_STREAM) {
569 				// accept incoming connection
570 				int value = 1;
571 				ioctl(i, FIONBIO, &value);
572 					// make sure we don't wait for the connection
573 
574 				socket = accept(address.socket, NULL, NULL);
575 
576 				value = 0;
577 				ioctl(i, FIONBIO, &value);
578 
579 				if (socket < 0)
580 					continue;
581 			} else
582 				socket = address.socket;
583 
584 			// launch this service's handler
585 
586 			_LaunchService(*address.owner, socket);
587 		}
588 	}
589 	return B_OK;
590 }
591 
592 
593 /*static*/ status_t
594 Services::_Listener(void* _self)
595 {
596 	Services* self = (Services*)_self;
597 	return self->_Listener();
598 }
599