• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2008 Kristian Høgsberg
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sublicense, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the
13  * next paragraph) shall be included in all copies or substantial
14  * portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  */
25 
26 #define _GNU_SOURCE
27 
28 #include <stdbool.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <stddef.h>
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <stdbool.h>
35 #include <errno.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <sys/socket.h>
39 #include <sys/un.h>
40 #include <dlfcn.h>
41 #include <assert.h>
42 #include <sys/time.h>
43 #include <fcntl.h>
44 #include <sys/file.h>
45 #include <sys/stat.h>
46 
47 #include "wayland-util.h"
48 #include "wayland-private.h"
49 #include "wayland-server-private.h"
50 #include "wayland-server.h"
51 #include "wayland-os.h"
52 
53 /* This is the size of the char array in struct sock_addr_un.
54  * No Wayland socket can be created with a path longer than this,
55  * including the null terminator.
56  */
57 #ifndef UNIX_PATH_MAX
58 #define UNIX_PATH_MAX	108
59 #endif
60 
61 #define LOCK_SUFFIX	".lock"
62 #define LOCK_SUFFIXLEN	5
63 
64 struct wl_socket {
65 	int fd;
66 	int fd_lock;
67 	struct sockaddr_un addr;
68 	char lock_addr[UNIX_PATH_MAX + LOCK_SUFFIXLEN];
69 	struct wl_list link;
70 	struct wl_event_source *source;
71 	char *display_name;
72 };
73 
74 struct wl_client {
75 	struct wl_connection *connection;
76 	struct wl_event_source *source;
77 	struct wl_display *display;
78 	struct wl_resource *display_resource;
79 	struct wl_list link;
80 	struct wl_map objects;
81 	struct wl_priv_signal destroy_signal;
82 	struct ucred ucred;
83 	int error;
84 	struct wl_priv_signal resource_created_signal;
85 };
86 
87 struct wl_display {
88 	struct wl_event_loop *loop;
89 	int run;
90 
91 	uint32_t id;
92 	uint32_t serial;
93 
94 	struct wl_list registry_resource_list;
95 	struct wl_list global_list;
96 	struct wl_list socket_list;
97 	struct wl_list client_list;
98 	struct wl_list protocol_loggers;
99 
100 	struct wl_priv_signal destroy_signal;
101 	struct wl_priv_signal create_client_signal;
102 
103 	struct wl_array additional_shm_formats;
104 
105 	wl_display_global_filter_func_t global_filter;
106 	void *global_filter_data;
107 };
108 
109 struct wl_global {
110 	struct wl_display *display;
111 	const struct wl_interface *interface;
112 	uint32_t name;
113 	uint32_t version;
114 	void *data;
115 	wl_global_bind_func_t bind;
116 	struct wl_list link;
117 	bool removed;
118 };
119 
120 struct wl_resource {
121 	struct wl_object object;
122 	wl_resource_destroy_func_t destroy;
123 	struct wl_list link;
124 	/* Unfortunately some users of libwayland (e.g. mesa) still use the
125 	 * deprecated wl_resource struct, even if creating it with the new
126 	 * wl_resource_create(). So we cannot change the layout of the struct
127 	 * unless after the data field. */
128 	struct wl_signal deprecated_destroy_signal;
129 	struct wl_client *client;
130 	void *data;
131 	int version;
132 	wl_dispatcher_func_t dispatcher;
133 	struct wl_priv_signal destroy_signal;
134 };
135 
136 struct wl_protocol_logger {
137 	struct wl_list link;
138 	wl_protocol_logger_func_t func;
139 	void *user_data;
140 };
141 
142 static int debug_server = 0;
143 
144 static void
log_closure(struct wl_resource * resource,struct wl_closure * closure,int send)145 log_closure(struct wl_resource *resource,
146 	    struct wl_closure *closure, int send)
147 {
148 	struct wl_object *object = &resource->object;
149 	struct wl_display *display = resource->client->display;
150 	struct wl_protocol_logger *protocol_logger;
151 	struct wl_protocol_logger_message message;
152 
153 	if (debug_server)
154 		wl_closure_print(closure, object, send);
155 
156 	if (!wl_list_empty(&display->protocol_loggers)) {
157 		message.resource = resource;
158 		message.message_opcode = closure->opcode;
159 		message.message = closure->message;
160 		message.arguments_count = closure->count;
161 		message.arguments = closure->args;
162 		wl_list_for_each(protocol_logger,
163 				 &display->protocol_loggers, link) {
164 			protocol_logger->func(protocol_logger->user_data,
165 					      send ? WL_PROTOCOL_LOGGER_EVENT :
166 						     WL_PROTOCOL_LOGGER_REQUEST,
167 					      &message);
168 		}
169 	}
170 }
171 
172 static bool
verify_objects(struct wl_resource * resource,uint32_t opcode,union wl_argument * args)173 verify_objects(struct wl_resource *resource, uint32_t opcode,
174 	       union wl_argument *args)
175 {
176 	struct wl_object *object = &resource->object;
177 	const char *signature = object->interface->events[opcode].signature;
178 	struct argument_details arg;
179 	struct wl_resource *res;
180 	int count, i;
181 
182 	count = arg_count_for_signature(signature);
183 	for (i = 0; i < count; i++) {
184 		signature = get_next_argument(signature, &arg);
185 		switch (arg.type) {
186 		case 'n':
187 		case 'o':
188 			res = (struct wl_resource *) (args[i].o);
189 			if (res && res->client != resource->client) {
190 				wl_log("compositor bug: The compositor "
191 				       "tried to use an object from one "
192 				       "client in a '%s.%s' for a different "
193 				       "client.\n", object->interface->name,
194 				       object->interface->events[opcode].name);
195 				return false;
196 			}
197 		}
198 	}
199 	return true;
200 }
201 
202 static void
handle_array(struct wl_resource * resource,uint32_t opcode,union wl_argument * args,int (* send_func)(struct wl_closure *,struct wl_connection *))203 handle_array(struct wl_resource *resource, uint32_t opcode,
204 	     union wl_argument *args,
205 	     int (*send_func)(struct wl_closure *, struct wl_connection *))
206 {
207 	struct wl_closure *closure;
208 	struct wl_object *object = &resource->object;
209 
210 	if (resource->client->error)
211 		return;
212 
213 	if (!verify_objects(resource, opcode, args)) {
214 		resource->client->error = 1;
215 		return;
216 	}
217 
218 	closure = wl_closure_marshal(object, opcode, args,
219 				     &object->interface->events[opcode]);
220 
221 	if (closure == NULL) {
222 		resource->client->error = 1;
223 		return;
224 	}
225 
226 	log_closure(resource, closure, true);
227 
228 	if (send_func(closure, resource->client->connection))
229 		resource->client->error = 1;
230 
231 	wl_closure_destroy(closure);
232 }
233 
234 WL_EXPORT void
wl_resource_post_event_array(struct wl_resource * resource,uint32_t opcode,union wl_argument * args)235 wl_resource_post_event_array(struct wl_resource *resource, uint32_t opcode,
236 			     union wl_argument *args)
237 {
238 	handle_array(resource, opcode, args, wl_closure_send);
239 }
240 
241 WL_EXPORT void
wl_resource_post_event(struct wl_resource * resource,uint32_t opcode,...)242 wl_resource_post_event(struct wl_resource *resource, uint32_t opcode, ...)
243 {
244 	union wl_argument args[WL_CLOSURE_MAX_ARGS];
245 	struct wl_object *object = &resource->object;
246 	va_list ap;
247 
248 	va_start(ap, opcode);
249 	wl_argument_from_va_list(object->interface->events[opcode].signature,
250 				 args, WL_CLOSURE_MAX_ARGS, ap);
251 	va_end(ap);
252 
253 	wl_resource_post_event_array(resource, opcode, args);
254 }
255 
256 
257 WL_EXPORT void
wl_resource_queue_event_array(struct wl_resource * resource,uint32_t opcode,union wl_argument * args)258 wl_resource_queue_event_array(struct wl_resource *resource, uint32_t opcode,
259 			      union wl_argument *args)
260 {
261 	handle_array(resource, opcode, args, wl_closure_queue);
262 }
263 
264 WL_EXPORT void
wl_resource_queue_event(struct wl_resource * resource,uint32_t opcode,...)265 wl_resource_queue_event(struct wl_resource *resource, uint32_t opcode, ...)
266 {
267 	union wl_argument args[WL_CLOSURE_MAX_ARGS];
268 	struct wl_object *object = &resource->object;
269 	va_list ap;
270 
271 	va_start(ap, opcode);
272 	wl_argument_from_va_list(object->interface->events[opcode].signature,
273 				 args, WL_CLOSURE_MAX_ARGS, ap);
274 	va_end(ap);
275 
276 	wl_resource_queue_event_array(resource, opcode, args);
277 }
278 
279 static void
wl_resource_post_error_vargs(struct wl_resource * resource,uint32_t code,const char * msg,va_list argp)280 wl_resource_post_error_vargs(struct wl_resource *resource,
281 			     uint32_t code, const char *msg, va_list argp)
282 {
283 	struct wl_client *client = resource->client;
284 	char buffer[128];
285 
286 	vsnprintf(buffer, sizeof buffer, msg, argp);
287 
288 	/*
289 	 * When a client aborts, its resources are destroyed in id order,
290 	 * which means the display resource is destroyed first. If destruction
291 	 * of any later resources results in a protocol error, we end up here
292 	 * with a NULL display_resource. Do not try to send errors to an
293 	 * already dead client.
294 	 */
295 	if (client->error || !client->display_resource)
296 		return;
297 
298 	wl_resource_post_event(client->display_resource,
299 			       WL_DISPLAY_ERROR, resource, code, buffer);
300 	client->error = 1;
301 
302 }
303 
304 WL_EXPORT void
wl_resource_post_error(struct wl_resource * resource,uint32_t code,const char * msg,...)305 wl_resource_post_error(struct wl_resource *resource,
306 		       uint32_t code, const char *msg, ...)
307 {
308 	va_list ap;
309 
310 	va_start(ap, msg);
311 	wl_resource_post_error_vargs(resource, code, msg, ap);
312 	va_end(ap);
313 }
314 
315 static void
destroy_client_with_error(struct wl_client * client,const char * reason)316 destroy_client_with_error(struct wl_client *client, const char *reason)
317 {
318 	wl_log("%s (pid %u)\n", reason, client->ucred.pid);
319 	wl_client_destroy(client);
320 }
321 
322 static int
wl_client_connection_data(int fd,uint32_t mask,void * data)323 wl_client_connection_data(int fd, uint32_t mask, void *data)
324 {
325 	struct wl_client *client = data;
326 	struct wl_connection *connection = client->connection;
327 	struct wl_resource *resource;
328 	struct wl_object *object;
329 	struct wl_closure *closure;
330 	const struct wl_message *message;
331 	uint32_t p[2];
332 	uint32_t resource_flags;
333 	int opcode, size, since;
334 	int len;
335 
336 	if (mask & WL_EVENT_HANGUP) {
337 		wl_client_destroy(client);
338 		return 1;
339 	}
340 
341 	if (mask & WL_EVENT_ERROR) {
342 		destroy_client_with_error(client, "socket error");
343 		return 1;
344 	}
345 
346 	if (mask & WL_EVENT_WRITABLE) {
347 		len = wl_connection_flush(connection);
348 		if (len < 0 && errno != EAGAIN) {
349 			destroy_client_with_error(
350 			    client, "failed to flush client connection");
351 			return 1;
352 		} else if (len >= 0) {
353 			wl_event_source_fd_update(client->source,
354 						  WL_EVENT_READABLE);
355 		}
356 	}
357 
358 	len = 0;
359 	if (mask & WL_EVENT_READABLE) {
360 		len = wl_connection_read(connection);
361 		if (len == 0 || (len < 0 && errno != EAGAIN)) {
362 			destroy_client_with_error(
363 			    client, "failed to read client connection");
364 			return 1;
365 		}
366 	}
367 
368 	while (len >= 0 && (size_t) len >= sizeof p) {
369 		wl_connection_copy(connection, p, sizeof p);
370 		opcode = p[1] & 0xffff;
371 		size = p[1] >> 16;
372 		if (len < size)
373 			break;
374 
375 		resource = wl_map_lookup(&client->objects, p[0]);
376 		resource_flags = wl_map_lookup_flags(&client->objects, p[0]);
377 		if (resource == NULL) {
378 			wl_resource_post_error(client->display_resource,
379 					       WL_DISPLAY_ERROR_INVALID_OBJECT,
380 					       "invalid object %u", p[0]);
381 			break;
382 		}
383 
384 		object = &resource->object;
385 		if (opcode >= object->interface->method_count) {
386 			wl_resource_post_error(client->display_resource,
387 					       WL_DISPLAY_ERROR_INVALID_METHOD,
388 					       "invalid method %d, object %s@%u",
389 					       opcode,
390 					       object->interface->name,
391 					       object->id);
392 			break;
393 		}
394 
395 		message = &object->interface->methods[opcode];
396 		since = wl_message_get_since(message);
397 		if (!(resource_flags & WL_MAP_ENTRY_LEGACY) &&
398 		    resource->version > 0 && resource->version < since) {
399 			wl_resource_post_error(client->display_resource,
400 					       WL_DISPLAY_ERROR_INVALID_METHOD,
401 					       "invalid method %d (since %d < %d)"
402 					       ", object %s@%u",
403 					       opcode, resource->version, since,
404 					       object->interface->name,
405 					       object->id);
406 			break;
407 		}
408 
409 
410 		closure = wl_connection_demarshal(client->connection, size,
411 						  &client->objects, message);
412 
413 		if (closure == NULL && errno == ENOMEM) {
414 			wl_resource_post_no_memory(resource);
415 			break;
416 		} else if (closure == NULL ||
417 			   wl_closure_lookup_objects(closure, &client->objects) < 0) {
418 			wl_resource_post_error(client->display_resource,
419 					       WL_DISPLAY_ERROR_INVALID_METHOD,
420 					       "invalid arguments for %s@%u.%s",
421 					       object->interface->name,
422 					       object->id,
423 					       message->name);
424 			wl_closure_destroy(closure);
425 			break;
426 		}
427 
428 		log_closure(resource, closure, false);
429 
430 		if ((resource_flags & WL_MAP_ENTRY_LEGACY) ||
431 		    resource->dispatcher == NULL) {
432 			wl_closure_invoke(closure, WL_CLOSURE_INVOKE_SERVER,
433 					  object, opcode, client);
434 		} else {
435 			wl_closure_dispatch(closure, resource->dispatcher,
436 					    object, opcode);
437 		}
438 
439 		wl_closure_destroy(closure);
440 
441 		if (client->error)
442 			break;
443 
444 		len = wl_connection_pending_input(connection);
445 	}
446 
447 	if (client->error) {
448 		destroy_client_with_error(client,
449 					  "error in client communication");
450 	}
451 
452 	return 1;
453 }
454 
455 /** Flush pending events to the client
456  *
457  * \param client The client object
458  *
459  * Events sent to clients are queued in a buffer and written to the
460  * socket later - typically when the compositor has handled all
461  * requests and goes back to block in the event loop.  This function
462  * flushes all queued up events for a client immediately.
463  *
464  * \memberof wl_client
465  */
466 WL_EXPORT void
wl_client_flush(struct wl_client * client)467 wl_client_flush(struct wl_client *client)
468 {
469 	wl_connection_flush(client->connection);
470 }
471 
472 /** Get the display object for the given client
473  *
474  * \param client The client object
475  * \return The display object the client is associated with.
476  *
477  * \memberof wl_client
478  */
479 WL_EXPORT struct wl_display *
wl_client_get_display(struct wl_client * client)480 wl_client_get_display(struct wl_client *client)
481 {
482 	return client->display;
483 }
484 
485 static int
486 bind_display(struct wl_client *client, struct wl_display *display);
487 
488 /** Create a client for the given file descriptor
489  *
490  * \param display The display object
491  * \param fd The file descriptor for the socket to the client
492  * \return The new client object or NULL on failure.
493  *
494  * Given a file descriptor corresponding to one end of a socket, this
495  * function will create a wl_client struct and add the new client to
496  * the compositors client list.  At that point, the client is
497  * initialized and ready to run, as if the client had connected to the
498  * servers listening socket.  When the client eventually sends
499  * requests to the compositor, the wl_client argument to the request
500  * handler will be the wl_client returned from this function.
501  *
502  * The other end of the socket can be passed to
503  * wl_display_connect_to_fd() on the client side or used with the
504  * WAYLAND_SOCKET environment variable on the client side.
505  *
506  * Listeners added with wl_display_add_client_created_listener() will
507  * be notified by this function after the client is fully constructed.
508  *
509  * On failure this function sets errno accordingly and returns NULL.
510  *
511  * \memberof wl_display
512  */
513 WL_EXPORT struct wl_client *
wl_client_create(struct wl_display * display,int fd)514 wl_client_create(struct wl_display *display, int fd)
515 {
516 	struct wl_client *client;
517 	socklen_t len;
518 
519 	client = zalloc(sizeof *client);
520 	if (client == NULL)
521 		return NULL;
522 
523 	wl_priv_signal_init(&client->resource_created_signal);
524 	client->display = display;
525 	client->source = wl_event_loop_add_fd(display->loop, fd,
526 					      WL_EVENT_READABLE,
527 					      wl_client_connection_data, client);
528 
529 	if (!client->source)
530 		goto err_client;
531 
532 	len = sizeof client->ucred;
533 	if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED,
534 		       &client->ucred, &len) < 0)
535 		goto err_source;
536 
537 	client->connection = wl_connection_create(fd);
538 	if (client->connection == NULL)
539 		goto err_source;
540 
541 	wl_map_init(&client->objects, WL_MAP_SERVER_SIDE);
542 
543 	if (wl_map_insert_at(&client->objects, 0, 0, NULL) < 0)
544 		goto err_map;
545 
546 	wl_priv_signal_init(&client->destroy_signal);
547 	if (bind_display(client, display) < 0)
548 		goto err_map;
549 
550 	wl_list_insert(display->client_list.prev, &client->link);
551 
552 	wl_priv_signal_emit(&display->create_client_signal, client);
553 
554 	return client;
555 
556 err_map:
557 	wl_map_release(&client->objects);
558 	wl_connection_destroy(client->connection);
559 err_source:
560 	wl_event_source_remove(client->source);
561 err_client:
562 	free(client);
563 	return NULL;
564 }
565 
566 /** Return Unix credentials for the client
567  *
568  * \param client The display object
569  * \param pid Returns the process ID
570  * \param uid Returns the user ID
571  * \param gid Returns the group ID
572  *
573  * This function returns the process ID, the user ID and the group ID
574  * for the given client.  The credentials come from getsockopt() with
575  * SO_PEERCRED, on the client socket fd.  All the pointers can be
576  * NULL, if the caller is not interested in a particular ID.
577  *
578  * Be aware that for clients that a compositor forks and execs and
579  * then connects using socketpair(), this function will return the
580  * credentials for the compositor.  The credentials for the socketpair
581  * are set at creation time in the compositor.
582  *
583  * \memberof wl_client
584  */
585 WL_EXPORT void
wl_client_get_credentials(struct wl_client * client,pid_t * pid,uid_t * uid,gid_t * gid)586 wl_client_get_credentials(struct wl_client *client,
587 			  pid_t *pid, uid_t *uid, gid_t *gid)
588 {
589 	if (pid)
590 		*pid = client->ucred.pid;
591 	if (uid)
592 		*uid = client->ucred.uid;
593 	if (gid)
594 		*gid = client->ucred.gid;
595 }
596 
597 /** Get the file descriptor for the client
598  *
599  * \param client The display object
600  * \return The file descriptor to use for the connection
601  *
602  * This function returns the file descriptor for the given client.
603  *
604  * Be sure to use the file descriptor from the client for inspection only.
605  * If the caller does anything to the file descriptor that changes its state,
606  * it will likely cause problems.
607  *
608  * See also wl_client_get_credentials().
609  * It is recommended that you evaluate whether wl_client_get_credentials()
610  * can be applied to your use case instead of this function.
611  *
612  * If you would like to distinguish just between the client and the compositor
613  * itself from the client's request, it can be done by getting the client
614  * credentials and by checking the PID of the client and the compositor's PID.
615  * Regarding the case in which the socketpair() is being used, you need to be
616  * careful. Please note the documentation for wl_client_get_credentials().
617  *
618  * This function can be used for a compositor to validate a request from
619  * a client if there are additional information provided from the client's
620  * file descriptor. For instance, suppose you can get the security contexts
621  * from the client's file descriptor. The compositor can validate the client's
622  * request with the contexts and make a decision whether it permits or deny it.
623  *
624  * \memberof wl_client
625  */
626 WL_EXPORT int
wl_client_get_fd(struct wl_client * client)627 wl_client_get_fd(struct wl_client *client)
628 {
629 	return wl_connection_get_fd(client->connection);
630 }
631 
632 /** Look up an object in the client name space
633  *
634  * \param client The client object
635  * \param id The object id
636  * \return The object or NULL if there is not object for the given ID
637  *
638  * This looks up an object in the client object name space by its
639  * object ID.
640  *
641  * \memberof wl_client
642  */
643 WL_EXPORT struct wl_resource *
wl_client_get_object(struct wl_client * client,uint32_t id)644 wl_client_get_object(struct wl_client *client, uint32_t id)
645 {
646 	return wl_map_lookup(&client->objects, id);
647 }
648 
649 WL_EXPORT void
wl_client_post_no_memory(struct wl_client * client)650 wl_client_post_no_memory(struct wl_client *client)
651 {
652 	wl_resource_post_error(client->display_resource,
653 			       WL_DISPLAY_ERROR_NO_MEMORY, "no memory");
654 }
655 
656 /** Report an internal server error
657  *
658  * \param client The client object
659  * \param msg A printf-style format string
660  * \param ... Format string arguments
661  *
662  * Report an unspecified internal implementation error and disconnect
663  * the client.
664  *
665  * \memberof wl_client
666  */
667 WL_EXPORT void
wl_client_post_implementation_error(struct wl_client * client,char const * msg,...)668 wl_client_post_implementation_error(struct wl_client *client,
669 				    char const *msg, ...)
670 {
671 	va_list ap;
672 
673 	va_start(ap, msg);
674 	wl_resource_post_error_vargs(client->display_resource,
675 				     WL_DISPLAY_ERROR_IMPLEMENTATION,
676 				     msg, ap);
677 	va_end(ap);
678 }
679 
680 WL_EXPORT void
wl_resource_post_no_memory(struct wl_resource * resource)681 wl_resource_post_no_memory(struct wl_resource *resource)
682 {
683 	wl_resource_post_error(resource->client->display_resource,
684 			       WL_DISPLAY_ERROR_NO_MEMORY, "no memory");
685 }
686 
687 /** Detect if a wl_resource uses the deprecated public definition.
688  *
689  * Before Wayland 1.2.0, the definition of struct wl_resource was public.
690  * It was made opaque just before 1.2.0, and later new fields were added.
691  * The new fields cannot be accessed if a program is using the deprecated
692  * definition, as there would not be memory allocated for them.
693  *
694  * The creation pattern for the deprecated definition was wl_resource_init()
695  * followed by wl_client_add_resource(). wl_resource_init() was an inline
696  * function and no longer exists, but binaries might still carry it.
697  * wl_client_add_resource() still exists for ABI compatibility.
698  */
699 static bool
resource_is_deprecated(struct wl_resource * resource)700 resource_is_deprecated(struct wl_resource *resource)
701 {
702 	struct wl_map *map = &resource->client->objects;
703 	int id = resource->object.id;
704 
705 	/* wl_client_add_resource() marks deprecated resources with the flag. */
706 	if (wl_map_lookup_flags(map, id) & WL_MAP_ENTRY_LEGACY)
707 		return true;
708 
709 	return false;
710 }
711 
712 static enum wl_iterator_result
destroy_resource(void * element,void * data,uint32_t flags)713 destroy_resource(void *element, void *data, uint32_t flags)
714 {
715 	struct wl_resource *resource = element;
716 
717 	wl_signal_emit(&resource->deprecated_destroy_signal, resource);
718 	/* Don't emit the new signal for deprecated resources, as that would
719 	 * access memory outside the bounds of the deprecated struct */
720 	if (!resource_is_deprecated(resource))
721 		wl_priv_signal_final_emit(&resource->destroy_signal, resource);
722 
723 	if (resource->destroy)
724 		resource->destroy(resource);
725 
726 	if (!(flags & WL_MAP_ENTRY_LEGACY))
727 		free(resource);
728 
729 	return WL_ITERATOR_CONTINUE;
730 }
731 
732 WL_EXPORT void
wl_resource_destroy(struct wl_resource * resource)733 wl_resource_destroy(struct wl_resource *resource)
734 {
735 	struct wl_client *client = resource->client;
736 	uint32_t id;
737 	uint32_t flags;
738 
739 	id = resource->object.id;
740 	flags = wl_map_lookup_flags(&client->objects, id);
741 	destroy_resource(resource, NULL, flags);
742 
743 	if (id < WL_SERVER_ID_START) {
744 		if (client->display_resource) {
745 			wl_resource_queue_event(client->display_resource,
746 						WL_DISPLAY_DELETE_ID, id);
747 		}
748 		wl_map_insert_at(&client->objects, 0, id, NULL);
749 	} else {
750 		wl_map_remove(&client->objects, id);
751 	}
752 }
753 
754 WL_EXPORT uint32_t
wl_resource_get_id(struct wl_resource * resource)755 wl_resource_get_id(struct wl_resource *resource)
756 {
757 	return resource->object.id;
758 }
759 
760 WL_EXPORT struct wl_list *
wl_resource_get_link(struct wl_resource * resource)761 wl_resource_get_link(struct wl_resource *resource)
762 {
763 	return &resource->link;
764 }
765 
766 WL_EXPORT struct wl_resource *
wl_resource_from_link(struct wl_list * link)767 wl_resource_from_link(struct wl_list *link)
768 {
769 	struct wl_resource *resource;
770 
771 	return wl_container_of(link, resource, link);
772 }
773 
774 WL_EXPORT struct wl_resource *
wl_resource_find_for_client(struct wl_list * list,struct wl_client * client)775 wl_resource_find_for_client(struct wl_list *list, struct wl_client *client)
776 {
777 	struct wl_resource *resource;
778 
779 	if (client == NULL)
780 		return NULL;
781 
782 	wl_list_for_each(resource, list, link) {
783 		if (resource->client == client)
784 			return resource;
785 	}
786 
787 	return NULL;
788 }
789 
790 WL_EXPORT struct wl_client *
wl_resource_get_client(struct wl_resource * resource)791 wl_resource_get_client(struct wl_resource *resource)
792 {
793 	return resource->client;
794 }
795 
796 WL_EXPORT void
wl_resource_set_user_data(struct wl_resource * resource,void * data)797 wl_resource_set_user_data(struct wl_resource *resource, void *data)
798 {
799 	resource->data = data;
800 }
801 
802 WL_EXPORT void *
wl_resource_get_user_data(struct wl_resource * resource)803 wl_resource_get_user_data(struct wl_resource *resource)
804 {
805 	return resource->data;
806 }
807 
808 WL_EXPORT int
wl_resource_get_version(struct wl_resource * resource)809 wl_resource_get_version(struct wl_resource *resource)
810 {
811 	return resource->version;
812 }
813 
814 WL_EXPORT void
wl_resource_set_destructor(struct wl_resource * resource,wl_resource_destroy_func_t destroy)815 wl_resource_set_destructor(struct wl_resource *resource,
816 			   wl_resource_destroy_func_t destroy)
817 {
818 	resource->destroy = destroy;
819 }
820 
821 WL_EXPORT int
wl_resource_instance_of(struct wl_resource * resource,const struct wl_interface * interface,const void * implementation)822 wl_resource_instance_of(struct wl_resource *resource,
823 			const struct wl_interface *interface,
824 			const void *implementation)
825 {
826 	return wl_interface_equal(resource->object.interface, interface) &&
827 		resource->object.implementation == implementation;
828 }
829 
830 WL_EXPORT void
wl_resource_add_destroy_listener(struct wl_resource * resource,struct wl_listener * listener)831 wl_resource_add_destroy_listener(struct wl_resource *resource,
832 				 struct wl_listener * listener)
833 {
834 	if (resource_is_deprecated(resource))
835 		wl_signal_add(&resource->deprecated_destroy_signal, listener);
836 	else
837 		wl_priv_signal_add(&resource->destroy_signal, listener);
838 }
839 
840 WL_EXPORT struct wl_listener *
wl_resource_get_destroy_listener(struct wl_resource * resource,wl_notify_func_t notify)841 wl_resource_get_destroy_listener(struct wl_resource *resource,
842 				 wl_notify_func_t notify)
843 {
844 	if (resource_is_deprecated(resource))
845 		return wl_signal_get(&resource->deprecated_destroy_signal, notify);
846 	return wl_priv_signal_get(&resource->destroy_signal, notify);
847 }
848 
849 /** Retrieve the interface name (class) of a resource object.
850  *
851  * \param resource The resource object
852  *
853  * \memberof wl_resource
854  */
855 WL_EXPORT const char *
wl_resource_get_class(struct wl_resource * resource)856 wl_resource_get_class(struct wl_resource *resource)
857 {
858 	return resource->object.interface->name;
859 }
860 
861 /** Safely converts an object into its corresponding resource
862  *
863  * \param object The object to convert
864  * \return A corresponding resource, or NULL on failure
865  *
866  * Safely converts an object into its corresponding resource.
867  *
868  * This is useful for implementing functions that are given a \c wl_argument
869  * array, and that need to do further introspection on the ".o" field, as it
870  * is otherwise an opaque type.
871  *
872  * \memberof wl_resource
873  */
874 WL_EXPORT struct wl_resource *
wl_resource_from_object(struct wl_object * object)875 wl_resource_from_object(struct wl_object *object)
876 {
877 	struct wl_resource *resource;
878 	if (object == NULL)
879 		return NULL;
880 	return wl_container_of(object, resource, object);
881 }
882 
883 WL_EXPORT void
wl_client_add_destroy_listener(struct wl_client * client,struct wl_listener * listener)884 wl_client_add_destroy_listener(struct wl_client *client,
885 			       struct wl_listener *listener)
886 {
887 	wl_priv_signal_add(&client->destroy_signal, listener);
888 }
889 
890 WL_EXPORT struct wl_listener *
wl_client_get_destroy_listener(struct wl_client * client,wl_notify_func_t notify)891 wl_client_get_destroy_listener(struct wl_client *client,
892 			       wl_notify_func_t notify)
893 {
894 	return wl_priv_signal_get(&client->destroy_signal, notify);
895 }
896 
897 WL_EXPORT void
wl_client_destroy(struct wl_client * client)898 wl_client_destroy(struct wl_client *client)
899 {
900 	uint32_t serial = 0;
901 
902 	wl_priv_signal_final_emit(&client->destroy_signal, client);
903 
904 	wl_client_flush(client);
905 	wl_map_for_each(&client->objects, destroy_resource, &serial);
906 	wl_map_release(&client->objects);
907 	wl_event_source_remove(client->source);
908 	close(wl_connection_destroy(client->connection));
909 	wl_list_remove(&client->link);
910 	wl_list_remove(&client->resource_created_signal.listener_list);
911 	free(client);
912 }
913 
914 /* Check if a global filter is registered and use it if any.
915  *
916  * If no wl_global filter has been registered, this function will
917  * return true, allowing the wl_global to be visible to the wl_client
918  */
919 static bool
wl_global_is_visible(const struct wl_client * client,const struct wl_global * global)920 wl_global_is_visible(const struct wl_client *client,
921 	      const struct wl_global *global)
922 {
923 	struct wl_display *display = client->display;
924 
925 	return (display->global_filter == NULL ||
926 		display->global_filter(client, global, display->global_filter_data));
927 }
928 
929 static void
registry_bind(struct wl_client * client,struct wl_resource * resource,uint32_t name,const char * interface,uint32_t version,uint32_t id)930 registry_bind(struct wl_client *client,
931 	      struct wl_resource *resource, uint32_t name,
932 	      const char *interface, uint32_t version, uint32_t id)
933 {
934 	struct wl_global *global;
935 	struct wl_display *display = resource->data;
936 
937 	wl_list_for_each(global, &display->global_list, link)
938 		if (global->name == name)
939 			break;
940 
941 	if (&global->link == &display->global_list)
942 		wl_resource_post_error(resource,
943 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
944 				       "invalid global %s (%d)", interface, name);
945 	else if (strcmp(global->interface->name, interface) != 0)
946 		wl_resource_post_error(resource,
947 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
948 				       "invalid interface for global %u: "
949 				       "have %s, wanted %s",
950 				       name, interface, global->interface->name);
951 	else if (version == 0)
952 		wl_resource_post_error(resource,
953 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
954 				       "invalid version for global %s (%d): 0 is not a valid version",
955 				       interface, name);
956 	else if (global->version < version)
957 		wl_resource_post_error(resource,
958 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
959 				       "invalid version for global %s (%d): have %d, wanted %d",
960 				       interface, name, global->version, version);
961 	else if (!wl_global_is_visible(client, global))
962 		wl_resource_post_error(resource,
963 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
964 				       "invalid global %s (%d)", interface, name);
965 	else
966 		global->bind(client, global->data, version, id);
967 }
968 
969 static const struct wl_registry_interface registry_interface = {
970 	registry_bind
971 };
972 
973 static void
display_sync(struct wl_client * client,struct wl_resource * resource,uint32_t id)974 display_sync(struct wl_client *client,
975 	     struct wl_resource *resource, uint32_t id)
976 {
977 	struct wl_resource *callback;
978 	uint32_t serial;
979 
980 	callback = wl_resource_create(client, &wl_callback_interface, 1, id);
981 	if (callback == NULL) {
982 		wl_client_post_no_memory(client);
983 		return;
984 	}
985 
986 	serial = wl_display_get_serial(client->display);
987 	wl_callback_send_done(callback, serial);
988 	wl_resource_destroy(callback);
989 }
990 
991 static void
unbind_resource(struct wl_resource * resource)992 unbind_resource(struct wl_resource *resource)
993 {
994 	wl_list_remove(&resource->link);
995 }
996 
997 static void
display_get_registry(struct wl_client * client,struct wl_resource * resource,uint32_t id)998 display_get_registry(struct wl_client *client,
999 		     struct wl_resource *resource, uint32_t id)
1000 {
1001 	struct wl_display *display = resource->data;
1002 	struct wl_resource *registry_resource;
1003 	struct wl_global *global;
1004 
1005 	registry_resource =
1006 		wl_resource_create(client, &wl_registry_interface, 1, id);
1007 	if (registry_resource == NULL) {
1008 		wl_client_post_no_memory(client);
1009 		return;
1010 	}
1011 
1012 	wl_resource_set_implementation(registry_resource,
1013 				       &registry_interface,
1014 				       display, unbind_resource);
1015 
1016 	wl_list_insert(&display->registry_resource_list,
1017 		       &registry_resource->link);
1018 
1019 	wl_list_for_each(global, &display->global_list, link)
1020 		if (wl_global_is_visible(client, global) && !global->removed)
1021 			wl_resource_post_event(registry_resource,
1022 					       WL_REGISTRY_GLOBAL,
1023 					       global->name,
1024 					       global->interface->name,
1025 					       global->version);
1026 }
1027 
1028 static const struct wl_display_interface display_interface = {
1029 	display_sync,
1030 	display_get_registry
1031 };
1032 
1033 static void
destroy_client_display_resource(struct wl_resource * resource)1034 destroy_client_display_resource(struct wl_resource *resource)
1035 {
1036 	resource->client->display_resource = NULL;
1037 }
1038 
1039 static int
bind_display(struct wl_client * client,struct wl_display * display)1040 bind_display(struct wl_client *client, struct wl_display *display)
1041 {
1042 	client->display_resource =
1043 		wl_resource_create(client, &wl_display_interface, 1, 1);
1044 	if (client->display_resource == NULL) {
1045 		/* DON'T send no-memory error to client - it has no
1046 		 * resource to which it could post the event */
1047 		return -1;
1048 	}
1049 
1050 	wl_resource_set_implementation(client->display_resource,
1051 				       &display_interface, display,
1052 				       destroy_client_display_resource);
1053 	return 0;
1054 }
1055 
1056 /** Create Wayland display object.
1057  *
1058  * \return The Wayland display object. Null if failed to create
1059  *
1060  * This creates the wl_display object.
1061  *
1062  * \memberof wl_display
1063  */
1064 WL_EXPORT struct wl_display *
wl_display_create(void)1065 wl_display_create(void)
1066 {
1067 	struct wl_display *display;
1068 	const char *debug;
1069 
1070 	debug = getenv("WAYLAND_DEBUG");
1071 	if (debug && (strstr(debug, "server") || strstr(debug, "1")))
1072 		debug_server = 1;
1073 
1074 	display = malloc(sizeof *display);
1075 	if (display == NULL)
1076 		return NULL;
1077 
1078 	display->loop = wl_event_loop_create();
1079 	if (display->loop == NULL) {
1080 		free(display);
1081 		return NULL;
1082 	}
1083 
1084 	wl_list_init(&display->global_list);
1085 	wl_list_init(&display->socket_list);
1086 	wl_list_init(&display->client_list);
1087 	wl_list_init(&display->registry_resource_list);
1088 	wl_list_init(&display->protocol_loggers);
1089 
1090 	wl_priv_signal_init(&display->destroy_signal);
1091 	wl_priv_signal_init(&display->create_client_signal);
1092 
1093 	display->id = 1;
1094 	display->serial = 0;
1095 
1096 	display->global_filter = NULL;
1097 	display->global_filter_data = NULL;
1098 
1099 	wl_array_init(&display->additional_shm_formats);
1100 
1101 	return display;
1102 }
1103 
1104 static void
wl_socket_destroy(struct wl_socket * s)1105 wl_socket_destroy(struct wl_socket *s)
1106 {
1107 	if (s->source)
1108 		wl_event_source_remove(s->source);
1109 	if (s->addr.sun_path[0])
1110 		unlink(s->addr.sun_path);
1111 	if (s->fd >= 0)
1112 		close(s->fd);
1113 	if (s->lock_addr[0])
1114 		unlink(s->lock_addr);
1115 	if (s->fd_lock >= 0)
1116 		close(s->fd_lock);
1117 
1118 	free(s);
1119 }
1120 
1121 static struct wl_socket *
wl_socket_alloc(void)1122 wl_socket_alloc(void)
1123 {
1124 	struct wl_socket *s;
1125 
1126 	s = zalloc(sizeof *s);
1127 	if (!s)
1128 		return NULL;
1129 
1130 	s->fd = -1;
1131 	s->fd_lock = -1;
1132 
1133 	return s;
1134 }
1135 
1136 /** Destroy Wayland display object.
1137  *
1138  * \param display The Wayland display object which should be destroyed.
1139  * \return None.
1140  *
1141  * This function emits the wl_display destroy signal, releases
1142  * all the sockets added to this display, free's all the globals associated
1143  * with this display, free's memory of additional shared memory formats and
1144  * destroy the display object.
1145  *
1146  * \sa wl_display_add_destroy_listener
1147  *
1148  * \memberof wl_display
1149  */
1150 WL_EXPORT void
wl_display_destroy(struct wl_display * display)1151 wl_display_destroy(struct wl_display *display)
1152 {
1153 	struct wl_socket *s, *next;
1154 	struct wl_global *global, *gnext;
1155 
1156 	wl_priv_signal_final_emit(&display->destroy_signal, display);
1157 
1158 	wl_list_for_each_safe(s, next, &display->socket_list, link) {
1159 		wl_socket_destroy(s);
1160 	}
1161 	wl_event_loop_destroy(display->loop);
1162 
1163 	wl_list_for_each_safe(global, gnext, &display->global_list, link)
1164 		free(global);
1165 
1166 	wl_array_release(&display->additional_shm_formats);
1167 
1168 	wl_list_remove(&display->protocol_loggers);
1169 
1170 	free(display);
1171 }
1172 
1173 /** Set a filter function for global objects
1174  *
1175  * \param display The Wayland display object.
1176  * \param filter  The global filter function.
1177  * \param data User data to be associated with the global filter.
1178  * \return None.
1179  *
1180  * Set a filter for the wl_display to advertise or hide global objects
1181  * to clients.
1182  * The set filter will be used during wl_global advertisement to
1183  * determine whether a global object should be advertised to a
1184  * given client, and during wl_global binding to determine whether
1185  * a given client should be allowed to bind to a global.
1186  *
1187  * Clients that try to bind to a global that was filtered out will
1188  * have an error raised.
1189  *
1190  * Setting the filter NULL will result in all globals being
1191  * advertised to all clients. The default is no filter.
1192  *
1193  * \memberof wl_display
1194  */
1195 WL_EXPORT void
wl_display_set_global_filter(struct wl_display * display,wl_display_global_filter_func_t filter,void * data)1196 wl_display_set_global_filter(struct wl_display *display,
1197 			     wl_display_global_filter_func_t filter,
1198 			     void *data)
1199 {
1200 	display->global_filter = filter;
1201 	display->global_filter_data = data;
1202 }
1203 
1204 WL_EXPORT struct wl_global *
wl_global_create(struct wl_display * display,const struct wl_interface * interface,int version,void * data,wl_global_bind_func_t bind)1205 wl_global_create(struct wl_display *display,
1206 		 const struct wl_interface *interface, int version,
1207 		 void *data, wl_global_bind_func_t bind)
1208 {
1209 	struct wl_global *global;
1210 	struct wl_resource *resource;
1211 
1212 	if (version < 1) {
1213 		wl_log("wl_global_create: failing to create interface "
1214 		       "'%s' with version %d because it is less than 1\n",
1215 			interface->name, version);
1216 		return NULL;
1217 	}
1218 
1219 	if (version > interface->version) {
1220 		wl_log("wl_global_create: implemented version for '%s' "
1221 		       "higher than interface version (%d > %d)\n",
1222 		       interface->name, version, interface->version);
1223 		return NULL;
1224 	}
1225 
1226 	global = malloc(sizeof *global);
1227 	if (global == NULL)
1228 		return NULL;
1229 
1230 	global->display = display;
1231 	global->name = display->id++;
1232 	global->interface = interface;
1233 	global->version = version;
1234 	global->data = data;
1235 	global->bind = bind;
1236 	global->removed = false;
1237 	wl_list_insert(display->global_list.prev, &global->link);
1238 
1239 	wl_list_for_each(resource, &display->registry_resource_list, link)
1240 		wl_resource_post_event(resource,
1241 				       WL_REGISTRY_GLOBAL,
1242 				       global->name,
1243 				       global->interface->name,
1244 				       global->version);
1245 
1246 	return global;
1247 }
1248 
1249 /** Remove the global
1250  *
1251  * \param global The Wayland global.
1252  *
1253  * Broadcast a global remove event to all clients without destroying the
1254  * global. This function can only be called once per global.
1255  *
1256  * wl_global_destroy() removes the global and immediately destroys it. On
1257  * the other end, this function only removes the global, allowing clients
1258  * that have not yet received the global remove event to continue to bind to
1259  * it.
1260  *
1261  * This can be used by compositors to mitigate clients being disconnected
1262  * because a global has been added and removed too quickly. Compositors can call
1263  * wl_global_remove(), then wait an implementation-defined amount of time, then
1264  * call wl_global_destroy(). Note that the destruction of a global is still
1265  * racy, since clients have no way to acknowledge that they received the remove
1266  * event.
1267  *
1268  * \since 1.17.90
1269  */
1270 WL_EXPORT void
wl_global_remove(struct wl_global * global)1271 wl_global_remove(struct wl_global *global)
1272 {
1273 	struct wl_display *display = global->display;
1274 	struct wl_resource *resource;
1275 
1276 	if (global->removed)
1277 		wl_abort("wl_global_remove: called twice on the same "
1278 			 "global '%s@%"PRIu32"'", global->interface->name,
1279 			 global->name);
1280 
1281 	wl_list_for_each(resource, &display->registry_resource_list, link)
1282 		wl_resource_post_event(resource, WL_REGISTRY_GLOBAL_REMOVE,
1283 				       global->name);
1284 
1285 	global->removed = true;
1286 }
1287 
1288 WL_EXPORT void
wl_global_destroy(struct wl_global * global)1289 wl_global_destroy(struct wl_global *global)
1290 {
1291 	if (!global->removed)
1292 		wl_global_remove(global);
1293 	wl_list_remove(&global->link);
1294 	free(global);
1295 }
1296 
1297 WL_EXPORT const struct wl_interface *
wl_global_get_interface(const struct wl_global * global)1298 wl_global_get_interface(const struct wl_global *global)
1299 {
1300 	return global->interface;
1301 }
1302 
1303 WL_EXPORT void *
wl_global_get_user_data(const struct wl_global * global)1304 wl_global_get_user_data(const struct wl_global *global)
1305 {
1306 	return global->data;
1307 }
1308 
1309 /** Set the global's user data
1310  *
1311  * \param global The global object
1312  * \param data The user data pointer
1313  *
1314  * \since 1.17.90
1315  */
1316 WL_EXPORT void
wl_global_set_user_data(struct wl_global * global,void * data)1317 wl_global_set_user_data(struct wl_global *global, void *data)
1318 {
1319 	global->data = data;
1320 }
1321 
1322 /** Get the current serial number
1323  *
1324  * \param display The display object
1325  *
1326  * This function returns the most recent serial number, but does not
1327  * increment it.
1328  *
1329  * \memberof wl_display
1330  */
1331 WL_EXPORT uint32_t
wl_display_get_serial(struct wl_display * display)1332 wl_display_get_serial(struct wl_display *display)
1333 {
1334 	return display->serial;
1335 }
1336 
1337 /** Get the next serial number
1338  *
1339  * \param display The display object
1340  *
1341  * This function increments the display serial number and returns the
1342  * new value.
1343  *
1344  * \memberof wl_display
1345  */
1346 WL_EXPORT uint32_t
wl_display_next_serial(struct wl_display * display)1347 wl_display_next_serial(struct wl_display *display)
1348 {
1349 	display->serial++;
1350 
1351 	return display->serial;
1352 }
1353 
1354 WL_EXPORT struct wl_event_loop *
wl_display_get_event_loop(struct wl_display * display)1355 wl_display_get_event_loop(struct wl_display *display)
1356 {
1357 	return display->loop;
1358 }
1359 
1360 WL_EXPORT void
wl_display_terminate(struct wl_display * display)1361 wl_display_terminate(struct wl_display *display)
1362 {
1363 	display->run = 0;
1364 }
1365 
1366 WL_EXPORT void
wl_display_run(struct wl_display * display)1367 wl_display_run(struct wl_display *display)
1368 {
1369 	display->run = 1;
1370 
1371 	while (display->run) {
1372 		wl_display_flush_clients(display);
1373 		wl_event_loop_dispatch(display->loop, -1);
1374 	}
1375 }
1376 
1377 WL_EXPORT void
wl_display_flush_clients(struct wl_display * display)1378 wl_display_flush_clients(struct wl_display *display)
1379 {
1380 	struct wl_client *client, *next;
1381 	int ret;
1382 
1383 	wl_list_for_each_safe(client, next, &display->client_list, link) {
1384 		ret = wl_connection_flush(client->connection);
1385 		if (ret < 0 && errno == EAGAIN) {
1386 			wl_event_source_fd_update(client->source,
1387 						  WL_EVENT_WRITABLE |
1388 						  WL_EVENT_READABLE);
1389 		} else if (ret < 0) {
1390 			wl_client_destroy(client);
1391 		}
1392 	}
1393 }
1394 
1395 /** Destroy all clients connected to the display
1396  *
1397  * \param display The display object
1398  *
1399  * This function should be called right before wl_display_destroy() to ensure
1400  * all client resources are closed properly. Destroying a client from within
1401  * wl_display_destroy_clients() is safe, but creating one will leak resources
1402  * and raise a warning.
1403  *
1404  * \memberof wl_display
1405  */
1406 WL_EXPORT void
wl_display_destroy_clients(struct wl_display * display)1407 wl_display_destroy_clients(struct wl_display *display)
1408 {
1409 	struct wl_list tmp_client_list, *pos;
1410 	struct wl_client *client;
1411 
1412 	/* Move the whole client list to a temporary head because some new clients
1413 	 * might be added to the original head. */
1414 	wl_list_init(&tmp_client_list);
1415 	wl_list_insert_list(&tmp_client_list, &display->client_list);
1416 	wl_list_init(&display->client_list);
1417 
1418 	/* wl_list_for_each_safe isn't enough here: it fails if the next client is
1419 	 * destroyed by the destroy handler of the current one. */
1420 	while (!wl_list_empty(&tmp_client_list)) {
1421 		pos = tmp_client_list.next;
1422 		client = wl_container_of(pos, client, link);
1423 
1424 		wl_client_destroy(client);
1425 	}
1426 
1427 	if (!wl_list_empty(&display->client_list)) {
1428 		wl_log("wl_display_destroy_clients: cannot destroy all clients because "
1429 			   "new ones were created by destroy callbacks\n");
1430 	}
1431 }
1432 
1433 static int
socket_data(int fd,uint32_t mask,void * data)1434 socket_data(int fd, uint32_t mask, void *data)
1435 {
1436 	struct wl_display *display = data;
1437 	struct sockaddr_un name;
1438 	socklen_t length;
1439 	int client_fd;
1440 
1441 	length = sizeof name;
1442 	client_fd = wl_os_accept_cloexec(fd, (struct sockaddr *) &name,
1443 					 &length);
1444 	if (client_fd < 0)
1445 		wl_log("failed to accept: %s\n", strerror(errno));
1446 	else
1447 		if (!wl_client_create(display, client_fd))
1448 			close(client_fd);
1449 
1450 	return 1;
1451 }
1452 
1453 static int
wl_socket_lock(struct wl_socket * socket)1454 wl_socket_lock(struct wl_socket *socket)
1455 {
1456 	struct stat socket_stat;
1457 
1458 	snprintf(socket->lock_addr, sizeof socket->lock_addr,
1459 		 "%s%s", socket->addr.sun_path, LOCK_SUFFIX);
1460 
1461 	socket->fd_lock = open(socket->lock_addr, O_CREAT | O_CLOEXEC | O_RDWR,
1462 			       (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
1463 
1464 	if (socket->fd_lock < 0) {
1465 		wl_log("unable to open lockfile %s check permissions\n",
1466 			socket->lock_addr);
1467 		goto err;
1468 	}
1469 
1470 	if (flock(socket->fd_lock, LOCK_EX | LOCK_NB) < 0) {
1471 		wl_log("unable to lock lockfile %s, maybe another compositor is running\n",
1472 			socket->lock_addr);
1473 		goto err_fd;
1474 	}
1475 
1476 	if (lstat(socket->addr.sun_path, &socket_stat) < 0 ) {
1477 		if (errno != ENOENT) {
1478 			wl_log("did not manage to stat file %s\n",
1479 				socket->addr.sun_path);
1480 			goto err_fd;
1481 		}
1482 	} else if (socket_stat.st_mode & S_IWUSR ||
1483 		   socket_stat.st_mode & S_IWGRP) {
1484 		unlink(socket->addr.sun_path);
1485 	}
1486 
1487 	return 0;
1488 err_fd:
1489 	close(socket->fd_lock);
1490 	socket->fd_lock = -1;
1491 err:
1492 	*socket->lock_addr = 0;
1493 	/* we did not set this value here, but without lock the
1494 	 * socket won't be created anyway. This prevents the
1495 	 * wl_socket_destroy from unlinking already existing socket
1496 	 * created by other compositor */
1497 	*socket->addr.sun_path = 0;
1498 
1499 	return -1;
1500 }
1501 
1502 static int
wl_socket_init_for_display_name(struct wl_socket * s,const char * name)1503 wl_socket_init_for_display_name(struct wl_socket *s, const char *name)
1504 {
1505 	int name_size;
1506 	const char *runtime_dir = "";
1507 	const char *separator = "";
1508 
1509 	if (name[0] != '/') {
1510 		runtime_dir = getenv("XDG_RUNTIME_DIR");
1511 		if (!runtime_dir) {
1512 			wl_log("error: XDG_RUNTIME_DIR not set in the environment\n");
1513 
1514 			/* to prevent programs reporting
1515 			 * "failed to add socket: Success" */
1516 			errno = ENOENT;
1517 			return -1;
1518 		}
1519 		separator = "/";
1520 	}
1521 
1522 	s->addr.sun_family = AF_LOCAL;
1523 	name_size = snprintf(s->addr.sun_path, sizeof s->addr.sun_path,
1524 			     "%s%s%s", runtime_dir, separator, name) + 1;
1525 
1526 	s->display_name = (s->addr.sun_path + name_size - 1) - strlen(name);
1527 
1528 	assert(name_size > 0);
1529 	if (name_size > (int)sizeof s->addr.sun_path) {
1530 		wl_log("error: socket path \"%s%s%s\" plus null terminator"
1531 		       " exceeds 108 bytes\n", runtime_dir, separator, name);
1532 		*s->addr.sun_path = 0;
1533 		/* to prevent programs reporting
1534 		 * "failed to add socket: Success" */
1535 		errno = ENAMETOOLONG;
1536 		return -1;
1537 	}
1538 
1539 	return 0;
1540 }
1541 
1542 static int
_wl_display_add_socket(struct wl_display * display,struct wl_socket * s)1543 _wl_display_add_socket(struct wl_display *display, struct wl_socket *s)
1544 {
1545 	socklen_t size;
1546 
1547 	s->fd = wl_os_socket_cloexec(PF_LOCAL, SOCK_STREAM, 0);
1548 	if (s->fd < 0) {
1549 		return -1;
1550 	}
1551 
1552 	size = offsetof (struct sockaddr_un, sun_path) + strlen(s->addr.sun_path);
1553 	if (bind(s->fd, (struct sockaddr *) &s->addr, size) < 0) {
1554 		wl_log("bind() failed with error: %s\n", strerror(errno));
1555 		return -1;
1556 	}
1557 
1558 	if (listen(s->fd, 128) < 0) {
1559 		wl_log("listen() failed with error: %s\n", strerror(errno));
1560 		return -1;
1561 	}
1562 
1563 	s->source = wl_event_loop_add_fd(display->loop, s->fd,
1564 					 WL_EVENT_READABLE,
1565 					 socket_data, display);
1566 	if (s->source == NULL) {
1567 		return -1;
1568 	}
1569 
1570 	wl_list_insert(display->socket_list.prev, &s->link);
1571 	return 0;
1572 }
1573 
1574 WL_EXPORT const char *
wl_display_add_socket_auto(struct wl_display * display)1575 wl_display_add_socket_auto(struct wl_display *display)
1576 {
1577 	struct wl_socket *s;
1578 	int displayno = 0;
1579 	char display_name[16] = "";
1580 
1581 	/* A reasonable number of maximum default sockets. If
1582 	 * you need more than this, use the explicit add_socket API. */
1583 	const int MAX_DISPLAYNO = 32;
1584 
1585 	s = wl_socket_alloc();
1586 	if (s == NULL)
1587 		return NULL;
1588 
1589 	do {
1590 		snprintf(display_name, sizeof display_name, "wayland-%d", displayno);
1591 		if (wl_socket_init_for_display_name(s, display_name) < 0) {
1592 			wl_socket_destroy(s);
1593 			return NULL;
1594 		}
1595 
1596 		if (wl_socket_lock(s) < 0)
1597 			continue;
1598 
1599 		if (_wl_display_add_socket(display, s) < 0) {
1600 			wl_socket_destroy(s);
1601 			return NULL;
1602 		}
1603 
1604 		return s->display_name;
1605 	} while (displayno++ < MAX_DISPLAYNO);
1606 
1607 	/* Ran out of display names. */
1608 	wl_socket_destroy(s);
1609 	errno = EINVAL;
1610 	return NULL;
1611 }
1612 
1613 /**  Add a socket with an existing fd to Wayland display for the clients to connect.
1614  *
1615  * \param display Wayland display to which the socket should be added.
1616  * \param sock_fd The existing socket file descriptor to be used
1617  * \return 0 if success. -1 if failed.
1618  *
1619  * The existing socket fd must already be created, opened, and locked.
1620  * The fd must be properly set to CLOEXEC and bound to a socket file
1621  * with both bind() and listen() already called.
1622  *
1623  * \memberof wl_display
1624  */
1625 WL_EXPORT int
wl_display_add_socket_fd(struct wl_display * display,int sock_fd)1626 wl_display_add_socket_fd(struct wl_display *display, int sock_fd)
1627 {
1628 	struct wl_socket *s;
1629 	struct stat buf;
1630 
1631 	/* Require a valid fd or fail */
1632 	if (sock_fd < 0 || fstat(sock_fd, &buf) < 0 || !S_ISSOCK(buf.st_mode)) {
1633 		return -1;
1634 	}
1635 
1636 	s = wl_socket_alloc();
1637 	if (s == NULL)
1638 		return -1;
1639 
1640 	s->source = wl_event_loop_add_fd(display->loop, sock_fd,
1641 					 WL_EVENT_READABLE,
1642 					 socket_data, display);
1643 	if (s->source == NULL) {
1644 		wl_log("failed to establish event source\n");
1645 		wl_socket_destroy(s);
1646 		return -1;
1647 	}
1648 
1649 	/* Reuse the existing fd */
1650 	s->fd = sock_fd;
1651 
1652 	wl_list_insert(display->socket_list.prev, &s->link);
1653 
1654 	return 0;
1655 }
1656 
1657 /** Add a socket to Wayland display for the clients to connect.
1658  *
1659  * \param display Wayland display to which the socket should be added.
1660  * \param name Name of the Unix socket.
1661  * \return 0 if success. -1 if failed.
1662  *
1663  * This adds a Unix socket to Wayland display which can be used by clients to
1664  * connect to Wayland display.
1665  *
1666  * If NULL is passed as name, then it would look for WAYLAND_DISPLAY env
1667  * variable for the socket name. If WAYLAND_DISPLAY is not set, then default
1668  * wayland-0 is used.
1669  *
1670  * If the socket name is a relative path, the Unix socket will be created in
1671  * the directory pointed to by environment variable XDG_RUNTIME_DIR. If
1672  * XDG_RUNTIME_DIR is not set, then this function fails and returns -1.
1673  *
1674  * If the socket name is an absolute path, then it is used as-is for the
1675  * the Unix socket.
1676  *
1677  * The length of the computed socket path must not exceed the maximum length
1678  * of a Unix socket path.
1679  * The function also fails if the user does not have write permission in the
1680  * directory or if the path is already in use.
1681  *
1682  * \memberof wl_display
1683  */
1684 WL_EXPORT int
wl_display_add_socket(struct wl_display * display,const char * name)1685 wl_display_add_socket(struct wl_display *display, const char *name)
1686 {
1687 	struct wl_socket *s;
1688 
1689 	s = wl_socket_alloc();
1690 	if (s == NULL)
1691 		return -1;
1692 
1693 	if (name == NULL)
1694 		name = getenv("WAYLAND_DISPLAY");
1695 	if (name == NULL)
1696 		name = "wayland-0";
1697 
1698 	if (wl_socket_init_for_display_name(s, name) < 0) {
1699 		wl_socket_destroy(s);
1700 		return -1;
1701 	}
1702 
1703 	if (wl_socket_lock(s) < 0) {
1704 		wl_socket_destroy(s);
1705 		return -1;
1706 	}
1707 
1708 	if (_wl_display_add_socket(display, s) < 0) {
1709 		wl_socket_destroy(s);
1710 		return -1;
1711 	}
1712 
1713 	return 0;
1714 }
1715 
1716 WL_EXPORT void
wl_display_add_destroy_listener(struct wl_display * display,struct wl_listener * listener)1717 wl_display_add_destroy_listener(struct wl_display *display,
1718 				struct wl_listener *listener)
1719 {
1720 	wl_priv_signal_add(&display->destroy_signal, listener);
1721 }
1722 
1723 /** Registers a listener for the client connection signal.
1724  *  When a new client object is created, \a listener will be notified, carrying
1725  *  a pointer to the new wl_client object.
1726  *
1727  *  \ref wl_client_create
1728  *  \ref wl_display
1729  *  \ref wl_listener
1730  *
1731  * \param display The display object
1732  * \param listener Signal handler object
1733  */
1734 WL_EXPORT void
wl_display_add_client_created_listener(struct wl_display * display,struct wl_listener * listener)1735 wl_display_add_client_created_listener(struct wl_display *display,
1736 					struct wl_listener *listener)
1737 {
1738 	wl_priv_signal_add(&display->create_client_signal, listener);
1739 }
1740 
1741 WL_EXPORT struct wl_listener *
wl_display_get_destroy_listener(struct wl_display * display,wl_notify_func_t notify)1742 wl_display_get_destroy_listener(struct wl_display *display,
1743 				wl_notify_func_t notify)
1744 {
1745 	return wl_priv_signal_get(&display->destroy_signal, notify);
1746 }
1747 
1748 WL_EXPORT void
wl_resource_set_implementation(struct wl_resource * resource,const void * implementation,void * data,wl_resource_destroy_func_t destroy)1749 wl_resource_set_implementation(struct wl_resource *resource,
1750 			       const void *implementation,
1751 			       void *data, wl_resource_destroy_func_t destroy)
1752 {
1753 	resource->object.implementation = implementation;
1754 	resource->data = data;
1755 	resource->destroy = destroy;
1756 	resource->dispatcher = NULL;
1757 }
1758 
1759 WL_EXPORT void
wl_resource_set_dispatcher(struct wl_resource * resource,wl_dispatcher_func_t dispatcher,const void * implementation,void * data,wl_resource_destroy_func_t destroy)1760 wl_resource_set_dispatcher(struct wl_resource *resource,
1761 			   wl_dispatcher_func_t dispatcher,
1762 			   const void *implementation,
1763 			   void *data, wl_resource_destroy_func_t destroy)
1764 {
1765 	resource->dispatcher = dispatcher;
1766 	resource->object.implementation = implementation;
1767 	resource->data = data;
1768 	resource->destroy = destroy;
1769 }
1770 
1771 /** Create a new resource object
1772  *
1773  * \param client The client owner of the new resource.
1774  * \param interface The interface of the new resource.
1775  * \param version The version of the new resource.
1776  * \param id The id of the new resource. If 0, an available id will be used.
1777  *
1778  * Listeners added with \a wl_client_add_resource_created_listener will be
1779  * notified at the end of this function.
1780  *
1781  * \memberof wl_resource
1782  */
1783 WL_EXPORT struct wl_resource *
wl_resource_create(struct wl_client * client,const struct wl_interface * interface,int version,uint32_t id)1784 wl_resource_create(struct wl_client *client,
1785 		   const struct wl_interface *interface,
1786 		   int version, uint32_t id)
1787 {
1788 	struct wl_resource *resource;
1789 
1790 	resource = malloc(sizeof *resource);
1791 	if (resource == NULL)
1792 		return NULL;
1793 
1794 	if (id == 0)
1795 		id = wl_map_insert_new(&client->objects, 0, NULL);
1796 
1797 	resource->object.id = id;
1798 	resource->object.interface = interface;
1799 	resource->object.implementation = NULL;
1800 
1801 	wl_signal_init(&resource->deprecated_destroy_signal);
1802 	wl_priv_signal_init(&resource->destroy_signal);
1803 
1804 	resource->destroy = NULL;
1805 	resource->client = client;
1806 	resource->data = NULL;
1807 	resource->version = version;
1808 	resource->dispatcher = NULL;
1809 
1810 	if (wl_map_insert_at(&client->objects, 0, id, resource) < 0) {
1811 		wl_resource_post_error(client->display_resource,
1812 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
1813 				       "invalid new id %d", id);
1814 		free(resource);
1815 		return NULL;
1816 	}
1817 
1818 	wl_priv_signal_emit(&client->resource_created_signal, resource);
1819 	return resource;
1820 }
1821 
1822 WL_EXPORT void
wl_log_set_handler_server(wl_log_func_t handler)1823 wl_log_set_handler_server(wl_log_func_t handler)
1824 {
1825 	wl_log_handler = handler;
1826 }
1827 
1828 /** Adds a new protocol logger.
1829  *
1830  * When a new protocol message arrives or is sent from the server
1831  * all the protocol logger functions will be called, carrying the
1832  * \a user_data pointer, the type of the message (request or
1833  * event) and the actual message.
1834  * The lifetime of the messages passed to the logger function ends
1835  * when they return so the messages cannot be stored and accessed
1836  * later.
1837  *
1838  * \a errno is set on error.
1839  *
1840  * \param display The display object
1841  * \param func The function to call to log a new protocol message
1842  * \param user_data The user data pointer to pass to \a func
1843  *
1844  * \return The protol logger object on success, NULL on failure.
1845  *
1846  * \sa wl_protocol_logger_destroy
1847  *
1848  * \memberof wl_display
1849  */
1850 WL_EXPORT struct wl_protocol_logger *
wl_display_add_protocol_logger(struct wl_display * display,wl_protocol_logger_func_t func,void * user_data)1851 wl_display_add_protocol_logger(struct wl_display *display,
1852 			       wl_protocol_logger_func_t func, void *user_data)
1853 {
1854 	struct wl_protocol_logger *logger;
1855 
1856 	logger = malloc(sizeof *logger);
1857 	if (!logger)
1858 		return NULL;
1859 
1860 	logger->func = func;
1861 	logger->user_data = user_data;
1862 	wl_list_insert(&display->protocol_loggers, &logger->link);
1863 
1864 	return logger;
1865 }
1866 
1867 /** Destroys a protocol logger.
1868  *
1869  * This function destroys a protocol logger and removes it from the display
1870  * it was added to with \a wl_display_add_protocol_logger.
1871  * The \a logger object becomes invalid after calling this function.
1872  *
1873  * \sa wl_display_add_protocol_logger
1874  *
1875  * \memberof wl_protocol_logger
1876  */
1877 WL_EXPORT void
wl_protocol_logger_destroy(struct wl_protocol_logger * logger)1878 wl_protocol_logger_destroy(struct wl_protocol_logger *logger)
1879 {
1880 	wl_list_remove(&logger->link);
1881 	free(logger);
1882 }
1883 
1884 /** Add support for a wl_shm pixel format
1885  *
1886  * \param display The display object
1887  * \param format The wl_shm pixel format to advertise
1888  * \return A pointer to the wl_shm format that was added to the list
1889  * or NULL if adding it to the list failed.
1890  *
1891  * Add the specified wl_shm format to the list of formats the wl_shm
1892  * object advertises when a client binds to it.  Adding a format to
1893  * the list means that clients will know that the compositor supports
1894  * this format and may use it for creating wl_shm buffers.  The
1895  * compositor must be able to handle the pixel format when a client
1896  * requests it.
1897  *
1898  * The compositor by default supports WL_SHM_FORMAT_ARGB8888 and
1899  * WL_SHM_FORMAT_XRGB8888.
1900  *
1901  * \memberof wl_display
1902  */
1903 WL_EXPORT uint32_t *
wl_display_add_shm_format(struct wl_display * display,uint32_t format)1904 wl_display_add_shm_format(struct wl_display *display, uint32_t format)
1905 {
1906 	uint32_t *p = NULL;
1907 
1908 	p = wl_array_add(&display->additional_shm_formats, sizeof *p);
1909 
1910 	if (p != NULL)
1911 		*p = format;
1912 	return p;
1913 }
1914 
1915 /**
1916  * Get list of additional wl_shm pixel formats
1917  *
1918  * \param display The display object
1919  *
1920  * This function returns the list of addition wl_shm pixel formats
1921  * that the compositor supports.  WL_SHM_FORMAT_ARGB8888 and
1922  * WL_SHM_FORMAT_XRGB8888 are always supported and not included in the
1923  * array, but all formats added through wl_display_add_shm_format()
1924  * will be in the array.
1925  *
1926  * \sa wl_display_add_shm_format()
1927  *
1928  * \private
1929  *
1930  * \memberof wl_display
1931  */
1932 struct wl_array *
wl_display_get_additional_shm_formats(struct wl_display * display)1933 wl_display_get_additional_shm_formats(struct wl_display *display)
1934 {
1935 	return &display->additional_shm_formats;
1936 }
1937 
1938 /** Get the list of currently connected clients
1939  *
1940  * \param display The display object
1941  *
1942  * This function returns a pointer to the list of clients currently
1943  * connected to the display. You can iterate on the list by using
1944  * the \a wl_client_for_each macro.
1945  * The returned value is valid for the lifetime of the \a display.
1946  * You must not modify the returned list, but only access it.
1947  *
1948  * \sa wl_client_for_each()
1949  * \sa wl_client_get_link()
1950  * \sa wl_client_from_link()
1951  *
1952  * \memberof wl_display
1953  */
1954 WL_EXPORT struct wl_list *
wl_display_get_client_list(struct wl_display * display)1955 wl_display_get_client_list(struct wl_display *display)
1956 {
1957 	return &display->client_list;
1958 }
1959 
1960 /** Get the link by which a client is inserted in the client list
1961  *
1962  * \param client The client object
1963  *
1964  * \sa wl_client_for_each()
1965  * \sa wl_display_get_client_list()
1966  * \sa wl_client_from_link()
1967  *
1968  * \memberof wl_client
1969  */
1970 WL_EXPORT struct wl_list *
wl_client_get_link(struct wl_client * client)1971 wl_client_get_link(struct wl_client *client)
1972 {
1973 	return &client->link;
1974 }
1975 
1976 /** Get a wl_client by its link
1977  *
1978  * \param link The link of a wl_client
1979  *
1980  * \sa wl_client_for_each()
1981  * \sa wl_display_get_client_list()
1982  * \sa wl_client_get_link()
1983  *
1984  * \memberof wl_client
1985  */
1986 WL_EXPORT struct wl_client *
wl_client_from_link(struct wl_list * link)1987 wl_client_from_link(struct wl_list *link)
1988 {
1989 	struct wl_client *client;
1990 
1991 	return wl_container_of(link, client, link);
1992 }
1993 
1994 /** Add a listener for the client's resource creation signal
1995  *
1996  * \param client The client object
1997  * \param listener The listener to be added
1998  *
1999  * When a new resource is created for this client the listener
2000  * will be notified, carrying the new resource as the data argument.
2001  *
2002  * \memberof wl_client
2003  */
2004 WL_EXPORT void
wl_client_add_resource_created_listener(struct wl_client * client,struct wl_listener * listener)2005 wl_client_add_resource_created_listener(struct wl_client *client,
2006 					struct wl_listener *listener)
2007 {
2008 	wl_priv_signal_add(&client->resource_created_signal, listener);
2009 }
2010 
2011 struct wl_resource_iterator_context {
2012 	void *user_data;
2013 	wl_client_for_each_resource_iterator_func_t it;
2014 };
2015 
2016 static enum wl_iterator_result
resource_iterator_helper(void * res,void * user_data,uint32_t flags)2017 resource_iterator_helper(void *res, void *user_data, uint32_t flags)
2018 {
2019 	struct wl_resource_iterator_context *context = user_data;
2020 	struct wl_resource *resource = res;
2021 
2022 	return context->it(resource, context->user_data);
2023 }
2024 
2025 /** Iterate over all the resources of a client
2026  *
2027  * \param client The client object
2028  * \param iterator The iterator function
2029  * \param user_data The user data pointer
2030  *
2031  * The function pointed by \a iterator will be called for each
2032  * resource owned by the client. The \a user_data will be passed
2033  * as the second argument of the iterator function.
2034  * If the \a iterator function returns \a WL_ITERATOR_CONTINUE the iteration
2035  * will continue, if it returns \a WL_ITERATOR_STOP it will stop.
2036  *
2037  * Creating and destroying resources while iterating is safe, but new
2038  * resources may or may not be picked up by the iterator.
2039  *
2040  * \sa wl_iterator_result
2041  *
2042  * \memberof wl_client
2043  */
2044 WL_EXPORT void
wl_client_for_each_resource(struct wl_client * client,wl_client_for_each_resource_iterator_func_t iterator,void * user_data)2045 wl_client_for_each_resource(struct wl_client *client,
2046 			    wl_client_for_each_resource_iterator_func_t iterator,
2047 			    void *user_data)
2048 {
2049 	struct wl_resource_iterator_context context = {
2050 		.user_data = user_data,
2051 		.it = iterator,
2052 	};
2053 
2054 	wl_map_for_each(&client->objects, resource_iterator_helper, &context);
2055 }
2056 
2057 /** \cond INTERNAL */
2058 
2059 /** Initialize a wl_priv_signal object
2060  *
2061  * wl_priv_signal is a safer implementation of a signal type, with the same API
2062  * as wl_signal, but kept as a private utility of libwayland-server.
2063  * It is safer because listeners can be removed from within wl_priv_signal_emit()
2064  * without corrupting the signal's list.
2065  *
2066  * Before passing a wl_priv_signal object to any other function it must be
2067  * initialized by using wl_priv_signal_init().
2068  *
2069  * \memberof wl_priv_signal
2070  */
2071 void
wl_priv_signal_init(struct wl_priv_signal * signal)2072 wl_priv_signal_init(struct wl_priv_signal *signal)
2073 {
2074 	wl_list_init(&signal->listener_list);
2075 	wl_list_init(&signal->emit_list);
2076 }
2077 
2078 /** Add a listener to a signal
2079  *
2080  * The new listener will be called when calling wl_signal_emit(). If a listener is
2081  * added to the signal while wl_signal_emit() is running it will be called from
2082  * the next time wl_priv_signal_emit() is called.
2083  * To remove a listener call wl_list_remove() on its link member.
2084  *
2085  * \memberof wl_priv_signal
2086  */
2087 void
wl_priv_signal_add(struct wl_priv_signal * signal,struct wl_listener * listener)2088 wl_priv_signal_add(struct wl_priv_signal *signal, struct wl_listener *listener)
2089 {
2090 	wl_list_insert(signal->listener_list.prev, &listener->link);
2091 }
2092 
2093 /** Get a listener added to a signal
2094  *
2095  * Returns the listener added to the given \a signal and with the given
2096  * \a notify function, or NULL if there isn't any.
2097  * Calling this function from within wl_priv_signal_emit() is safe and will
2098  * return the correct value.
2099  *
2100  * \memberof wl_priv_signal
2101  */
2102 struct wl_listener *
wl_priv_signal_get(struct wl_priv_signal * signal,wl_notify_func_t notify)2103 wl_priv_signal_get(struct wl_priv_signal *signal, wl_notify_func_t notify)
2104 {
2105 	struct wl_listener *l;
2106 
2107 	wl_list_for_each(l, &signal->listener_list, link)
2108 		if (l->notify == notify)
2109 			return l;
2110 	wl_list_for_each(l, &signal->emit_list, link)
2111 		if (l->notify == notify)
2112 			return l;
2113 
2114 	return NULL;
2115 }
2116 
2117 /** Emit the signal, calling all the installed listeners
2118  *
2119  * Iterate over all the listeners added to this \a signal and call
2120  * their \a notify function pointer, passing on the given \a data.
2121  * Removing or adding a listener from within wl_priv_signal_emit()
2122  * is safe.
2123  */
2124 void
wl_priv_signal_emit(struct wl_priv_signal * signal,void * data)2125 wl_priv_signal_emit(struct wl_priv_signal *signal, void *data)
2126 {
2127 	struct wl_listener *l;
2128 	struct wl_list *pos;
2129 
2130 	wl_list_insert_list(&signal->emit_list, &signal->listener_list);
2131 	wl_list_init(&signal->listener_list);
2132 
2133 	/* Take every element out of the list and put them in a temporary list.
2134 	 * This way, the 'it' func can remove any element it wants from the list
2135 	 * without troubles, because we always get the first element, not the
2136 	 * one after the current, which may be invalid.
2137 	 * wl_list_for_each_safe tries to be safe but it fails: it works fine
2138 	 * if the current item is removed, but not if the next one is. */
2139 	while (!wl_list_empty(&signal->emit_list)) {
2140 		pos = signal->emit_list.next;
2141 		l = wl_container_of(pos, l, link);
2142 
2143 		wl_list_remove(pos);
2144 		wl_list_insert(&signal->listener_list, pos);
2145 
2146 		l->notify(l, data);
2147 	}
2148 }
2149 
2150 /** Emit the signal for the last time, calling all the installed listeners
2151  *
2152  * Iterate over all the listeners added to this \a signal and call
2153  * their \a notify function pointer, passing on the given \a data.
2154  * Removing or adding a listener from within wl_priv_signal_emit()
2155  * is safe, as is freeing the structure containing the listener.
2156  *
2157  * A large body of external code assumes it's ok to free a destruction
2158  * listener without removing that listener from the list.  Mixing code
2159  * that acts like this and code that doesn't will result in list
2160  * corruption.
2161  *
2162  * We resolve this by removing each item from the list and isolating it
2163  * in another list.  We discard it completely after firing the notifier.
2164  * This should allow interoperability between code that unlinks its
2165  * destruction listeners and code that just frees structures they're in.
2166  *
2167  */
2168 void
wl_priv_signal_final_emit(struct wl_priv_signal * signal,void * data)2169 wl_priv_signal_final_emit(struct wl_priv_signal *signal, void *data)
2170 {
2171 	struct wl_listener *l;
2172 	struct wl_list *pos;
2173 
2174 	/* During a destructor notifier isolate every list item before
2175 	 * notifying.  This renders harmless the long standing misuse
2176 	 * of freeing listeners without removing them, but allows
2177 	 * callers that do choose to remove them to interoperate with
2178 	 * ones that don't. */
2179 	while (!wl_list_empty(&signal->listener_list)) {
2180 		pos = signal->listener_list.next;
2181 		l = wl_container_of(pos, l, link);
2182 
2183 		wl_list_remove(pos);
2184 		wl_list_init(pos);
2185 
2186 		l->notify(l, data);
2187 	}
2188 }
2189 
2190 /** \endcond INTERNAL */
2191 
2192 /** \cond */ /* Deprecated functions below. */
2193 
2194 uint32_t
2195 wl_client_add_resource(struct wl_client *client,
2196 		       struct wl_resource *resource) WL_DEPRECATED;
2197 
2198 WL_EXPORT uint32_t
wl_client_add_resource(struct wl_client * client,struct wl_resource * resource)2199 wl_client_add_resource(struct wl_client *client,
2200 		       struct wl_resource *resource)
2201 {
2202 	if (resource->object.id == 0) {
2203 		resource->object.id =
2204 			wl_map_insert_new(&client->objects,
2205 					  WL_MAP_ENTRY_LEGACY, resource);
2206 	} else if (wl_map_insert_at(&client->objects, WL_MAP_ENTRY_LEGACY,
2207 				  resource->object.id, resource) < 0) {
2208 		wl_resource_post_error(client->display_resource,
2209 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
2210 				       "invalid new id %d",
2211 				       resource->object.id);
2212 		return 0;
2213 	}
2214 
2215 	resource->client = client;
2216 	wl_signal_init(&resource->deprecated_destroy_signal);
2217 
2218 	return resource->object.id;
2219 }
2220 
2221 struct wl_resource *
2222 wl_client_add_object(struct wl_client *client,
2223 		     const struct wl_interface *interface,
2224 		     const void *implementation,
2225 		     uint32_t id, void *data) WL_DEPRECATED;
2226 
2227 WL_EXPORT struct wl_resource *
wl_client_add_object(struct wl_client * client,const struct wl_interface * interface,const void * implementation,uint32_t id,void * data)2228 wl_client_add_object(struct wl_client *client,
2229 		     const struct wl_interface *interface,
2230 		     const void *implementation, uint32_t id, void *data)
2231 {
2232 	struct wl_resource *resource;
2233 
2234 	resource = wl_resource_create(client, interface, -1, id);
2235 	if (resource == NULL)
2236 		wl_client_post_no_memory(client);
2237 	else
2238 		wl_resource_set_implementation(resource,
2239 					       implementation, data, NULL);
2240 
2241 	return resource;
2242 }
2243 
2244 struct wl_resource *
2245 wl_client_new_object(struct wl_client *client,
2246 		     const struct wl_interface *interface,
2247 		     const void *implementation, void *data) WL_DEPRECATED;
2248 
2249 WL_EXPORT struct wl_resource *
wl_client_new_object(struct wl_client * client,const struct wl_interface * interface,const void * implementation,void * data)2250 wl_client_new_object(struct wl_client *client,
2251 		     const struct wl_interface *interface,
2252 		     const void *implementation, void *data)
2253 {
2254 	struct wl_resource *resource;
2255 
2256 	resource = wl_resource_create(client, interface, -1, 0);
2257 	if (resource == NULL)
2258 		wl_client_post_no_memory(client);
2259 	else
2260 		wl_resource_set_implementation(resource,
2261 					       implementation, data, NULL);
2262 
2263 	return resource;
2264 }
2265 
2266 struct wl_global *
2267 wl_display_add_global(struct wl_display *display,
2268 		      const struct wl_interface *interface,
2269 		      void *data, wl_global_bind_func_t bind) WL_DEPRECATED;
2270 
2271 WL_EXPORT struct wl_global *
wl_display_add_global(struct wl_display * display,const struct wl_interface * interface,void * data,wl_global_bind_func_t bind)2272 wl_display_add_global(struct wl_display *display,
2273 		      const struct wl_interface *interface,
2274 		      void *data, wl_global_bind_func_t bind)
2275 {
2276 	return wl_global_create(display, interface, interface->version, data, bind);
2277 }
2278 
2279 void
2280 wl_display_remove_global(struct wl_display *display,
2281 			 struct wl_global *global) WL_DEPRECATED;
2282 
2283 WL_EXPORT void
wl_display_remove_global(struct wl_display * display,struct wl_global * global)2284 wl_display_remove_global(struct wl_display *display, struct wl_global *global)
2285 {
2286 	wl_global_destroy(global);
2287 }
2288 
2289 /** \endcond */
2290 
2291 /* Functions at the end of this file are deprecated.  Instead of adding new
2292  * code here, add it before the comment above that states:
2293  * Deprecated functions below.
2294  */
2295