-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathnotify_client.c
More file actions
4752 lines (4061 loc) · 146 KB
/
Copy pathnotify_client.c
File metadata and controls
4752 lines (4061 loc) · 146 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2003-2012 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/ipc.h>
#include <sys/signal.h>
#include <sys/syslimits.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/mman.h>
#include <sys/fcntl.h>
#include <sys/fileport.h>
#include <sys/time.h>
#include <bootstrap_priv.h>
#include <errno.h>
#include <stdatomic.h>
#include <os/alloc_once_private.h>
#include <os/lock_private.h>
#include <os/reason_private.h>
#include <os/variant_private.h>
#include <os/log_simple_private.h>
#include <TargetConditionals.h>
#include <AvailabilityMacros.h>
#include <Block.h>
#include <dispatch/dispatch.h>
#include <dispatch/private.h>
#include <xpc/private.h>
#include <_simple.h>
#include <mach-o/dyld_priv.h> // _dyld_is_memory_immutable
#include "libnotify.h"
#include "notify.h"
#include "notify_internal.h"
#include "notify_ipc.h"
#include "notify_private.h"
#include "notify_probes.h"
#ifdef DEBUG
#define DEBUG_REGISTRATION 0x00000001
#define DEBUG_NOTIFICATION 0x00000002
#define DEBUG_RETAIN_RELEASE 0x00000004
#define DEBUG_CANCEL 0x00000008
#define DEBUG_GET_STATE 0x00000010
#define DEBUG_SEND_NO_BLOCK 0x00000020
#define DEBUG_NODES 0x00000040
#define DEBUG_API 0x00000080
#define DEBUG_USER 0x80000000
#define DEBUG_ALL 0xffffffff
static uint32_t _libnotify_debug = DEBUG_ALL;
#endif /* DEBUG */
#define EVENT_INIT 0
#define EVENT_REGEN 1
#define SELF_PREFIX "self."
#define SELF_PREFIX_LEN 5
#define COMMON_SELF_PORT_KEY "self.com.apple.system.notify.common"
#define LOOPBACK_MODE_ENTITLEMENT "com.apple.developer.web-browser-engine.restrict.notifyd"
#define INTROSPECTION_ENTITLEMENT "com.apple.private.darwin-notification.introspect"
#define INTROSPECTION_NAME_PREFIX_CHAR '*'
#define MULTIPLE_REGISTRATION_WARNING_TRIGGER 500
#define NID_UNSET 0xffffffffffffffffL
#define NID_CALLED_ONCE 0xfffffffffffffffeL
// If connection to notifyd tries, we retry a total of
// NOTIFY_SERVER_RETRY_NUMBER times, waiting in between each attempt for
// NOTIFY_SERVER_RETRY_WAIT_US microseconds.
#define NOTIFY_SERVER_RETRY_WAIT_US 100000
#define NOTIFY_SERVER_RETRY_NUMBER 50
#define notification_name_is_self(name) \
(!strncmp(name, SELF_PREFIX, SELF_PREFIX_LEN) || notification_loopback_mode_enabled())
#define assert_loopback_disabled() \
if(os_unlikely(notification_loopback_mode_enabled())) \
{ \
NOTIFY_CLIENT_CRASH(0, "loopback mode enabled but process wants to IPC to notifyd"); \
}
#define notification_introspection_expect_exempt(name) \
if(os_unlikely(!_notification_introspection_is_exempt(name))) {\
simulate_crash("LIBNOTIFY INTROSPECT: registering for non-exempt notification %s", name);\
}
#define LIBNOTIFY_LOGGING_ENVVAR "DarwinNotificationLogging"
#define __notify_log(fmt, lvl, ...) \
os_log_simple_with_subsystem(OS_LOG_SIMPLE_TYPE_ ## lvl, "com.apple.libnotify", fmt, ##__VA_ARGS__)
#define _notify_log_debug(fmt, ...) __notify_log(fmt, DEBUG, ##__VA_ARGS__)
#define _notify_log(fmt, ...) __notify_log(fmt, DEFAULT, ##__VA_ARGS__)
#define NOTIFY_LOG(name, fmt, ...) \
{ \
if (_notify_log_enabled(name)) { \
_notify_log("[%s] " fmt, name, ##__VA_ARGS__); \
} \
}
/*
* Details about registrations, tokens, dispatch (NOTIFY_OPT_DISPATCH), IPC versions, and etc.
*
* In the first versions of the client/server protocol (ipc versions 0 and 1), the integer
* token representing a registration was generated by notifyd and returned to the client
* as an out parameter in the MIG registration call.
*
* If a client uses the old protocols, then each registration in the client goes straight to
* the server. If the client registers for signals, file descriptor writes, or whatever,
* that's all handled by the server.
*
* The current version (ipc version 2) has better performance. The client now generates
* a unique token (simply incremented by 1 for each new registration) and sends it to
* notifyd in a MIG simpleroutine. notifyd internally uses a 64 bit ID for each registration
* that's formed from the client's PID (high-order 32 bits) and the client-provided integer
* (low-order 32 bits).
*
* With the advent of libdispatch, there was an opportunity to further improve performance
* and reduce the load on notifyd. The client library (this source file) checks if the
* client process is multithreaded, or at least can be multithreaded, with a call to the
* _dispatch_is_multithreaded() routine. This tells us if we can use dispatch in the client.
*
* If the client can use dispatch (NOTIFY_OPT_DISPATCH gets set in globals->client_opts),
* then all registrations use a single shared mach port (globals->notify_common_port).
* The client creates a dispatch source (globals->notify_dispatch_source) that handles all
* notifications from the server. The handler routine looks up the client's registration
* for the received notification and sends a signal, writes on a file descriptor, or sends
* a mach message as required. It's all done locally in the client process.
*
* Many clients register several times for the same notification name. That's sometimes
* due to bad code, but it may be legitimate as well. For example, different libraries or
* frameworks may register independently, or different threads in a client process may
* each require a registration for the same name. When dispatch is available, client
* registrations for the same name are coalesced. The library still generates a new
* token (and an underlying token data structure) for each registration, but only the
* first registration is actually sent to notifyd. Subsequent registrations are simply
* chained to the first in a linked list. When the globals->notify_dispatch_source
* handler processes a notification from the server, it traverses the linked list and
* forwards the notification to each.
*
* Note that it is possible for the client to still have multiple registrations with
* notifyd, even when coalescing. Polled registrations (memory or plain) must be handled
* by notifyd, so these registration types are not coalesced. Also, a client might start
* out single threaded and appear not to be dispatch-safe, but them become multi-threaded
* later on. Early registrations would go individually to notifyd, while later
* registrations would be coalesced.
*
* The library uses both locking and refcounting of data structures. A mutex in the
* library globals (globals->notify_lock) is used when accessing mutable values, hash
* tables, and lists that are found in the global data (returned by _notify_globals()).
* Data structure instances (name_node_t and registration_node_t types) are refcounted.
* name_node_t instances have locks to protect their data. registration_node_t
* instances do not, mostly to save memory. Most operations on them can either be done
* atomically, or are within the scope of some other lock.
*/
typedef struct
{
uint64_t name_id;
TAILQ_HEAD(, __registration_node_s) coalesced;
struct __registration_node_s *coalesce_base;
char *name;
os_unfair_lock lock;
atomic_uint_fast32_t refcount;
uint32_t coalesce_base_token;
bool has_been_warned;
bool needs_free;
} name_node_t;
/*
* Data structure behind a client's token.
* The library exports tokens (integers) to users of the library, so
* notify_register_...() gives the client an int value that represents
* a registration.
*
* If the client registers multiple times for the same name and we can
* use dispatch in the library, then the duplicate registration creates
* a new client-side registration, but not a new registration with the
* server. Multiple registrations are chained in a linked list. The
* base registration is retained for each coalesced registration.
*/
typedef struct __registration_node_s
{
TAILQ_ENTRY(__registration_node_s) registration_coalesced_entry;
atomic_uint_fast32_t refcount;
uint32_t token;
uint32_t flags;
/* shared memory slot and value at that location when we last did notify_check() */
uint32_t slot;
uint32_t val;
/* client-facing parts of a notification */
int fd;
int signal_or_xtra_mp;
mach_port_t mp;
dispatch_queue_t queue;
notify_handler_t block;
/* client_id is the value returned from notifyd for registrations using IPC version 0 */
uint32_t client_id;
/* state value and timestamp when we set it - used to regenerate if notifyd restarts */
uint64_t set_state_val;
uint64_t set_state_time;
/* path monitoring */
char *path;
int path_flags;
/* name table node for this registration */
name_node_t *name_node;
} registration_node_t;
/* FORWARD */
static void _notify_lib_server_restart_handler(void *ctxt);
static void notify_retain_mach_port(notify_globals_t globals, mach_port_t mp, int flags);
static void _notify_dispatch_handle(void *context);
static void registration_node_release(registration_node_t *r);
static void registration_node_release_locked(notify_globals_t globals, registration_node_t *r);
static void notify_release_file_descriptor_locked(notify_globals_t globals, int fd);
static void notify_release_mach_port_locked(notify_globals_t globals, mach_port_t mp, uint32_t flags);
static uint32_t notify_register_coalesced_registration(const char *name, int flags, int *out_token, notify_globals_t globals, mach_port_t extra_mp);
static bool notification_loopback_mode_enabled(void);
static bool _notification_introspection_is_exempt(const char *);
static bool _notify_log_enabled(const char *);
static registration_node_t * registration_node_find(uint32_t token);
// TSAN doesn't know about os_unfair_lock_with_options
#if defined(__has_feature)
#if __has_feature(thread_sanitizer)
#define TSAN_SAFE_LOCK(x) os_unfair_lock_lock(x)
#else
#define TSAN_SAFE_LOCK(x) os_unfair_lock_lock_with_options(x, OS_UNFAIR_LOCK_DATA_SYNCHRONIZATION)
#endif // __has_feature(thread_sanitizer)
#else
#define TSAN_SAFE_LOCK(x) os_unfair_lock_lock(x)
#endif // defined(__clang__)
#ifdef DEBUG_MUTEX
#define mutex_lock(s,x,f,l) \
_notify_client_log(ASL_LEVEL_NOTICE, "attempting mutex lock %s %p from %s:%u", s, x, f, l); \
TSAN_SAFE_LOCK(x); \
_notify_client_log(ASL_LEVEL_NOTICE, "acquired mutex lock %s %p from %s:%u", s, x, f, l);
#define mutex_unlock(s,x,f,l) \
_notify_client_log(ASL_LEVEL_NOTICE, "dropping mutex lock %s %p from %s:%u", s, x, f, l); \
os_unfair_lock_unlock(x);
#else
#define mutex_lock(s,x,f,l) TSAN_SAFE_LOCK(x)
#define mutex_unlock(s,x,f,l) os_unfair_lock_unlock(x)
#endif
// returns the result after the decrement
inline static int32_t
atomic_refcount_release(atomic_uint_fast32_t *val)
{
int32_t result = os_atomic_dec(val, release);
// Crash right away if we underrun our refcounts
// as this indicates a bug in our logic
assert(result >= 0);
// result == 0 means that this was the last reference so any changes
// made to the refcounted object need to be visible to all threads
// at this point. c.f. "Release-Acquire ordering" at
// http://en.cppreference.com/w/cpp/atomic/memory_order
if (result == 0) os_atomic_thread_fence(acquire);
return result;
}
// returns the result after the increment
inline static int32_t
atomic_increment32(atomic_uint_fast32_t *val)
{
return os_atomic_inc(val, relaxed);
}
inline static void
name_node_retain(name_node_t *node)
{
atomic_increment32(&node->refcount);
}
inline static void
registration_node_retain(registration_node_t *reg)
{
atomic_increment32(®->refcount);
}
inline static uint32_t
client_opts(notify_globals_t globals)
{
return os_atomic_load(&globals->client_opts, relaxed);
}
__printflike(2, 3)
static void
_notify_client_log(int level, const char *fmt, ...)
{
va_list ap;
char *msg = NULL;
va_start(ap, fmt);
vasprintf(&msg, fmt, ap);
va_end(ap);
if (msg != NULL)
{
_simple_asl_log(level, "com.apple.notify", msg);
#ifdef DEBUG_VERBOSE
fprintf(stderr, "thread %p: %s\n", (void *)pthread_self(), msg);
#endif
}
free(msg);
}
#if !TARGET_OS_SIMULATOR && !TARGET_OS_OSX
#define REPORT_BAD_BEHAVIOR(...) \
if(os_variant_has_internal_diagnostics("libnotify.simulate_crash")) \
{ \
_simulate_crash(__VA_ARGS__); \
} else { \
_notify_client_log(ASL_LEVEL_ERR, __VA_ARGS__); \
} \
(void)0 // This allows ; after the macro and the compiler will optimize it out
#else /* !TARGET_OS_SIMULATOR && !TARGET_OS_OSX */
#define REPORT_BAD_BEHAVIOR(...) _notify_client_log(ASL_LEVEL_ERR, __VA_ARGS__)
#endif /* !TARGET_OS_SIMULATOR && !TARGET_OS_OSX */
static char *
_notify_strdup_if_mutable(const char *str, bool *needs_free)
{
size_t size = strlen(str) + 1;
if (!_dyld_is_memory_immutable(str, size)) {
char *clone = (char *)malloc(size);
if (clone) {
memcpy(clone, str, size);
if (needs_free) *needs_free = true;
}
return clone;
}
if (needs_free) *needs_free = false;
return (char *)str;
}
#pragma mark -
#pragma mark globals
#define INITIAL_TOKEN_ID 1
#define NUM_LOGGED_WRONG_CANARY 3
#if 64 < CANARY_COUNT
#error CANARY_COUNT too large to be represented in bitvector in _check_canary()
#endif
#if CANARY_COUNT < NUM_LOGGED_WRONG_CANARY
#error NUM_LOGGED_WRONG_CANARY too large; set equal to or lower than CANARY_COUNT
#endif
static const uint64_t canary_const = 0xAAAAaaaaAAAAaaaaULL;
/*
* Initialization of global variables. Called once per process.
*/
static void
_notify_init_globals(void * /* notify_globals_t */ _globals)
{
notify_globals_t globals = _globals;
for (uint64_t idx = 0; idx < CANARY_COUNT; idx += 1) {
globals->canary[idx] = canary_const;
}
globals->notify_lock = OS_UNFAIR_LOCK_INIT;
os_atomic_store(&globals->token_id, INITIAL_TOKEN_ID, relaxed);
globals->notify_common_token = -1;
globals->check_lock = OS_UNFAIR_LOCK_INIT;
_nc_table_init(&globals->name_node_table, offsetof(name_node_t, name));
_nc_table_init_n(&globals->registration_table, offsetof(registration_node_t, token));
_notify_lib_notify_state_init(&globals->self_state, NOTIFY_STATE_USE_LOCKS);
}
static inline void
_check_canary(notify_globals_t globals) {
uint64_t ne_bits = 0;
size_t cnt = 0;
uint64_t wrong[NUM_LOGGED_WRONG_CANARY];
for (size_t idx = 0; idx < CANARY_COUNT; idx += 1) {
uint64_t canary = globals->canary[idx];
if (os_unlikely(canary_const != canary)) {
ne_bits |= (1ULL << idx);
if (cnt == 0) {
memset(wrong, 0, sizeof(wrong));
}
if (cnt < NUM_LOGGED_WRONG_CANARY) {
wrong[cnt] = canary;
cnt += 1;
}
}
}
if (ne_bits != 0) {
REPORT_BAD_BEHAVIOR("BUG IN LIBNOTIFY CLIENT: internal data structure corrupted [0x%04llx, 0x%llx, 0x%llx, 0x%llx]]", ne_bits, wrong[0], wrong[1], wrong[2]);
// Reset canary to (1) avoid further reports of this corruption, and (2) detect the next corruption.
for (uint64_t idx = 0; idx < CANARY_COUNT; idx += 1) {
globals->canary[idx] = canary_const;
}
}
}
__attribute__((__pure__))
static inline notify_globals_t
_notify_globals(void)
{
notify_globals_t globals = (notify_globals_t)os_alloc_once(OS_ALLOC_ONCE_KEY_LIBSYSTEM_NOTIFY,
sizeof(struct notify_globals_s), &_notify_init_globals);
static uintptr_t _globals_lookup_counter = 0;
_globals_lookup_counter += 1;
if ((_globals_lookup_counter & 0x3) == 0) {
_check_canary(globals);
}
return globals;
}
#pragma mark -
#pragma mark Old IPC base support
// XXX HACK - these subsets of the header don't namespace according to the userprefix
#define __Request__notify_old_ipc_subsystem__defined
#define __Reply__notify_old_ipc_subsystem__defined
#include "notify_old_ipc.h"
#ifndef _ipc_base_call
#define _ipc_base_call(routine, ...) \
_new_ipc_base##routine(__VA_ARGS__)
#endif
// Note: there's no need to add new routines here, as notifyd versions using the
// old base won't support them anyway.
#define _notify_server_check(...) _ipc_base_call(_notify_server_check, ##__VA_ARGS__)
#define _notify_server_get_state(...) _ipc_base_call(_notify_server_get_state, ##__VA_ARGS__)
#define _notify_server_suspend(...) _ipc_base_call(_notify_server_suspend, ##__VA_ARGS__)
#define _notify_server_resume(...) _ipc_base_call(_notify_server_resume, ##__VA_ARGS__)
#define _notify_server_suspend_pid(...) _ipc_base_call(_notify_server_suspend_pid, ##__VA_ARGS__)
#define _notify_server_resume_pid(...) _ipc_base_call(_notify_server_resume_pid, ##__VA_ARGS__)
#define _notify_server_post_2(...) _ipc_base_call(_notify_server_post_2, ##__VA_ARGS__)
#define _notify_server_post_3(...) _ipc_base_call(_notify_server_post_3, ##__VA_ARGS__)
#define _notify_server_post_4(...) _ipc_base_call(_notify_server_post_4, ##__VA_ARGS__)
#define _notify_server_register_plain_2(...) _ipc_base_call(_notify_server_register_plain_2, ##__VA_ARGS__)
#define _notify_server_register_check_2(...) _ipc_base_call(_notify_server_register_check_2, ##__VA_ARGS__)
#define _notify_server_register_signal_2(...) _ipc_base_call(_notify_server_register_signal_2, ##__VA_ARGS__)
#define _notify_server_register_file_descriptor_2(...) _ipc_base_call(_notify_server_register_file_descriptor_2, ##__VA_ARGS__)
#define _notify_server_register_mach_port_2(...) _ipc_base_call(_notify_server_register_mach_port_2, ##__VA_ARGS__)
#define _notify_server_cancel_2(...) _ipc_base_call(_notify_server_cancel_2, ##__VA_ARGS__)
#define _notify_server_get_state_2(...) _ipc_base_call(_notify_server_get_state_2, ##__VA_ARGS__)
#define _notify_server_get_state_3(...) _ipc_base_call(_notify_server_get_state_3, ##__VA_ARGS__)
#define _notify_server_set_state_2(...) _ipc_base_call(_notify_server_set_state_2, ##__VA_ARGS__)
#define _notify_server_set_state_3(...) _ipc_base_call(_notify_server_set_state_3, ##__VA_ARGS__)
#define _notify_server_monitor_file_2(...) _ipc_base_call(_notify_server_monitor_file_2, ##__VA_ARGS__)
#define _notify_server_regenerate(...) _ipc_base_call(_notify_server_regenerate, ##__VA_ARGS__)
#define _notify_server_checkin(...) _ipc_base_call(_notify_server_checkin, ##__VA_ARGS__)
#define _notify_server_dump(...) _ipc_base_call(_notify_server_dump, ##__VA_ARGS__)
#define _notify_generate_common_port(...) _ipc_base_call(_notify_generate_common_port, ##__VA_ARGS__)
#define _notify_server_register_common_port(...) _ipc_base_call(_notify_server_register_common_port, ##__VA_ARGS__)
#define _notify_server_register_mach_port_3(...) _ipc_base_call(_notify_server_register_mach_port_3, ##__VA_ARGS__)
#define _filtered_notify_server_checkin(...) _ipc_base_call(_filtered_notify_server_checkin, ##__VA_ARGS__)
#define _filtered_notify_server_post(...) _ipc_base_call(_filtered_notify_server_post, ##__VA_ARGS__)
#define _filtered_notify_server_regenerate(...) _ipc_base_call(_filtered_notify_server_regenerate, ##__VA_ARGS__)
#define _filtered_notify_server_set_state_2(...) _ipc_base_call(_filtered_notify_server_set_state_2, ##__VA_ARGS__)
#define _filtered_notify_server_set_state_3(...) _ipc_base_call(_filtered_notify_server_set_state_3, ##__VA_ARGS__)
#pragma mark -
#pragma mark name_node_t
#ifdef NOTDEF
static void
name_node_dump(int level, name_node_t *n)
{
if (n == NULL)
{
_notify_client_log(level, "name_node_t NULL\n");
return;
}
_notify_client_log(level, "name_node_t %p name=%s name_id=%llu refcount=%d coalesce_base_token=%u coalesce_base=%p\n", (n->name == NULL) ? "NULL" : n->name, n->name_id, n->refcount, n->coalesce_base_token, n->coalesce_base);
}
#endif
// must be called with the global lock held
static name_node_t *
name_node_for_name_locked(notify_globals_t globals, const char *name, uint64_t nid, bool create)
{
os_unfair_lock_assert_owner(&globals->notify_lock);
if (name == NULL) return NULL;
name_node_t *n = _nc_table_find(&globals->name_node_table, name);
if (n != NULL)
{
name_node_retain(n);
}
else if (create)
{
n = (name_node_t *)calloc(1, sizeof(name_node_t));
if (n == NULL)
{
#ifdef DEBUG
_notify_client_log(ASL_LEVEL_ERR, "name_node_for_name name %s calloc failed errno %d [%s]\n", name, errno, strerror(errno));
#endif
goto done;
}
n->name = _notify_strdup_if_mutable(name, &n->needs_free);
if (n->name == NULL)
{
free(n);
n = NULL;
goto done;
}
os_atomic_store(&n->refcount, 1, relaxed);
n->name_id = nid;
TAILQ_INIT(&n->coalesced);
n->coalesce_base_token = NOTIFY_TOKEN_INVALID;
n->lock = OS_UNFAIR_LOCK_INIT;
n->has_been_warned = false;
_nc_table_insert(&globals->name_node_table, &n->name);
}
done:
#ifdef DEBUG
if (_libnotify_debug & DEBUG_NODES)
{
if (n == NULL) _notify_client_log(ASL_LEVEL_NOTICE, "name_node_for_name name %s returning NULL\n", name);
else _notify_client_log(ASL_LEVEL_NOTICE, "name_node_for_name name %s refcount %d %p\n", n->name, n->refcount, n);
}
#endif
return n;
}
static name_node_t *
name_node_for_name(const char *name, uint64_t nid, bool create)
{
notify_globals_t globals = _notify_globals();
mutex_lock("global", &globals->notify_lock, __func__, __LINE__);
name_node_t *node = name_node_for_name_locked(globals, name, nid, create);
mutex_unlock("global", &globals->notify_lock, __func__, __LINE__);
return node;
}
// must be called with the global lock held
static void
name_node_delete_locked(notify_globals_t globals, name_node_t *n)
{
os_unfair_lock_assert_owner(&globals->notify_lock);
/* refcount is zero, free the node */
#ifdef DEBUG
if (_libnotify_debug & DEBUG_NODES) _notify_client_log(ASL_LEVEL_NOTICE, "name_node_release name %s refcount %d %p FREE", n->name, n->refcount, n);
#endif
_nc_table_delete(&globals->name_node_table, n->name, &n->name);
if (n->needs_free) {
free(n->name);
}
n->name = NULL;
free(n);
}
// must be called with the global lock held
static void
name_node_release_locked(notify_globals_t globals, name_node_t *n)
{
os_unfair_lock_assert_owner(&globals->notify_lock);
if (n == NULL) return;
if (atomic_refcount_release(&n->refcount) > 0)
{
#ifdef DEBUG
if (_libnotify_debug & DEBUG_NODES) _notify_client_log(ASL_LEVEL_NOTICE, "%s name %s refcount %d %p", __func__, n->name, n->refcount, n);
#endif
return;
}
name_node_delete_locked(globals, n);
}
static void
name_node_unlock_and_release(name_node_t *n)
{
if (n == NULL) return;
mutex_unlock(n->name, &n->lock, __func__, __LINE__);
notify_globals_t globals = _notify_globals();
mutex_lock("global", &globals->notify_lock, __func__, __LINE__);
if (atomic_refcount_release(&n->refcount) > 0)
{
#ifdef DEBUG
if (_libnotify_debug & DEBUG_NODES) _notify_client_log(ASL_LEVEL_NOTICE, "%s name %s refcount %d %p", __func__, n->name, n->refcount, n);
#endif
mutex_unlock("global", &globals->notify_lock, __func__, __LINE__);
return;
}
name_node_delete_locked(globals, n);
mutex_unlock("global", &globals->notify_lock, __func__, __LINE__);
}
// We avoid an extra retain here if the base registration was just created
static void
name_node_add_coalesced_registration_locked(name_node_t *n, registration_node_t *r, bool skip_retain)
{
if (n == NULL) return;
if (r == NULL) return;
os_unfair_lock_assert_owner(&n->lock);
if (!skip_retain && n->coalesce_base) registration_node_retain(n->coalesce_base);
TAILQ_INSERT_TAIL(&n->coalesced, r, registration_coalesced_entry);
}
// must be called with the global lock held
static void
name_node_remove_coalesced_registration_locked(notify_globals_t globals, name_node_t *n, registration_node_t *r)
{
os_unfair_lock_assert_owner(&globals->notify_lock);
if (n == NULL) return;
if (r == NULL) return;
mutex_lock(n->name, &n->lock, __func__, __LINE__);
TAILQ_REMOVE(&n->coalesced, r, registration_coalesced_entry);
mutex_unlock(n->name, &n->lock, __func__, __LINE__);
registration_node_release_locked(globals, n->coalesce_base);
}
static void
name_node_set_nid_locked(name_node_t *n, uint64_t nid)
{
os_unfair_lock_assert_owner(&n->lock);
n->name_id = nid;
}
static void
name_node_set_nid(name_node_t *n, uint64_t nid)
{
if (n == NULL) return;
mutex_lock(n->name, &n->lock, __func__, __LINE__);
name_node_set_nid_locked(n, nid);
mutex_unlock(n->name, &n->lock, __func__, __LINE__);
}
#pragma mark -
#pragma mark registration_node_t
static registration_node_t *
registration_node_find(uint32_t token)
{
notify_globals_t globals = _notify_globals();
mutex_lock("global", &globals->notify_lock, __func__, __LINE__);
registration_node_t *r = _nc_table_find_n(&globals->registration_table, token);
if (r != NULL) registration_node_retain(r);
mutex_unlock("global", &globals->notify_lock, __func__, __LINE__);
#ifdef DEBUG
if (_libnotify_debug & DEBUG_NODES) _notify_client_log(ASL_LEVEL_NOTICE, "registration_node_find token %u refcount %d -> %p", token, r ? r->refcount : -1, r);
#endif
return r;
}
/*
* Tells the caller if a value is a valid token number.
* Internal coalesce_base registration tokens are reported as invalid,
* since clients should not be mucking around with them.
*/
bool
notify_is_valid_token(int val)
{
#ifdef DEBUG
if (_libnotify_debug & DEBUG_API) _notify_client_log(ASL_LEVEL_NOTICE, "-> %s\n", __func__);
#endif
bool valid = true;
notify_globals_t globals = _notify_globals();
mutex_lock("global", &globals->notify_lock, __func__, __LINE__);
registration_node_t *r = _nc_table_find_n(&globals->registration_table, val);
if (r == NULL) valid = false;
else if (r->flags & NOTIFY_FLAG_COALESCE_BASE) valid = false;
mutex_unlock("global", &globals->notify_lock, __func__, __LINE__);
#ifdef DEBUG
if (_libnotify_debug & DEBUG_API) _notify_client_log(ASL_LEVEL_NOTICE, "<- %s [%d]\n", __func__, __LINE__ + 2);
#endif
return valid;
}
// must be called with the global lock held
static void
registration_node_free_locked(notify_globals_t globals, registration_node_t *r)
{
os_unfair_lock_assert_owner(&globals->notify_lock);
name_node_t *n = r->name_node;
NOTIFY_LOG(n->name, "canceling notification: token=%d flags=0x%x", r->token, r->flags);
if (r->flags & NOTIFY_FLAG_COALESCED)
{
name_node_remove_coalesced_registration_locked(globals, n, r);
}
else if (r->flags & NOTIFY_FLAG_COALESCE_BASE)
{
mutex_lock(n->name, &n->lock, __func__, __LINE__);
n->coalesce_base_token = NOTIFY_TOKEN_INVALID;
n->coalesce_base = NULL;
mutex_unlock(n->name, &n->lock, __func__, __LINE__);
/* cancel the registration with notifyd */
#ifdef DEBUG
if (_libnotify_debug & DEBUG_CANCEL) _notify_client_log(ASL_LEVEL_NOTICE, "_notify_server_cancel_2 token %u", r->token);
#endif
// hold lock across async server call
(void)_notify_server_cancel_2(globals->notify_server_port, r->token);
}
notify_release_file_descriptor_locked(globals, r->fd);
notify_release_mach_port_locked(globals, r->mp, r->flags);
if(((r->flags & NOTIFY_TYPE_MASK) == NOTIFY_TYPE_COMMON_PORT) && (r->signal_or_xtra_mp != MACH_PORT_NULL)) {
notify_release_mach_port_locked(globals, (mach_port_t)r->signal_or_xtra_mp, r->flags | NOTIFY_FLAG_RELEASE_SEND);
}
free(r->path);
if (r->block != NULL) dispatch_async_f(r->queue, r->block, (dispatch_function_t)_Block_release);
r->block = NULL;
if (r->queue != NULL) dispatch_release(r->queue);
r->queue = NULL;
free(r);
name_node_release_locked(globals, n);
}
// must be called with the global lock held
static void
registration_node_delete_locked(notify_globals_t globals, registration_node_t *r)
{
os_unfair_lock_assert_owner(&globals->notify_lock);
/* refcount is zero, free the node */
#ifdef DEBUG
if (_libnotify_debug & DEBUG_NODES) _notify_client_log(ASL_LEVEL_NOTICE, "%s token %u refcount %d flags 0x%08x %p FREE", __func__, r->token, r->refcount, r->flags, r);
#endif
_nc_table_delete_n(&globals->registration_table, r->token, &r->token);
uint32_t reg_token = r->token;
uint32_t reg_flags = r->flags;
registration_node_free_locked(globals, r);
if (reg_flags & NOTIFY_FLAG_SELF)
{
/*
* _notify_lib_cancel fails quietly if self_state is NULL
* We let it fail quietly.
*/
_notify_lib_cancel(&globals->self_state, NOTIFY_CLIENT_SELF, reg_token);
#ifdef DEBUG
if (_libnotify_debug & DEBUG_API) _notify_client_log(ASL_LEVEL_NOTICE, "<- %s [%d]\n", __func__, __LINE__ + 2);
#endif
return;
}
assert_loopback_disabled();
if (reg_flags & NOTIFY_FLAG_COALESCE_BASE)
{
#ifdef DEBUG
if (_libnotify_debug & DEBUG_CANCEL) _notify_client_log(ASL_LEVEL_NOTICE, "notify_cancel token %d NOTIFY_FLAG_COALESCE_BASE", reg_token);
#endif
#ifdef DEBUG
if (_libnotify_debug & DEBUG_API) _notify_client_log(ASL_LEVEL_NOTICE, "<- %s [%d]\n", __func__, __LINE__ + 2);
#endif
return;
}
kern_return_t kstatus = KERN_SUCCESS;
if ((reg_flags & NOTIFY_FLAG_COALESCED) == 0)
{
// hold lock across async server call
kstatus = _notify_server_cancel_2(globals->notify_server_port, reg_token);
}
#ifdef DEBUG
if (_libnotify_debug & DEBUG_CANCEL) _notify_client_log(ASL_LEVEL_NOTICE, "notify_cancel token %d reg_node %p has been cancelled", reg_token, r);
#endif
if ((kstatus == MIG_SERVER_DIED) || (kstatus == MACH_SEND_INVALID_DEST))
{
#ifdef DEBUG
if (_libnotify_debug & DEBUG_API) _notify_client_log(ASL_LEVEL_NOTICE, "<- %s [%d]\n", __func__, __LINE__ + 2);
#endif
return;
}
else if (kstatus != KERN_SUCCESS)
{
#ifdef DEBUG
if (_libnotify_debug & DEBUG_API) _notify_client_log(ASL_LEVEL_NOTICE, "<- %s [%d]\n", __func__, __LINE__ + 2);
#endif
_notify_client_log(ASL_LEVEL_ERR, "<- %s [%d] _notify_server_cancel_2 failed: 0x%08x\n", __func__, __LINE__ + 2, kstatus);
return;
}
#ifdef DEBUG
if (_libnotify_debug & DEBUG_API) _notify_client_log(ASL_LEVEL_NOTICE, "<- %s [%d]\n", __func__, __LINE__ + 2);
#endif
}
static void
registration_node_release(registration_node_t *r)
{
notify_globals_t globals = _notify_globals();
mutex_lock("global", &globals->notify_lock, __func__, __LINE__);
registration_node_release_locked(globals, r);
mutex_unlock("global", &globals->notify_lock, __func__, __LINE__);
}
static void
registration_node_release_locked(notify_globals_t globals, registration_node_t *r)
{
os_unfair_lock_assert_owner(&globals->notify_lock);
if (r == NULL) return;
if (atomic_refcount_release(&r->refcount) > 0)
{
#ifdef DEBUG
if (_libnotify_debug & DEBUG_NODES) _notify_client_log(ASL_LEVEL_NOTICE, "%s token %u refcount %d flags 0x%08x %p", __func__, r->token, r->refcount, r->flags, r);
#endif
return;
}
registration_node_delete_locked(globals, r);
}
#if !TARGET_OS_SIMULATOR
static bool
shm_attach(uint32_t size)
{
int32_t shmfd;
notify_globals_t globals = _notify_globals();
void *shm_base = NULL;
bool result = true;
shmfd = shm_open(SHM_ID, O_RDONLY, 0);
if (shmfd == -1)
{
// Do not simulated crash on sandbox violation.
if (errno != EPERM) {
REPORT_BAD_BEHAVIOR("Libnotify: %s failed on line %d with errno %d", __func__, __LINE__, errno);
}
return false;
}
shm_base = mmap(NULL, size, PROT_READ, MAP_SHARED, shmfd, 0);
if (shm_base == MAP_FAILED) {
REPORT_BAD_BEHAVIOR("Libnotify: %s failed on line %d with errno %d", __func__, __LINE__, errno);
result = false;
} else {
globals->shm_base = shm_base;
result = true;
}
close(shmfd);
return result;
}
#endif /* TARGET_OS_SIMULATOR */
#ifdef NOTDEF
static void
shm_detach(void)
{
if (shm_base != NULL)
{
shmdt(shm_base);
shm_base = NULL;
}
}
#endif
static void
_notify_lib_set_common_port(notify_globals_t globals, mach_port_t mp)
{
globals->notify_common_port = mp;
globals->notify_dispatch_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, mp, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
dispatch_set_context(globals->notify_dispatch_source, globals);
dispatch_source_set_event_handler_f(globals->notify_dispatch_source, _notify_dispatch_handle);
dispatch_source_set_cancel_handler(globals->notify_dispatch_source, ^{
mach_port_destruct(mach_task_self(), mp, 0, 0);
});
dispatch_resume(globals->notify_dispatch_source);
}
static bool
_notify_log_enabled(const char *name) {
notify_globals_t globals = _notify_globals();
if (!globals->logging) {
return false;
}
if (globals->logging->global) {
return true;
}
return os_set_find(&globals->logging->notifications, name) != NULL;
}
static struct _notify_logging_s _notify_logging_global =
{
.global = true,
.notifications = {NULL}
};
static struct _notify_logging_s *
_notify_lib_init_logging(void) {
if (!os_variant_has_internal_diagnostics("com.apple.libnotify")) {
return NULL;
}
const char *logging = getenv(LIBNOTIFY_LOGGING_ENVVAR);
if (logging == NULL) {
return NULL;
}
if (strcmp(logging, "1") == 0) {
_notify_log("enabled logging for all notifications");
return &_notify_logging_global;
} else {
struct _notify_logging_s *result = calloc(1, sizeof(struct _notify_logging_s));
result->global = false;
os_set_init(&result->notifications, NULL);
char *notification_str = strdup(logging);
for (char *lasts, *n = strtok_r(notification_str, ",", &lasts);
n != NULL; n = strtok_r(NULL, ",", &lasts)) {
struct _str_container_s {
const char *str;
};
struct _str_container_s *strcntr = calloc(1, sizeof(struct _str_container_s));
strcntr->str = strdup(n);