File: MessageServerTest.cpp

package info (click to toggle)
ruby-passenger 4.0.53-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 28,668 kB
  • ctags: 70,512
  • sloc: cpp: 264,280; ruby: 25,606; sh: 22,815; ansic: 18,277; python: 767; makefile: 99; perl: 20
file content (386 lines) | stat: -rw-r--r-- 12,108 bytes parent folder | download
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
#include "TestSupport.h"

#include <boost/thread.hpp>
#include <boost/bind.hpp>

#include "MessageServer.h"
#include "MessageClient.h"
#include "Utils.h"
#include <string>
#include <cstring>
#include <unistd.h>
#include <errno.h>

using namespace Passenger;
using namespace boost;
using namespace std;

namespace tut {
	struct MessageServerTest {
		ServerInstanceDirPtr serverInstanceDir;
		ServerInstanceDir::GenerationPtr generation;
		string socketFilename;
		string socketAddress;
		AccountsDatabasePtr accountsDatabase;
		AccountPtr clientAccount;
		boost::shared_ptr<MessageServer> server;
		boost::shared_ptr<oxt::thread> serverThread;
		
		MessageServerTest() {
			createServerInstanceDirAndGeneration(serverInstanceDir, generation);
			socketFilename = generation->getPath() + "/socket";
			socketAddress = "unix:" + socketFilename;
			accountsDatabase = ptr(new AccountsDatabase());
			clientAccount = accountsDatabase->add("test", "12345", false);
			
			server = ptr(new MessageServer(socketFilename, accountsDatabase));
			serverThread  = ptr(new oxt::thread(
				boost::bind(&MessageServer::mainLoop, server.get())
			));
		}
		
		~MessageServerTest() {
			if (serverThread != NULL) {
				serverThread->interrupt_and_join();
			}
			Passenger::setLogLevel(0);
		}
		
		class SlowClient: public MessageClient {
		private:
			unsigned int timeToSendUsername;
			unsigned int timeToSendPassword;
			
		protected:
			virtual void sendUsername(int fd, const StaticString &username, unsigned long long *timeout) {
				if (timeToSendUsername > 0) {
					usleep(timeToSendUsername * 1000);
				}
				writeScalarMessage(fd, username);
			}

			virtual void sendPassword(int fd, const StaticString &userSuppliedPassword, unsigned long long *timeout) {
				if (timeToSendPassword > 0) {
					usleep(timeToSendPassword * 1000);
				}
				writeScalarMessage(fd, userSuppliedPassword);
			}
			
		public:
			SlowClient(unsigned int timeToSendUsername,
			           unsigned int timeToSendPassword)
			         : MessageClient()
			{
				this->timeToSendUsername = timeToSendUsername;
				this->timeToSendPassword = timeToSendPassword;
			}
		};
		
		class CustomClient: public MessageClient {
		public:
			CustomClient *sendText(const string &text) {
				write(text.c_str(), NULL);
				return this;
			}
		};
		
		class LoggingHandler: public MessageServer::Handler {
		public:
			struct SpecificContext: public MessageServer::ClientContext {
				int id;
				
				SpecificContext(int i) {
					id = i;
				}
			};
			
			typedef boost::shared_ptr<SpecificContext> SpecificContextPtr;
			
			boost::mutex mutex;
			volatile int clientsAccepted;
			volatile int clientsDisconnected;
			string receivedData;
			volatile int id;
			volatile int returnValue;
			SpecificContextPtr latestContext;
			
			LoggingHandler() {
				clientsAccepted = 0;
				clientsDisconnected = 0;
				returnValue = true;
			}
			
			virtual MessageServer::ClientContextPtr newClient(MessageServer::CommonClientContext &context) {
				boost::lock_guard<boost::mutex> l(mutex);
				clientsAccepted++;
				return ptr(new SpecificContext(id));
			}
			
			virtual void clientDisconnected(MessageServer::CommonClientContext &context,
			                                MessageServer::ClientContextPtr &handlerSpecificContext)
			{
				boost::lock_guard<boost::mutex> l(mutex);
				clientsDisconnected++;
			}
			
			virtual bool processMessage(MessageServer::CommonClientContext &commonContext,
			                            MessageServer::ClientContextPtr &handlerSpecificContext,
			                            const vector<string> &args)
			{
				boost::lock_guard<boost::mutex> l(mutex);
				latestContext = static_pointer_cast<SpecificContext>(handlerSpecificContext);
				receivedData.append(args[0]);
				return returnValue;
			}
		};
		
		typedef boost::shared_ptr<LoggingHandler> LoggingHandlerPtr;
		
		class ProcessMessageReturnsFalseHandler: public MessageServer::Handler {
		public:
			virtual bool processMessage(MessageServer::CommonClientContext &commonContext,
			                            MessageServer::ClientContextPtr &handlerSpecificContext,
			                            const vector<string> &args)
			{
				return false;
			}
		};
	};

	DEFINE_TEST_GROUP(MessageServerTest);
	
	TEST_METHOD(1) {
		// It rejects the connection if the an invalid username or password was sent.
		accountsDatabase->add("hashed_user", Account::createHash("67890"), true);
		
		try {
			MessageClient().connect(socketAddress, "testt", "12345");
			fail("SecurityException expected when invalid username is given");
		} catch (const SecurityException &) {
			// Pass.
		}
		try {
			MessageClient().connect(socketAddress, "test", "123456");
			fail("SecurityException expected when invalid password is given for an account with plain text password");
		} catch (const SecurityException &) {
			// Pass.
		}
		try {
			MessageClient().connect(socketAddress, "test", "678900");
			fail("SecurityException expected when invalid password is given for an account with hashed password");
		} catch (const SecurityException &) {
			// Pass.
		}
	}
	
	TEST_METHOD(2) {
		// It supports hashed passwords.
		accountsDatabase->add("hashed_user", Account::createHash("67890"), true);
		MessageClient().connect(socketAddress, "hashed_user", "67890"); // Should not throw exception.
	}
	
	TEST_METHOD(3) {
		// It disconnects the client if the client does not supply a username and
		// password within a time limit.
		Passenger::setLogLevel(-1);
		server->setLoginTimeout(30000);
		
		/* These can throw either an IOException or SystemException:
		 * - An IOException is raised when connect() encounters EOF.
		 * - But when connect() fails during the middle of a read()
		 *   or write() (e.g. because the server disconnects before
		 *   connect() is done writing), then SystemException is raised.
		 */
		
		try {
			// This client takes too much time on sending the username.
			SlowClient(50, 0).connect(socketAddress, "test", "12345");
			fail("IOException or SystemException expected (1).");
		} catch (const IOException &e) {
			// Pass.
		} catch (const SystemException &e) {
			// Pass.
		}
		
		try {
			// This client takes too much time on sending the password.
			SlowClient(0, 50).connect(socketAddress, "test", "12345");
			fail("IOException or SystemException expected (2).");
		} catch (const IOException &e) {
			// Pass.
		} catch (const SystemException &e) {
			// Pass.
		}
		
		try {
			// This client is fast enough at sending the username and
			// password individually, but the combined time is too long.
			SlowClient(25, 25).connect(socketAddress, "test", "12345");
			fail("IOException or SystemException expected (3).");
		} catch (const IOException &e) {
			// Pass.
		} catch (const SystemException &e) {
			// Pass.
		}
	}
	
	TEST_METHOD(4) {
		// It disconnects the client if it provides a username that's too large.
		char username[1024];
		memset(username, 'x', sizeof(username));
		username[sizeof(username) - 1] = '\0';
		try {
			MessageClient().connect(socketAddress, username, "1234");
			fail("SecurityException expected");
		} catch (const SecurityException &e) {
			// Pass.
		}
	}
	
	TEST_METHOD(5) {
		// It disconnects the client if it provides a password that's too large.
		char password[1024];
		memset(password, 'x', sizeof(password));
		password[sizeof(password) - 1] = '\0';
		try {
			MessageClient().connect(socketAddress, "test", password);
			fail("SecurityException expected");
		} catch (const SecurityException &e) {
			// Pass.
		}
	}
	
	TEST_METHOD(6) {
		// It notifies all handlers when a new client has connected.
		LoggingHandlerPtr handler1(new LoggingHandler());
		LoggingHandlerPtr handler2(new LoggingHandler());
		server->addHandler(handler1);
		server->addHandler(handler2);
		MessageClient().connect(socketAddress, "test", "12345");
		MessageClient().connect(socketAddress, "test", "12345");
		
		usleep(10000); // Give the threads some time to do work.
		ensure_equals(handler1->clientsAccepted, 2);
		ensure_equals(handler2->clientsAccepted, 2);
	}
	
	TEST_METHOD(7) {
		// It notifies all handlers when a message is sent, but stops
		// at the first handler that returns true.
		LoggingHandlerPtr handler1(new LoggingHandler());
		LoggingHandlerPtr handler2(new LoggingHandler());
		LoggingHandlerPtr handler3(new LoggingHandler());
		server->addHandler(handler1);
		server->addHandler(handler2);
		server->addHandler(handler3);
		handler1->returnValue = false;
		
		CustomClient c1, c2;
		c1.connect(socketAddress, "test", "12345");
		c1.sendText("hello");
		c1.sendText(" ");
		usleep(10000); // Give the thread some time to do work.
		
		c2.connect(socketAddress, "test", "12345");
		c2.sendText("world");
		usleep(10000); // Give the thread some time to do work.
		
		ensure_equals("(1)", handler1->receivedData, "hello world");
		ensure_equals("(2)", handler2->receivedData, "hello world");
		ensure_equals("(3)", handler3->receivedData, "");
	}
	
	TEST_METHOD(8) {
		// It does not close the connection if some, but not all of the handlers'
		// processMessage() methods return false.
		MessageServer::HandlerPtr handler1(new LoggingHandler());
		MessageServer::HandlerPtr handler2(new ProcessMessageReturnsFalseHandler());
		server->addHandler(handler1);
		server->addHandler(handler2);
		
		CustomClient c;
		c.connect(socketAddress, "test", "12345");
		c.sendText("hi");
		usleep(10000); // Give the thread some time to do work.
		
		c.sendText("hi"); // Connection should still be valid.
	}
	
	TEST_METHOD(9) {
		// It closes the connection if all of the handlers'
		// processMessage() methods return false.
		MessageServer::HandlerPtr handler1(new ProcessMessageReturnsFalseHandler());
		MessageServer::HandlerPtr handler2(new ProcessMessageReturnsFalseHandler());
		server->addHandler(handler1);
		server->addHandler(handler2);
		
		CustomClient c;
		c.connect(socketAddress, "test", "12345");
		c.sendText("hi");
		usleep(10000); // Give the thread some time to do work.
		
		try {
			c.sendText("hi");
			fail("SystemException expected.");
		} catch (const SystemException &e) {
			ensure_equals(e.code(), EPIPE);
		}
	}
	
	TEST_METHOD(10) {
		// The specific context as returned by the handler's newClient()
		// method is passed to processMessage().
		LoggingHandlerPtr handler1(new LoggingHandler());
		LoggingHandlerPtr handler2(new LoggingHandler());
		LoggingHandlerPtr handler3(new LoggingHandler());
		server->addHandler(handler1);
		server->addHandler(handler2);
		server->addHandler(handler3);
		handler1->returnValue = false;
		handler2->returnValue = false;
		
		CustomClient c1, c2;
		
		handler1->id = 100;
		handler2->id = 101;
		c1.connect(socketAddress, "test", "12345");
		c1.sendText("hi");
		usleep(10000); // Give the thread some time to do work.
		ensure_equals(handler1->latestContext->id, 100);
		ensure_equals(handler2->latestContext->id, 101);
		
		handler1->id = 200;
		handler2->id = 201;
		c2.connect(socketAddress, "test", "12345");
		c2.sendText("hi");
		usleep(10000); // Give the thread some time to do work.
		ensure_equals(handler1->latestContext->id, 200);
		ensure_equals(handler2->latestContext->id, 201);
		
		c1.sendText("hi");
		usleep(10000); // Give the thread some time to do work.
		ensure_equals(handler1->latestContext->id, 100);
		ensure_equals(handler2->latestContext->id, 101);
	}
	
	TEST_METHOD(11) {
		// It notifies all handlers when a client is disconnected.
		LoggingHandlerPtr handler1(new LoggingHandler());
		LoggingHandlerPtr handler2(new LoggingHandler());
		server->addHandler(handler1);
		server->addHandler(handler2);
		{
			{
				MessageClient().connect(socketAddress, "test", "12345");
			}
			usleep(10000); // Give the threads some time to do work.
			ensure_equals(handler1->clientsDisconnected, 1);
			ensure_equals(handler2->clientsDisconnected, 1);
			
			MessageClient().connect(socketAddress, "test", "12345");
		}
		usleep(10000); // Give the threads some time to do work.
		ensure_equals(handler1->clientsDisconnected, 2);
		ensure_equals(handler2->clientsDisconnected, 2);
	}
}