/
Main.cpp
292 lines (261 loc) · 9.74 KB
/
Main.cpp
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
/*
* Phusion Passenger - http://www.modrails.com/
* Copyright (c) 2010 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <oxt/system_calls.hpp>
#include <oxt/backtrace.hpp>
#include <oxt/thread.hpp>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <signal.h>
#include <agents/Base.h>
#include <agents/LoggingAgent/LoggingServer.h>
#include <AccountsDatabase.h>
#include <Account.h>
#include <ServerInstanceDir.h>
#include <Exceptions.h>
#include <Utils.h>
#include <Utils/IOUtils.h>
#include <Utils/MessageIO.h>
#include <Utils/Base64.h>
#include <Utils/VariantMap.h>
using namespace oxt;
using namespace Passenger;
static struct ev_loop *eventLoop;
static LoggingServer *loggingServer;
static int exitCode = 0;
static struct ev_loop *
createEventLoop() {
struct ev_loop *loop;
// libev doesn't like choosing epoll and kqueue because the author thinks they're broken,
// so let's try to force it.
loop = ev_default_loop(EVBACKEND_EPOLL);
if (loop == NULL) {
loop = ev_default_loop(EVBACKEND_KQUEUE);
}
if (loop == NULL) {
loop = ev_default_loop(0);
}
if (loop == NULL) {
throw RuntimeException("Cannot create an event loop");
} else {
return loop;
}
}
static void
lowerPrivilege(const string &username, const struct passwd *user, const struct group *group) {
int e;
if (initgroups(username.c_str(), group->gr_gid) != 0) {
e = errno;
P_WARN("WARNING: Unable to set supplementary groups for " <<
"PassengerLoggingAgent: " << strerror(e) << " (" << e << ")");
}
if (setgid(group->gr_gid) != 0) {
e = errno;
P_WARN("WARNING: Unable to lower PassengerLoggingAgent's "
"privilege to that of user '" << username <<
"': cannot set group ID to " << group->gr_gid <<
": " << strerror(e) <<
" (" << e << ")");
}
if (setuid(user->pw_uid) != 0) {
e = errno;
P_WARN("WARNING: Unable to lower PassengerLoggingAgent's "
"privilege to that of user '" << username <<
"': cannot set user ID: " << strerror(e) <<
" (" << e << ")");
}
}
void
feedbackFdBecameReadable(ev::io &watcher, int revents) {
/* This event indicates that the watchdog has been killed.
* In this case we'll kill all descendant
* processes and exit. There's no point in keeping this agent
* running because we can't detect when the web server exits,
* and because this agent doesn't own the server instance
* directory. As soon as passenger-status is run, the server
* instance directory will be cleaned up, making this agent's
* services inaccessible.
*/
syscalls::killpg(getpgrp(), SIGKILL);
_exit(2); // In case killpg() fails.
}
void
caughtExitSignal(ev::sig &watcher, int revents) {
P_DEBUG("Caught signal, exiting...");
ev_break(eventLoop, EVBREAK_ONE);
/* We only consider the "exit" command to be a graceful way to shut down
* the logging agent, so upon receiving an exit signal we want to return
* a non-zero exit code. This is because we want the watchdog to restart
* the logging agent when it's killed by SIGTERM.
*/
exitCode = 1;
}
void
printInfo(ev::sig &watcher, int revents) {
loggingServer->dump(cout);
cout.flush();
}
static string
myself() {
struct passwd *entry = getpwuid(geteuid());
if (entry != NULL) {
return entry->pw_name;
} else {
throw NonExistentUserException(string("The current user, UID ") +
toString(geteuid()) + ", doesn't have a corresponding " +
"entry in the system's user database. Please fix your " +
"system's user database first.");
}
}
int
main(int argc, char *argv[]) {
VariantMap options = initializeAgent(argc, argv, "PassengerLoggingAgent");
string socketAddress = options.get("logging_agent_address");
string loggingDir = options.get("analytics_log_dir");
string password = options.get("logging_agent_password");
string username = options.get("analytics_log_user",
false, myself());
string groupname = options.get("analytics_log_group", false);
string permissions = options.get("analytics_log_permissions",
false, DEFAULT_ANALYTICS_LOG_PERMISSIONS);
string unionStationGatewayAddress = options.get("union_station_gateway_address",
false, DEFAULT_UNION_STATION_GATEWAY_ADDRESS);
int unionStationGatewayPort = options.getInt("union_station_gateway_port",
false, DEFAULT_UNION_STATION_GATEWAY_PORT);
string unionStationGatewayCert = options.get("union_station_gateway_cert", false);
string unionStationProxyAddress = options.get("union_station_proxy_address", false);
string unionStationProxyType = options.get("union_station_proxy_type", false);
curl_global_init(CURL_GLOBAL_ALL);
try {
/********** Now begins the real initialization **********/
/* Create all the necessary objects and sockets... */
AccountsDatabasePtr accountsDatabase;
FileDescriptor serverSocketFd;
struct passwd *user;
struct group *group;
int ret;
eventLoop = createEventLoop();
accountsDatabase = ptr(new AccountsDatabase());
serverSocketFd = createServer(socketAddress.c_str());
if (getSocketAddressType(socketAddress) == SAT_UNIX) {
do {
ret = chmod(parseUnixSocketAddress(socketAddress).c_str(),
S_ISVTX |
S_IRUSR | S_IWUSR | S_IXUSR |
S_IRGRP | S_IWGRP | S_IXGRP |
S_IROTH | S_IWOTH | S_IXOTH);
} while (ret == -1 && errno == EINTR);
}
/* Sanity check user accounts. */
user = getpwnam(username.c_str());
if (user == NULL) {
throw NonExistentUserException(string("The configuration option ") +
"'PassengerAnalyticsLogUser' (Apache) or " +
"'passenger_analytics_log_user' (Nginx) was set to '" +
username + "', but this user doesn't exist. Please fix " +
"the configuration option.");
}
if (groupname.empty()) {
group = getgrgid(user->pw_gid);
if (group == NULL) {
throw NonExistentGroupException(string("The configuration option ") +
"'PassengerAnalyticsLogGroup' (Apache) or " +
"'passenger_analytics_log_group' (Nginx) wasn't set, " +
"so PassengerLoggingAgent tried to use the default group " +
"for user '" + username + "' - which is GID #" +
toString(user->pw_gid) + " - as the group for the analytics " +
"log dir, but this GID doesn't exist. " +
"You can solve this problem by explicitly " +
"setting PassengerAnalyticsLogGroup (Apache) or " +
"passenger_analytics_log_group (Nginx) to a group that " +
"does exist. In any case, it looks like your system's user " +
"database is broken; Phusion Passenger can work fine even " +
"with this broken user database, but you should still fix it.");
} else {
groupname = group->gr_name;
}
} else {
group = getgrnam(groupname.c_str());
if (group == NULL) {
throw NonExistentGroupException(string("The configuration option ") +
"'PassengerAnalyticsLogGroup' (Apache) or " +
"'passenger_analytics_log_group' (Nginx) was set to '" +
groupname + "', but this group doesn't exist. Please fix " +
"the configuration option.");
}
}
/* Create the logging directory if necessary. */
if (getFileType(loggingDir) == FT_NONEXISTANT) {
if (geteuid() == 0) {
makeDirTree(loggingDir, permissions, user->pw_uid, group->gr_gid);
} else {
makeDirTree(loggingDir, permissions);
}
}
/* Now's a good time to lower the privilege. */
if (geteuid() == 0) {
lowerPrivilege(username, user, group);
}
/* Now setup the actual logging server. */
accountsDatabase->add("logging", password, false);
LoggingServer server(eventLoop, serverSocketFd,
accountsDatabase, loggingDir,
"u=rwx,g=rx,o=rx", GROUP_NOT_GIVEN,
unionStationGatewayAddress,
unionStationGatewayPort,
unionStationGatewayCert,
unionStationProxyAddress,
unionStationProxyType);
loggingServer = &server;
ev::io feedbackFdWatcher(eventLoop);
ev::sig sigintWatcher(eventLoop);
ev::sig sigtermWatcher(eventLoop);
ev::sig sigquitWatcher(eventLoop);
if (feedbackFdAvailable()) {
feedbackFdWatcher.set<&feedbackFdBecameReadable>();
feedbackFdWatcher.start(FEEDBACK_FD, ev::READ);
writeArrayMessage(FEEDBACK_FD, "initialized", NULL);
}
sigintWatcher.set<&caughtExitSignal>();
sigintWatcher.start(SIGINT);
sigtermWatcher.set<&caughtExitSignal>();
sigtermWatcher.start(SIGTERM);
sigquitWatcher.set<&printInfo>();
sigquitWatcher.start(SIGQUIT);
/********** Initialized! Enter main loop... **********/
P_DEBUG("Logging agent online, listening at " << socketAddress);
ev_run(eventLoop, 0);
P_DEBUG("Logging agent exiting with code " << exitCode << ".");
return exitCode;
} catch (const tracable_exception &e) {
P_ERROR("*** ERROR: " << e.what() << "\n" << e.backtrace());
return 1;
}
}