1 /*
2  * This application is Copyright 2012 Red Hat, Inc.
3  *	Doug Ledford <dledford@redhat.com>
4  *
5  * mq_open_tests is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, version 3.
8  *
9  * mq_open_tests is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * For the full text of the license, see <http://www.gnu.org/licenses/>.
15  *
16  * mq_open_tests.c
17  *   Tests the various situations that should either succeed or fail to
18  *   open a posix message queue and then reports whether or not they
19  *   did as they were supposed to.
20  *
21  */
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <string.h>
27 #include <limits.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/time.h>
31 #include <sys/resource.h>
32 #include <sys/stat.h>
33 #include <mqueue.h>
34 
35 static char *usage =
36 "Usage:\n"
37 "  %s path\n"
38 "\n"
39 "	path	Path name of the message queue to create\n"
40 "\n"
41 "	Note: this program must be run as root in order to enable all tests\n"
42 "\n";
43 
44 char *DEF_MSGS = "/proc/sys/fs/mqueue/msg_default";
45 char *DEF_MSGSIZE = "/proc/sys/fs/mqueue/msgsize_default";
46 char *MAX_MSGS = "/proc/sys/fs/mqueue/msg_max";
47 char *MAX_MSGSIZE = "/proc/sys/fs/mqueue/msgsize_max";
48 
49 int default_settings;
50 struct rlimit saved_limits, cur_limits;
51 int saved_def_msgs, saved_def_msgsize, saved_max_msgs, saved_max_msgsize;
52 int cur_def_msgs, cur_def_msgsize, cur_max_msgs, cur_max_msgsize;
53 FILE *def_msgs, *def_msgsize, *max_msgs, *max_msgsize;
54 char *queue_path;
55 mqd_t queue = -1;
56 
57 static inline void __set(FILE *stream, int value, char *err_msg);
58 void shutdown(int exit_val, char *err_cause, int line_no);
59 static inline int get(FILE *stream);
60 static inline void set(FILE *stream, int value);
61 static inline void getr(int type, struct rlimit *rlim);
62 static inline void setr(int type, struct rlimit *rlim);
63 void validate_current_settings();
64 static inline void test_queue(struct mq_attr *attr, struct mq_attr *result);
65 static inline int test_queue_fail(struct mq_attr *attr, struct mq_attr *result);
66 
67 static inline void __set(FILE *stream, int value, char *err_msg)
68 {
69 	rewind(stream);
70 	if (fprintf(stream, "%d", value) < 0)
71 		perror(err_msg);
72 }
73 
74 
75 void shutdown(int exit_val, char *err_cause, int line_no)
76 {
77 	static int in_shutdown = 0;
78 
79 	/* In case we get called recursively by a set() call below */
80 	if (in_shutdown++)
81 		return;
82 
83 	if (seteuid(0) == -1)
84 		perror("seteuid() failed");
85 
86 	if (queue != -1)
87 		if (mq_close(queue))
88 			perror("mq_close() during shutdown");
89 	if (queue_path)
90 		/*
91 		 * Be silent if this fails, if we cleaned up already it's
92 		 * expected to fail
93 		 */
94 		mq_unlink(queue_path);
95 	if (default_settings) {
96 		if (saved_def_msgs)
97 			__set(def_msgs, saved_def_msgs,
98 			      "failed to restore saved_def_msgs");
99 		if (saved_def_msgsize)
100 			__set(def_msgsize, saved_def_msgsize,
101 			      "failed to restore saved_def_msgsize");
102 	}
103 	if (saved_max_msgs)
104 		__set(max_msgs, saved_max_msgs,
105 		      "failed to restore saved_max_msgs");
106 	if (saved_max_msgsize)
107 		__set(max_msgsize, saved_max_msgsize,
108 		      "failed to restore saved_max_msgsize");
109 	if (exit_val)
110 		error(exit_val, errno, "%s at %d", err_cause, line_no);
111 	exit(0);
112 }
113 
114 static inline int get(FILE *stream)
115 {
116 	int value;
117 	rewind(stream);
118 	if (fscanf(stream, "%d", &value) != 1)
119 		shutdown(4, "Error reading /proc entry", __LINE__ - 1);
120 	return value;
121 }
122 
123 static inline void set(FILE *stream, int value)
124 {
125 	int new_value;
126 
127 	rewind(stream);
128 	if (fprintf(stream, "%d", value) < 0)
129 		return shutdown(5, "Failed writing to /proc file",
130 				__LINE__ - 1);
131 	new_value = get(stream);
132 	if (new_value != value)
133 		return shutdown(5, "We didn't get what we wrote to /proc back",
134 				__LINE__ - 1);
135 }
136 
137 static inline void getr(int type, struct rlimit *rlim)
138 {
139 	if (getrlimit(type, rlim))
140 		shutdown(6, "getrlimit()", __LINE__ - 1);
141 }
142 
143 static inline void setr(int type, struct rlimit *rlim)
144 {
145 	if (setrlimit(type, rlim))
146 		shutdown(7, "setrlimit()", __LINE__ - 1);
147 }
148 
149 void validate_current_settings()
150 {
151 	int rlim_needed;
152 
153 	if (cur_limits.rlim_cur < 4096) {
154 		printf("Current rlimit value for POSIX message queue bytes is "
155 		       "unreasonably low,\nincreasing.\n\n");
156 		cur_limits.rlim_cur = 8192;
157 		cur_limits.rlim_max = 16384;
158 		setr(RLIMIT_MSGQUEUE, &cur_limits);
159 	}
160 
161 	if (default_settings) {
162 		rlim_needed = (cur_def_msgs + 1) * (cur_def_msgsize + 1 +
163 						    2 * sizeof(void *));
164 		if (rlim_needed > cur_limits.rlim_cur) {
165 			printf("Temporarily lowering default queue parameters "
166 			       "to something that will work\n"
167 			       "with the current rlimit values.\n\n");
168 			set(def_msgs, 10);
169 			cur_def_msgs = 10;
170 			set(def_msgsize, 128);
171 			cur_def_msgsize = 128;
172 		}
173 	} else {
174 		rlim_needed = (cur_max_msgs + 1) * (cur_max_msgsize + 1 +
175 						    2 * sizeof(void *));
176 		if (rlim_needed > cur_limits.rlim_cur) {
177 			printf("Temporarily lowering maximum queue parameters "
178 			       "to something that will work\n"
179 			       "with the current rlimit values in case this is "
180 			       "a kernel that ties the default\n"
181 			       "queue parameters to the maximum queue "
182 			       "parameters.\n\n");
183 			set(max_msgs, 10);
184 			cur_max_msgs = 10;
185 			set(max_msgsize, 128);
186 			cur_max_msgsize = 128;
187 		}
188 	}
189 }
190 
191 /*
192  * test_queue - Test opening a queue, shutdown if we fail.  This should
193  * only be called in situations that should never fail.  We clean up
194  * after ourselves and return the queue attributes in *result.
195  */
196 static inline void test_queue(struct mq_attr *attr, struct mq_attr *result)
197 {
198 	int flags = O_RDWR | O_EXCL | O_CREAT;
199 	int perms = DEFFILEMODE;
200 
201 	if ((queue = mq_open(queue_path, flags, perms, attr)) == -1)
202 		shutdown(1, "mq_open()", __LINE__);
203 	if (mq_getattr(queue, result))
204 		shutdown(1, "mq_getattr()", __LINE__);
205 	if (mq_close(queue))
206 		shutdown(1, "mq_close()", __LINE__);
207 	queue = -1;
208 	if (mq_unlink(queue_path))
209 		shutdown(1, "mq_unlink()", __LINE__);
210 }
211 
212 /*
213  * Same as test_queue above, but failure is not fatal.
214  * Returns:
215  * 0 - Failed to create a queue
216  * 1 - Created a queue, attributes in *result
217  */
218 static inline int test_queue_fail(struct mq_attr *attr, struct mq_attr *result)
219 {
220 	int flags = O_RDWR | O_EXCL | O_CREAT;
221 	int perms = DEFFILEMODE;
222 
223 	if ((queue = mq_open(queue_path, flags, perms, attr)) == -1)
224 		return 0;
225 	if (mq_getattr(queue, result))
226 		shutdown(1, "mq_getattr()", __LINE__);
227 	if (mq_close(queue))
228 		shutdown(1, "mq_close()", __LINE__);
229 	queue = -1;
230 	if (mq_unlink(queue_path))
231 		shutdown(1, "mq_unlink()", __LINE__);
232 	return 1;
233 }
234 
235 int main(int argc, char *argv[])
236 {
237 	struct mq_attr attr, result;
238 
239 	if (argc != 2) {
240 		fprintf(stderr, "Must pass a valid queue name\n\n");
241 		fprintf(stderr, usage, argv[0]);
242 		exit(1);
243 	}
244 
245 	/*
246 	 * Although we can create a msg queue with a non-absolute path name,
247 	 * unlink will fail.  So, if the name doesn't start with a /, add one
248 	 * when we save it.
249 	 */
250 	if (*argv[1] == '/')
251 		queue_path = strdup(argv[1]);
252 	else {
253 		queue_path = malloc(strlen(argv[1]) + 2);
254 		if (!queue_path) {
255 			perror("malloc()");
256 			exit(1);
257 		}
258 		queue_path[0] = '/';
259 		queue_path[1] = 0;
260 		strcat(queue_path, argv[1]);
261 	}
262 
263 	if (getuid() != 0) {
264 		fprintf(stderr, "Not running as root, but almost all tests "
265 			"require root in order to modify\nsystem settings.  "
266 			"Exiting.\n");
267 		exit(1);
268 	}
269 
270 	/* Find out what files there are for us to make tweaks in */
271 	def_msgs = fopen(DEF_MSGS, "r+");
272 	def_msgsize = fopen(DEF_MSGSIZE, "r+");
273 	max_msgs = fopen(MAX_MSGS, "r+");
274 	max_msgsize = fopen(MAX_MSGSIZE, "r+");
275 
276 	if (!max_msgs)
277 		shutdown(2, "Failed to open msg_max", __LINE__);
278 	if (!max_msgsize)
279 		shutdown(2, "Failed to open msgsize_max", __LINE__);
280 	if (def_msgs || def_msgsize)
281 		default_settings = 1;
282 
283 	/* Load up the current system values for everything we can */
284 	getr(RLIMIT_MSGQUEUE, &saved_limits);
285 	cur_limits = saved_limits;
286 	if (default_settings) {
287 		saved_def_msgs = cur_def_msgs = get(def_msgs);
288 		saved_def_msgsize = cur_def_msgsize = get(def_msgsize);
289 	}
290 	saved_max_msgs = cur_max_msgs = get(max_msgs);
291 	saved_max_msgsize = cur_max_msgsize = get(max_msgsize);
292 
293 	/* Tell the user our initial state */
294 	printf("\nInitial system state:\n");
295 	printf("\tUsing queue path:\t\t%s\n", queue_path);
296 	printf("\tRLIMIT_MSGQUEUE(soft):\t\t%ld\n",
297 		(long) saved_limits.rlim_cur);
298 	printf("\tRLIMIT_MSGQUEUE(hard):\t\t%ld\n",
299 		(long) saved_limits.rlim_max);
300 	printf("\tMaximum Message Size:\t\t%d\n", saved_max_msgsize);
301 	printf("\tMaximum Queue Size:\t\t%d\n", saved_max_msgs);
302 	if (default_settings) {
303 		printf("\tDefault Message Size:\t\t%d\n", saved_def_msgsize);
304 		printf("\tDefault Queue Size:\t\t%d\n", saved_def_msgs);
305 	} else {
306 		printf("\tDefault Message Size:\t\tNot Supported\n");
307 		printf("\tDefault Queue Size:\t\tNot Supported\n");
308 	}
309 	printf("\n");
310 
311 	validate_current_settings();
312 
313 	printf("Adjusted system state for testing:\n");
314 	printf("\tRLIMIT_MSGQUEUE(soft):\t\t%ld\n", (long) cur_limits.rlim_cur);
315 	printf("\tRLIMIT_MSGQUEUE(hard):\t\t%ld\n", (long) cur_limits.rlim_max);
316 	printf("\tMaximum Message Size:\t\t%d\n", cur_max_msgsize);
317 	printf("\tMaximum Queue Size:\t\t%d\n", cur_max_msgs);
318 	if (default_settings) {
319 		printf("\tDefault Message Size:\t\t%d\n", cur_def_msgsize);
320 		printf("\tDefault Queue Size:\t\t%d\n", cur_def_msgs);
321 	}
322 
323 	printf("\n\nTest series 1, behavior when no attr struct "
324 	       "passed to mq_open:\n");
325 	if (!default_settings) {
326 		test_queue(NULL, &result);
327 		printf("Given sane system settings, mq_open without an attr "
328 		       "struct succeeds:\tPASS\n");
329 		if (result.mq_maxmsg != cur_max_msgs ||
330 		    result.mq_msgsize != cur_max_msgsize) {
331 			printf("Kernel does not support setting the default "
332 			       "mq attributes,\nbut also doesn't tie the "
333 			       "defaults to the maximums:\t\t\tPASS\n");
334 		} else {
335 			set(max_msgs, ++cur_max_msgs);
336 			set(max_msgsize, ++cur_max_msgsize);
337 			test_queue(NULL, &result);
338 			if (result.mq_maxmsg == cur_max_msgs &&
339 			    result.mq_msgsize == cur_max_msgsize)
340 				printf("Kernel does not support setting the "
341 				       "default mq attributes and\n"
342 				       "also ties system wide defaults to "
343 				       "the system wide maximums:\t\t"
344 				       "FAIL\n");
345 			else
346 				printf("Kernel does not support setting the "
347 				       "default mq attributes,\n"
348 				       "but also doesn't tie the defaults to "
349 				       "the maximums:\t\t\tPASS\n");
350 		}
351 	} else {
352 		printf("Kernel supports setting defaults separately from "
353 		       "maximums:\t\tPASS\n");
354 		/*
355 		 * While we are here, go ahead and test that the kernel
356 		 * properly follows the default settings
357 		 */
358 		test_queue(NULL, &result);
359 		printf("Given sane values, mq_open without an attr struct "
360 		       "succeeds:\t\tPASS\n");
361 		if (result.mq_maxmsg != cur_def_msgs ||
362 		    result.mq_msgsize != cur_def_msgsize)
363 			printf("Kernel supports setting defaults, but does "
364 			       "not actually honor them:\tFAIL\n\n");
365 		else {
366 			set(def_msgs, ++cur_def_msgs);
367 			set(def_msgsize, ++cur_def_msgsize);
368 			/* In case max was the same as the default */
369 			set(max_msgs, ++cur_max_msgs);
370 			set(max_msgsize, ++cur_max_msgsize);
371 			test_queue(NULL, &result);
372 			if (result.mq_maxmsg != cur_def_msgs ||
373 			    result.mq_msgsize != cur_def_msgsize)
374 				printf("Kernel supports setting defaults, but "
375 				       "does not actually honor them:\t"
376 				       "FAIL\n");
377 			else
378 				printf("Kernel properly honors default setting "
379 				       "knobs:\t\t\t\tPASS\n");
380 		}
381 		set(def_msgs, cur_max_msgs + 1);
382 		cur_def_msgs = cur_max_msgs + 1;
383 		set(def_msgsize, cur_max_msgsize + 1);
384 		cur_def_msgsize = cur_max_msgsize + 1;
385 		if (cur_def_msgs * (cur_def_msgsize + 2 * sizeof(void *)) >=
386 		    cur_limits.rlim_cur) {
387 			cur_limits.rlim_cur = (cur_def_msgs + 2) *
388 				(cur_def_msgsize + 2 * sizeof(void *));
389 			cur_limits.rlim_max = 2 * cur_limits.rlim_cur;
390 			setr(RLIMIT_MSGQUEUE, &cur_limits);
391 		}
392 		if (test_queue_fail(NULL, &result)) {
393 			if (result.mq_maxmsg == cur_max_msgs &&
394 			    result.mq_msgsize == cur_max_msgsize)
395 				printf("Kernel properly limits default values "
396 				       "to lesser of default/max:\t\tPASS\n");
397 			else
398 				printf("Kernel does not properly set default "
399 				       "queue parameters when\ndefaults > "
400 				       "max:\t\t\t\t\t\t\t\tFAIL\n");
401 		} else
402 			printf("Kernel fails to open mq because defaults are "
403 			       "greater than maximums:\tFAIL\n");
404 		set(def_msgs, --cur_def_msgs);
405 		set(def_msgsize, --cur_def_msgsize);
406 		cur_limits.rlim_cur = cur_limits.rlim_max = cur_def_msgs *
407 			cur_def_msgsize;
408 		setr(RLIMIT_MSGQUEUE, &cur_limits);
409 		if (test_queue_fail(NULL, &result))
410 			printf("Kernel creates queue even though defaults "
411 			       "would exceed\nrlimit setting:"
412 			       "\t\t\t\t\t\t\t\tFAIL\n");
413 		else
414 			printf("Kernel properly fails to create queue when "
415 			       "defaults would\nexceed rlimit:"
416 			       "\t\t\t\t\t\t\t\tPASS\n");
417 	}
418 
419 	/*
420 	 * Test #2 - open with an attr struct that exceeds rlimit
421 	 */
422 	printf("\n\nTest series 2, behavior when attr struct is "
423 	       "passed to mq_open:\n");
424 	cur_max_msgs = 32;
425 	cur_max_msgsize = cur_limits.rlim_max >> 4;
426 	set(max_msgs, cur_max_msgs);
427 	set(max_msgsize, cur_max_msgsize);
428 	attr.mq_maxmsg = cur_max_msgs;
429 	attr.mq_msgsize = cur_max_msgsize;
430 	if (test_queue_fail(&attr, &result))
431 		printf("Queue open in excess of rlimit max when euid = 0 "
432 		       "succeeded:\t\tFAIL\n");
433 	else
434 		printf("Queue open in excess of rlimit max when euid = 0 "
435 		       "failed:\t\tPASS\n");
436 	attr.mq_maxmsg = cur_max_msgs + 1;
437 	attr.mq_msgsize = 10;
438 	if (test_queue_fail(&attr, &result))
439 		printf("Queue open with mq_maxmsg > limit when euid = 0 "
440 		       "succeeded:\t\tPASS\n");
441 	else
442 		printf("Queue open with mq_maxmsg > limit when euid = 0 "
443 		       "failed:\t\tFAIL\n");
444 	attr.mq_maxmsg = 1;
445 	attr.mq_msgsize = cur_max_msgsize + 1;
446 	if (test_queue_fail(&attr, &result))
447 		printf("Queue open with mq_msgsize > limit when euid = 0 "
448 		       "succeeded:\t\tPASS\n");
449 	else
450 		printf("Queue open with mq_msgsize > limit when euid = 0 "
451 		       "failed:\t\tFAIL\n");
452 	attr.mq_maxmsg = 65536;
453 	attr.mq_msgsize = 65536;
454 	if (test_queue_fail(&attr, &result))
455 		printf("Queue open with total size > 2GB when euid = 0 "
456 		       "succeeded:\t\tFAIL\n");
457 	else
458 		printf("Queue open with total size > 2GB when euid = 0 "
459 		       "failed:\t\t\tPASS\n");
460 
461 	if (seteuid(99) == -1) {
462 		perror("seteuid() failed");
463 		exit(1);
464 	}
465 
466 	attr.mq_maxmsg = cur_max_msgs;
467 	attr.mq_msgsize = cur_max_msgsize;
468 	if (test_queue_fail(&attr, &result))
469 		printf("Queue open in excess of rlimit max when euid = 99 "
470 		       "succeeded:\t\tFAIL\n");
471 	else
472 		printf("Queue open in excess of rlimit max when euid = 99 "
473 		       "failed:\t\tPASS\n");
474 	attr.mq_maxmsg = cur_max_msgs + 1;
475 	attr.mq_msgsize = 10;
476 	if (test_queue_fail(&attr, &result))
477 		printf("Queue open with mq_maxmsg > limit when euid = 99 "
478 		       "succeeded:\t\tFAIL\n");
479 	else
480 		printf("Queue open with mq_maxmsg > limit when euid = 99 "
481 		       "failed:\t\tPASS\n");
482 	attr.mq_maxmsg = 1;
483 	attr.mq_msgsize = cur_max_msgsize + 1;
484 	if (test_queue_fail(&attr, &result))
485 		printf("Queue open with mq_msgsize > limit when euid = 99 "
486 		       "succeeded:\t\tFAIL\n");
487 	else
488 		printf("Queue open with mq_msgsize > limit when euid = 99 "
489 		       "failed:\t\tPASS\n");
490 	attr.mq_maxmsg = 65536;
491 	attr.mq_msgsize = 65536;
492 	if (test_queue_fail(&attr, &result))
493 		printf("Queue open with total size > 2GB when euid = 99 "
494 		       "succeeded:\t\tFAIL\n");
495 	else
496 		printf("Queue open with total size > 2GB when euid = 99 "
497 		       "failed:\t\t\tPASS\n");
498 
499 	shutdown(0,"",0);
500 }
501