summaryrefslogtreecommitdiff
path: root/cpp/src/Glacier/StarterI.cpp
blob: 1cff6cf63b1b3baa76f5f4d75512fce4c6495f60 (plain)
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// **********************************************************************
//
// Copyright (c) 2001
// ZeroC, Inc.
// Huntsville, AL, USA
//
// All Rights Reserved
//
// **********************************************************************

#ifdef _WIN32
#   error Sorry, the Glacier Starter is not yet supported on WIN32.
#endif

#include <IceUtil/UUID.h>
#include <IceSSL/RSAKeyPair.h>
#include <Glacier/StarterI.h>
#include <fcntl.h>
#include <shadow.h>

using namespace std;
using namespace Ice;
using namespace Glacier;

using IceSSL::RSAKeyPairPtr;

Glacier::StarterI::StarterI(const CommunicatorPtr& communicator, const PasswordVerifierPrx& verifier) :
    _communicator(communicator),
    _logger(_communicator->getLogger()),
    _properties(_communicator->getProperties()),
    _verifier(verifier)
{
    assert(_verifier);

    _traceLevel = _properties->getPropertyAsInt("Glacier.Starter.Trace");

    // Set up the Certificate Generation context
    string country = _properties->getPropertyWithDefault("Glacier.Starter.Certificate.Country", "US");
    string stateProv = _properties->getPropertyWithDefault("Glacier.Starter.Certificate.StateProvince", "DC");
    string locality = _properties->getPropertyWithDefault("Glacier.Starter.Certificate.Locality", "Washington");
    string org = _properties->getPropertyWithDefault("Glacier.Starter.Certificate.Organization", "Some Company Inc.");
    string orgUnit = _properties->getPropertyWithDefault("Glacier.Starter.Certificate.OranizationalUnit", "Sales");
    string commonName = _properties->getPropertyWithDefault("Glacier.Starter.Certificate.CommonName", "John Doe");

    Int bitStrength = _properties->getPropertyAsIntWithDefault(
	"Glacier.Starter.Certificate.BitStrength", 1024);
    Int secondsValid = _properties->getPropertyAsIntWithDefault(
	"Glacier.Starter.Certificate.SecondsValid", IceSSL::RSACertificateGenContext::daysToSeconds(1));
    Int issuedAdjust = _properties->getPropertyAsIntWithDefault("Glacier.Starter.Certificate.IssuedAdjust", 0);
    
    _certContext.setCountry(country);
    _certContext.setStateProvince(stateProv);
    _certContext.setLocality(locality);
    _certContext.setOrganization(org);
    _certContext.setOrgainizationalUnit(orgUnit);
    _certContext.setCommonName(commonName);
    _certContext.setBitStrength(bitStrength);
    _certContext.setSecondsValid(secondsValid);
    _certContext.setSecondsValid(issuedAdjust);
}

static bool
prefixOK(const string& property)
{
    if(property.find("--Ice.") == 0)
	return false;
    if(property.find("--IceSSL.") == 0)
	return false;
    if(property.find("--Glacier.Router") == 0)
	return false;

    return true;
}

void
Glacier::StarterI::destroy()
{
    //
    // No mutex protection necessary, destroy is only called after all
    // object adapters have shut down.
    //
    _communicator = 0;
    _logger = 0;
    _properties = 0;
}

Glacier::RouterPrx
Glacier::StarterI::startRouter(const string& userId, const string& password, ByteSeq& privateKey, ByteSeq& publicKey,
			       ByteSeq& routerCert, const Current&)
{
    assert(_communicator); // Destroyed?

    if(!_verifier->checkPassword(userId, password))
    {
	throw InvalidPasswordException();
    }

    bool sslConfigured = !_properties->getProperty("IceSSL.Server.Config").empty();

    //
    // routerPrivateKeyBase64 and routerCertificateBase64 are passed to the
    // router as the values for the properties
    //  * IceSSL.Server.Overrides.Server.RSA.PrivateKey
    //  * IceSSL.Server.Overrides.Server.RSA.Certificate
    // respectively.
    //
    // If the router is to act as a client to the Client as well, then
    // these values should also be passed into the router as the properties
    //  * IceSSL.Client.Overrides.RSA.PrivateKey
    //  * IceSSL.Client.Overrides.RSA.Certificate
    // respectively.
    //
    // The value of clientCertificateBase64 should be passed in to the router
    // in the property
    //  * Glacier.Router.AcceptCert
    //
    string routerPrivateKeyBase64;
    string routerCertificateBase64;
    string clientCertificateBase64;
    
    if(sslConfigured)
    {
        //
        // Create a certificate for the client and the router.
        //
        RSAKeyPairPtr clientKeyPair = _certificateGenerator.generate(_certContext);
        RSAKeyPairPtr routerKeyPair = _certificateGenerator.generate(_certContext);

        clientKeyPair->keyToByteSeq(privateKey);
        clientKeyPair->certToByteSeq(publicKey);
        routerKeyPair->certToByteSeq(routerCert);

        routerKeyPair->keyToBase64(routerPrivateKeyBase64);
        routerKeyPair->certToBase64(routerCertificateBase64);
        clientKeyPair->certToBase64(clientCertificateBase64);
    }

    //
    // Start a router.
    //
    string path = _properties->getPropertyWithDefault("Glacier.Starter.RouterPath", "glacierrouter");
    string uuid = IceUtil::generateUUID();
    pid_t pid;
    int fds[2];

    try
    {
	if(pipe(fds) != 0)
	{
	    SyscallException ex(__FILE__, __LINE__);
	    ex.error = getSystemErrno();
	    throw ex;
	}
	pid = fork();
	if(pid == -1)
	{
	    SyscallException ex(__FILE__, __LINE__);
	    ex.error = getSystemErrno();
	    throw ex;
	}
    }
    catch(const LocalException& ex)
    {
	Error out(_logger);
	out << ex;
	ex.ice_throw();
    }

    if(pid == 0) // Child process.
    {
	//
	// Close all filedescriptors, except for standard input,
	// standard output, standard error output, and the write side
	// of the newly created pipe.
	//
	int maxFd = static_cast<int>(sysconf(_SC_OPEN_MAX));
	for(int fd = 3; fd < maxFd; ++fd)
	{
	    if(fd != fds[1])
	    {
		close(fd);
	    }
	}
	
	//
	// Setup arguments to start the router with.
	//
	StringSeq args = _properties->getCommandLineOptions();

	//
	// Filter all arguments that don't start with "--Ice.",
	// "--IceSSL.", or "--Glacier.Router.".
	//
	args.erase(remove_if(args.begin(), args.end(), prefixOK), args.end());

	args.push_back("--Glacier.Router.Identity=" + uuid);

        //
	// TODO: Potential security risk, command line parameters can
	// be seen with `ps'. Keys and certificate should rather be
	// passed through a pipe? (ML will take care of this...)
	//
        if(sslConfigured)
        {
            args.push_back("--IceSSL.Server.Overrides.RSA.PrivateKey=" + routerPrivateKeyBase64);
            args.push_back("--IceSSL.Server.Overrides.RSA.Certificate=" + routerCertificateBase64);
            args.push_back("--IceSSL.Client.Overrides.RSA.PrivateKey=" + routerPrivateKeyBase64);
            args.push_back("--IceSSL.Client.Overrides.RSA.Certificate=" + routerCertificateBase64);
            args.push_back("--Glacier.Router.AcceptCert=" + clientCertificateBase64);
        }

	args.push_back("--Glacier.Router.UserId=" + userId);
	
	int addUserMode = _properties->getPropertyAsIntWithDefault("Glacier.Starter.AddUserToAllowCategories", 0);
	if(addUserMode == 1)
	{
	    // Add user id to allowed categories.
	    args.push_back("--Glacier.Router.AllowCategories=" +
			   _properties->getProperty("Glacier.Router.AllowCategories") + " " + userId);
	}
	else if(addUserMode == 2)
	{
	    // Add user id with prepended underscore to allowed categories.
	    args.push_back("--Glacier.Router.AllowCategories=" +
			   _properties->getProperty("Glacier.Router.AllowCategories") + " _" + userId);
	}

	ostringstream s;
	s << "--Glacier.Router.PrintProxyOnFd=" << fds[1];
	args.push_back(s.str());
	string overwrite = _properties->getProperty("Glacier.Starter.PropertiesOverwrite");
	if(!overwrite.empty())
	{
	    string::size_type end = 0;
	    while(end != string::npos)
	    {
		const string delim = " \t\r\n";
		
		string::size_type beg = overwrite.find_first_not_of(delim, end);
		if(beg == string::npos)
		{
		    break;
		}
		
		end = overwrite.find_first_of(delim, beg);
		string arg;
		if(end == string::npos)
		{
		    arg = overwrite.substr(beg);
		}
		else
		{
		    arg = overwrite.substr(beg, end - beg);
		}
		if(arg.find("--") != 0)
		{
		    arg = "--" + arg;
		}
		args.push_back(arg);
	    }
	}

/*
        StringSeq::iterator seqElem = args.begin();
        while(seqElem != args.end())
        {
            cerr << *seqElem << endl;
            seqElem++;
        }
*/
	
	//
	// Convert to standard argc/argv.
	//
	int argc = args.size() + 1;
	char** argv = static_cast<char**>(malloc((argc + 1) * sizeof(char*)));
	StringSeq::iterator p;
	int i;
	for(p = args.begin(), i = 1; p != args.end(); ++p, ++i)
	{
	    assert(i < argc);
	    argv[i] = strdup(p->c_str());
	}
	assert(i == argc);
	argv[0] = strdup(path.c_str());
	argv[argc] = 0;

	//
	// Try to start the router.
	//
	if(execvp(argv[0], argv) == -1)
	{
	    //
	    // Send any errors to the parent process, using the write
	    // end of the pipe.
	    //
	    string msg = "can't execute `" + path + "': " + strerror(errno);
	    write(fds[1], msg.c_str(), msg.length());
	    close(fds[1]);
	    exit(EXIT_FAILURE);
	}
    }
    else // Parent process.
    {
	try
	{
	    //
	    // Close the write side of the newly created pipe.
	    //
	    close(fds[1]);
	    
	    //
	    // Wait until data can be read from the newly started router,
	    // with timeout.
	    //
	    int flags = fcntl(fds[0], F_GETFL);
	    flags |= O_NONBLOCK;
	    if(fcntl(fds[0], F_SETFL, flags) == -1)
	    {
		SyscallException ex(__FILE__, __LINE__);
		ex.error = getSystemErrno();
		throw ex;
	    }
	    
	repeatSelect:
	    fd_set fdSet;
	    FD_ZERO(&fdSet);
	    FD_SET(fds[0], &fdSet);
	    struct timeval tv;
	    tv.tv_sec = _properties->getPropertyAsIntWithDefault("Glacier.Starter.StartupTimeout", 10);
	    if(tv.tv_sec < 1)
	    {
		tv.tv_sec = 1; // One second is minimum.
	    }
	    tv.tv_usec = 0;
	    int ret = ::select(fds[0] + 1, &fdSet, 0, 0, &tv);
	    
	    if(ret == -1)
	    {
		if(errno == EINTR)
		{
		    goto repeatSelect;
		}
		
		SyscallException ex(__FILE__, __LINE__);
		ex.error = getSystemErrno();
		throw ex;
	    }
	    
	    if(ret == 0) // Timeout.
	    {
		CannotStartRouterException ex;
		ex.reason = "timeout while starting `" + path + "'";
		throw ex;
	    }

	    assert(FD_ISSET(fds[0], &fdSet));
	
	    //
	    // Read the response.
	    //
	    char buf[4*1024];
	    ssize_t sz = read(fds[0], buf, sizeof(buf)/sizeof(char) - 1);
	    if(sz == -1)
	    {
		SyscallException ex(__FILE__, __LINE__);
		ex.error = getSystemErrno();
		throw ex;
	    }

	    if(sz == 0) // EOF?
	    {
		CannotStartRouterException ex;
		ex.reason = "got EOF from `" + path + "'";
		throw ex;
	    }

	    buf[sz] = '\0'; // Terminate the string we got back.

	    if(strncmp(buf, uuid.c_str(), uuid.length()) == 0)
	    {
		//
		// We got the stringified router proxy.
		//
		RouterPrx router = RouterPrx::uncheckedCast(_communicator->stringToProxy(buf));

		if(_traceLevel >= 2)
		{
		    Trace out(_logger, "Glacier");
		    out << "started new router:\n" << _communicator->proxyToString(router);
		}

		return router;
	    }
	    else
	    {
		//
		// We got something else.
		//
		CannotStartRouterException ex;
		ex.reason = buf;
		throw ex;
	    }
	}
	catch(const CannotStartRouterException& ex)
	{
	    if(_traceLevel >= 1)
	    {
		Trace out(_logger, "Glacier");
		out << "router starter exception:\n" << ex << ":\n" << ex.reason;
	    }
	    
	    ex.ice_throw();
	}
	catch(const Exception& ex)
	{
	    Error out(_logger);
	    out << ex;
	    ex.ice_throw();
	}
    }

    assert(false); // Should never be reached.
    return 0; // To keep the compiler from complaining.
}

Glacier::CryptPasswordVerifierI::CryptPasswordVerifierI(const map<string, string>& passwords) :
    _passwords(passwords)
{
}

bool
Glacier::CryptPasswordVerifierI::checkPassword(const string& userId, const string& password, const Current&) const
{
    map<string, string>::const_iterator p = _passwords.find(userId);

    if(p == _passwords.end())
    {
	return false;
    }

    if(p->second.size() != 13) // Crypt passwords are 13 characters long.
    {
	return false;
    }

    {
	IceUtil::Lock<IceUtil::Mutex> sync(*this); // Need a lock as crypt() is not reentrant.
	
	return p->second == crypt(password.c_str(), p->second.substr(0, 2).c_str());
    }
}

void
Glacier::CryptPasswordVerifierI::destroy(const Current&)
{
    // Nothing to do.
}