summaryrefslogtreecommitdiffstats
path: root/daemon/main.cpp
blob: 8878bc25199f47e67dcdd5d8418ca6c2bbd880cf (plain) (blame)
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
#include "Listener.h"
#include <QHostAddress>
#include <QCoreApplication>
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>

int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);
	a.setApplicationName(QLatin1String("AnyLoader"));
	a.setOrganizationName(QLatin1String("AnyClip"));
	a.setOrganizationDomain(QLatin1String("anyclip.com"));
	QString hostAddress("0.0.0.0");
	int port = 8964;
	QString pidFile;
	QString userName;
	int c;
	while ((c = getopt(argc, argv, "a:p:b:u:")) != -1) {
		switch (c) {
		case 'a':
			hostAddress = optarg;
			break;
		case 'p':
			port = QString(optarg).toInt();
			break;
		case 'b':
			pidFile = optarg;
			break;
		case 'u':
			userName = optarg;
			break;
		default:
			std::cerr << "Invalid option '" << c << "'." << std::endl;
			return 1;
		}
	}
	Listener listener;
	if (!listener.start(QHostAddress(hostAddress), port)) {
		std::cerr << "Could not bind." << std::endl;
		return 1;
	}
	if (!pidFile.isEmpty()) {
		pid_t pid, sid;
		pid = fork();
		if (pid < 0)
			_exit(1);
		else if (pid > 0) {
			std::ofstream pidfile;
			pidfile.open(pidFile.toAscii());
			pidfile << QString::number(pid).toStdString() << std::endl;
			pidfile.close();
			_exit(0);
		}
		if (!userName.isEmpty()) {
			struct passwd *pw;
			if (!(pw = getpwnam(userName.toAscii()))) {
				std::cerr << "Couldnt find username." << std::endl;
				_exit(1);
			}
			if (setgid(pw->pw_gid) || setuid(pw->pw_uid)) {
				std::cerr << "Couldn't set gid or uid." << std::endl;
				_exit(1);
			}
		}
		umask(0);
		sid = setsid();
		if (sid < 0)
			_exit(1);
		if ((chdir("/")) < 0)
			_exit(1);
		close(STDIN_FILENO);
		close(STDOUT_FILENO);
		close(STDERR_FILENO);
	}
	return a.exec();
}