-
Notifications
You must be signed in to change notification settings - Fork 3
/
kextd_watchvol.c
2377 lines (2046 loc) · 88.3 KB
/
kextd_watchvol.c
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) 2007 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@
*/
/*
* FILE: watchvol.c
* AUTH: Soren Spies (sspies)
* DATE: 5 March 2006
* DESC: watch volumes as they come, go, or are changed, fire rebuilds
* NOTE: everything in this file should happen on the main thread
*
* Here's roughly how it all works.
* 1. sign up for diskarb notifications
* 2. generate a data structure for each incoming comprehensible OS volume
* 2a. set up notifications for all relevant paths on said volume
* [notifications <-> structures]
* (2) uses bootcaches.plist to describe what caches a system needs.
* All top-level keys are assumed required (which means the mkext could
* get fancier in the future if an old-fashioned mkext was still okay).
* If keys exist that can't be understood or don't parse correctly,
* we bail on watching that volume.
*
* 3. intelligently respond to notifications
* 3a. set up a timer to fire so the system has time to settle
* 3b. upon lazy firing, rebuild caches OR copy files to Apple_Boot
* 3c. if someone tries to unmount a BootRoot volume, cancel any timer and check
* 3d. if a locker unlocks happily, cancel any timer and check (TODO)
* 3e. if a locker unlocks unhappily, need to force a check of non-caches? (???)
* 3f. we don't care if the volume is locked; additional kextcaches wait
* (3d) has the effect that the first kextcache effectively triggers the
* second one which copies caches down. It also allows us ... to be
* smart about things like forcing reboots if we booted from staleness.
*
* 4. arbitrate kextcache locks
* 4a. keep a Mach send right to a receive right in the locker
* 4b. detect crashes via CFMachPortInvalidaton callback
* 4c. take success information on unlock
* 4d. if a lock was lost, force a rebuild (XX)?
*
* 5. keep structures up to date
* 5a. clean up when a volume goes away
* 5b. disappear/appear whenever there's a change
*
* 6. reboot stuff: take a big lock; free it only if locker dies
*
* given that we read bootcaches.plist, we don't trust anything in it
* ... but we push the checking off to kextcache, which ensures
* (via dev_t/safecalls) that it is only operating on a single volume and
* not being redirected to other volumes, etc. We have had Security review.
*
* To make sure mkexts have the correct owners, kextd enables owners
* for the duration of kextcache's locks.
*
*/
// system includes
#include <asl.h>
#include <notify.h> // note notify_monitor_file below
#include <string.h> // strerror()
#include <sysexits.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/wait.h> // waitpid(2)
#include <stdlib.h> // daemon(3)
#include <signal.h>
#include <unistd.h> // e.g. execv
#include <bless.h>
#include <CoreFoundation/CoreFoundation.h>
#include <DiskArbitration/DiskArbitration.h>
#include <DiskArbitration/DiskArbitrationPrivate.h>
#include <IOKit/kext/kextmanager_types.h>
#include <IOKit/storage/CoreStorage/CoreStorageUserLib.h> // LVGChanged
#include <IOKit/kext/OSKextPrivate.h>
#ifndef kOSKextLogCacheFlag
#define kOSKextLogCacheFlag kOSKextLogArchiveFlag
#endif // no kOSKextLogCacheFlag
// notifyd SPI
extern uint32_t notify_monitor_file(int token, const char *name, int flags);
extern uint32_t notify_get_event(int token, int *ev, char *buf, int *len);
// project includes
#include "kextd_main.h" // handleSignal()
#include "kextd_watchvol.h" // kextd_watch_volumes
#include "kextd_globals.h" // gClientUID
#include "kextd_usernotification.h" // kextd_raise_notification
#include "bootcaches.h" // struct bootCaches
#include "bootroot.h" // BRBLLogFunc (only, for now)
#include "kextmanager_async.h" // lock_*_reply()
#include "safecalls.h" // sdeepunlink
// constants
#define kAutoUpdateDelay 300
#define kWatchKeyBase "com.apple.system.kextd.fswatch"
#define kWatchSettleTime 5
#define kMaxUpdateFailures 5 // consecutive failures
#define kMaxUpdateAttempts 25 // reset after failure->success
// XXX after 25 successful updates, touching /S/L/E becomes lame
// 6227955 dictates the failure->success reset metric
// should instead detect 25 back-to-back attempts
// 6775045 / 5350761: basic MessageTracer logging
#define kMessageTracerDomainKey "com.apple.message.domain"
#define kMessageTracerSignatureKey "com.apple.message.signature"
#define kMessageTracerResultKey "com.apple.message.result"
#define kMTCachesDomain "com.apple.kext.caches"
#define kMTUpdatedCaches "updatedCaches"
#define kMTBeginShutdownDelay "beginShutdownDelay"
#define kMTEndShutdownDelay "endShutdownDelay"
// the type: struct watchedVol's (struct bootCaches in bootcaches.h)
// created/destroyed with volumes coming/going; stored in sFsysWatchDict
// use notify_set_state on our notifications to point to these objects
struct watchedVol {
// CFUUIDRef volUUID; // DA id (is the key in sFsysWatchDict)
CFRunLoopTimerRef delayer; // non-NULL if something is scheduled
CFMachPortRef lock; // send right to locker's port
CFMutableArrayRef waiters; // reply ports awaiting this volume
int updterrs; // bump when locker reports an error
int updtattempts; // # times kextcache launched (w/o err->noerr)
uint32_t origMntFlags; // mount flags to restore if owners were off
Boolean isBootRoot; // should we try to update helpers?
CFMutableArrayRef tokens; // notify(3) tokens
struct bootCaches *caches; // parsed version of bootcaches.plist
// XX should track the PID of any launched kextcache (5736801)
};
// module-wide data
static DASessionRef sDASession = NULL; // learn about volumes
static DAApprovalSessionRef sDAApproval = NULL; // retain volumes
static CFMachPortRef sFsysChangedPort = NULL; // let us know
static CFRunLoopSourceRef sFsysChangedSource = NULL; // on the runloop
static CFMutableDictionaryRef sFsysWatchDict = NULL; // disk ids -> wstruct*s
static CFMutableDictionaryRef sReplyPorts = NULL; // cfports -> replyPorts
static CFMachPortRef sRebootLock = NULL; // sys lock for reboot
static CFMachPortRef sRebootWaiter = NULL; // only need one
static CFRunLoopTimerRef sAutoUpdateDelayer = NULL; // avoid boot / movie
/*
* For historical reasons (avoiding first boot movie, old kextcache -U
* race), kextd waits five minutes before performing automatic updates.
* Once the timer has expiered, vol_appeared() and fsys_changed() will
* trigger updates as needed. 6276173 tracks removal of the fixed delay.
*
* Updates are always performed at shutdown.
*/
// function declarations (kextd_watch_volumes, _stop in watchvol.h)
// ctor/dtors
static struct watchedVol* create_watchedVol(DADiskRef disk);
static void destroy_watchedVol(struct watchedVol *watched);
static CFMachPortRef createWatchedPort(mach_port_t mport, void *ctx);
// volume state
static void vol_appeared(DADiskRef disk, void *ctx);
static void vol_changed(DADiskRef, CFArrayRef keys, void* ctx);
static void vol_disappeared(DADiskRef, void* ctx);
CF_RETURNS_RETAINED static DADissenterRef is_dadisk_busy(DADiskRef, void *ctx);
static Boolean check_vol_busy(struct watchedVol *watched);
// notification processing delay scheme
static void fsys_changed(CFMachPortRef p, void *msg, CFIndex size, void *info);
static void checkScheduleUpdate(struct watchedVol *watched);
static void check_now(CFRunLoopTimerRef timer, void *ctx); // notify timer cb
// check and act
static Boolean check_rebuild(struct watchedVol*); // true if launched
// CFMachPort invalidation callback
static void port_died(CFMachPortRef p, void *info);
// helpers for volume and reboot locking routines
static void checkAutoUpdate(CFRunLoopTimerRef t, void *ctx);
static Boolean reconsiderVolumes(mountpoint_t busyVol);
static Boolean checkAllWatched(mountpoint_t busyVol); // true => work to do
// logging
static void logMTMessage(char *signature, char *result, char *mfmt, ...);
// additional "local" helpers are declared/defined just before use
// utility macros
#define CFRELEASE(x) if (x) { CFRelease(x); x = NULL; }
#if 0
// for testing
#define twrite(msg) write(STDERR_FILENO, msg, sizeof(msg))
static void debug_chld(int signum) __attribute__((unused))
{
int olderrno = errno;
int status;
pid_t childpid;
if (signum != SIGCHLD)
twrite("debug_chld not registered for signal\n");
else
if ((childpid = waitpid(-1, &status, WNOHANG)) == -1)
twrite("DEBUG: SIGCHLD received, but no children available?\n");
else
if (!WIFEXITED(status))
twrite("DEBUG: child quit on signal?\n");
else
if (WEXITSTATUS(status))
twrite("DEBUG: child exited with unhappy status\n");
else
twrite("DEBUG: child exited with happy status\n");
errno = olderrno;
}
#endif
/******************************************************************************
* kextd_watch_volumes sets everything up (on the current runloop)
* cleanup of the file-glabal static objects is done in kextd_stop_volwatch()
*****************************************************************************/
int kextd_watch_volumes(int sourcePriority)
{
int rval;
char *errmsg;
CFRunLoopRef rl;
const void *keyobjs[2] = { kDADiskDescriptionMediaContentKey,
kDADiskDescriptionVolumePathKey };
CFArrayRef dakeys = NULL;
rval = EEXIST;
errmsg = "kextd_watch_volumes() already initialized";
if (sFsysWatchDict) goto finish;
rval = ELAST + 1;
// the callbacks will want to go digging in here, so set it up first
errmsg = "couldn't create data structures";
// sFsysWatchDict keeps track of watched volumes with UUIDs as keys
sFsysWatchDict = CFDictionaryCreateMutable(nil, 0,
&kCFTypeDictionaryKeyCallBacks, NULL); // storing watchedVol*'s
if (!sFsysWatchDict) goto finish;
// We keep two ports for a client; one to for death tracking and one to
// reply when the time comes. sReplyPorts maps between the CF wrapper
// for the death-tracking port and the mach_port_t replyPort.
sReplyPorts = CFDictionaryCreateMutable(nil, 0,
&kCFTypeDictionaryKeyCallBacks, NULL); // storing mach_port_t's
if (!sReplyPorts) goto finish;
errmsg = "error setting up ports and sources";
rl = CFRunLoopGetCurrent();
if (!rl) goto finish;
// change notifications will eventually come in through this port/source
sFsysChangedPort = CFMachPortCreate(nil, fsys_changed, NULL, NULL);
// we have to keep these objects so we can unschedule them later?
if (!sFsysChangedPort) goto finish;
sFsysChangedSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault,
sFsysChangedPort, sourcePriority++);
if (!sFsysChangedSource) goto finish;
CFRunLoopAddSource(rl, sFsysChangedSource, kCFRunLoopDefaultMode);
// in general, being on the runloop means we could be called ...
// and we are thus careful about our ordering. In practice, however,
// we're adding to the current runloop, which means nothing can happen
// until this routine exits (we're on the one and only thread).
/*
* XX need to set up a better match dictionary
* kDADiskDescriptionMediaWritableKey = true
* kDADiskDescriptionVolumeNetworkKey != true
*/
// make sure we have a chance to block unmounts
errmsg = "couldn't set up diskarb sessions";
sDAApproval = DAApprovalSessionCreate(nil);
if (!sDAApproval) goto finish;
DARegisterDiskUnmountApprovalCallback(sDAApproval,
kDADiskDescriptionMatchVolumeMountable, is_dadisk_busy, NULL);
DAApprovalSessionScheduleWithRunLoop(sDAApproval, rl,kCFRunLoopDefaultMode);
// set up the disk arrival session & callbacks
// XX need to investigate custom match dictionaries
sDASession = DASessionCreate(nil);
if (!sDASession) goto finish;
DARegisterDiskAppearedCallback(sDASession,
kDADiskDescriptionMatchVolumeMountable, vol_appeared, NULL);
if (!(dakeys = CFArrayCreate(nil, keyobjs, 2, &kCFTypeArrayCallBacks)))
goto finish;
DARegisterDiskDescriptionChangedCallback(sDASession,
kDADiskDescriptionMatchVolumeMountable, dakeys, vol_changed, NULL);
DARegisterDiskDisappearedCallback(sDASession,
kDADiskDescriptionMatchVolumeMountable, vol_disappeared, NULL);
// we're ready to rumble!
DASessionScheduleWithRunLoop(sDASession, rl, kCFRunLoopDefaultMode);
// 5519500: schedule a timer to re-enable autobuilds and reconsider volumes
// should sign up for IOSystemLoadAdvisory() once it can avoid the movie
sAutoUpdateDelayer = CFRunLoopTimerCreate(kCFAllocatorDefault,
CFAbsoluteTimeGetCurrent() + kAutoUpdateDelay, 0,
0, sourcePriority++, checkAutoUpdate, NULL);
if (!sAutoUpdateDelayer) {
goto finish;
}
CFRunLoopAddTimer(CFRunLoopGetCurrent(), sAutoUpdateDelayer,
kCFRunLoopDefaultMode);
CFRelease(sAutoUpdateDelayer); // later self-invalidation will free
// if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) goto finish;
// errmsg = "couldn't set debug signal handler";
// if (signal(SIGCHLD, debug_chld) == SIG_ERR) goto finish;
errmsg = NULL;
rval = 0;
// volume notifications should start coming in shortly
finish:
if (rval) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"kextd_watch_volumes: %s.", errmsg);
if (rval != EEXIST) kextd_stop_volwatch();
}
if (dakeys) CFRelease(dakeys);
return rval;
}
/******************************************************************************
* 5519500: if appropriate, checkAutoUpdate() enables event-driven updates
* and checks all watched volumes to see if they need updating.
* It doesn't yet use IOSystemLoadAdvisory() since that doesn't avoid movies.
*****************************************************************************/
static void checkAutoUpdate(CFRunLoopTimerRef timer, void *ctx)
{
// assert(timer == sAutoUpdateDelayer)
mountpoint_t ignore;
// one-shot timer self-invalidates, so clear out our reference
// Also, vol_appeared() won't call check_rebuild() until this is clear.
sAutoUpdateDelayer = NULL;
// and check all of the watched volumes for updates
(void)checkAllWatched(ignore);
}
/******************************************************************************
* kextd_stop_volwatch unregisters from everything and cleans up
* - called from watch_volumes to handle partial cleanup
*****************************************************************************/
// to help clear out sFsysWatch
static void free_dict_item(const void* key, const void *val, void *c)
{
destroy_watchedVol((struct watchedVol*)val);
}
// public entry point to this module
void kextd_stop_volwatch()
{
CFRunLoopRef rl;
// runloop cleanup
rl = CFRunLoopGetCurrent();
if (rl && sDASession) DASessionUnscheduleFromRunLoop(sDASession, rl,
kCFRunLoopDefaultMode);
if (rl && sDAApproval) DAApprovalSessionUnscheduleFromRunLoop(sDAApproval,
rl, kCFRunLoopDefaultMode);
// use CFRELEASE to nullify cfrefs in case watch_volumes called again
if (sDASession) {
DAUnregisterCallback(sDASession, vol_disappeared, NULL);
DAUnregisterCallback(sDASession, vol_changed, NULL);
DAUnregisterCallback(sDASession, vol_appeared, NULL);
CFRELEASE(sDASession);
}
if (sDAApproval) {
DAUnregisterApprovalCallback(sDAApproval, is_dadisk_busy, NULL);
CFRELEASE(sDAApproval);
}
if (rl && sFsysChangedSource) CFRunLoopRemoveSource(rl, sFsysChangedSource,
kCFRunLoopDefaultMode);
CFRELEASE(sFsysChangedSource);
CFRELEASE(sFsysChangedPort);
if (sFsysWatchDict) {
CFDictionaryApplyFunction(sFsysWatchDict, free_dict_item, NULL);
CFRELEASE(sFsysWatchDict);
}
return;
}
/******************************************************************************
* destroy_watchedVol unregisters any notification tokens and frees
* pieces created in create_watchedVol
******************************************************************************/
static void destroy_watchedVol(struct watchedVol *watched)
{
CFIndex ntokens;
int token;
int errnum;
// assert that ->delayer, and ->lock have already been cleaned up
if (watched->tokens) {
ntokens = CFArrayGetCount(watched->tokens);
while(ntokens--) {
token = (int)(intptr_t)CFArrayGetValueAtIndex(watched->tokens,ntokens);
// XX should take (hacky) steps to insure token is never zero?
if (/* !token || */ (errnum = notify_cancel(token))) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogIPCFlag,
"destroy_watchedVol: error %d canceling notification on vol '%s'.",
errnum, watched->caches->root);
}
}
CFRelease(watched->tokens);
}
if (watched->caches) destroyCaches(watched->caches);
free(watched);
}
/******************************************************************************
* create_watchedVol calls readCaches and creates watch-specific necessities
******************************************************************************/
static struct watchedVol* create_watchedVol(DADiskRef disk)
{
struct watchedVol *watched, *rval = NULL;
char *errmsg;
errmsg = "allocation error";
watched = calloc(1, sizeof(*watched));
if (!watched) goto finish;
errmsg = NULL; // no bootcaches.plist, no problem
watched->caches = readBootCachesForDADisk(disk); // logs errors
if (!watched->caches) {
goto finish;
}
watched->isBootRoot = hasBootRootBoots(watched->caches, NULL, NULL, NULL);
// get rid of any old bootstamps
if (!watched->isBootRoot) {
(void)updateStamps(watched->caches, kBCStampsUnlinkOnly);
}
// There will be RPS paths, booters, "misc" paths, and the exts folder.
// For now, we'll just set the array size to 0 and let it grow.
errmsg = "allocation error";
watched->tokens = CFArrayCreateMutable(nil, 0, NULL);
if (!watched->tokens) goto finish;
errmsg = NULL;
rval = watched; // success!
finish:
if (errmsg) {
if (watched && watched->caches && watched->caches->root[0]) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"%s: %s.", watched->caches->root, errmsg);
} else {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"create_watchedVol(): %s.", errmsg);
}
}
if (!rval && watched) {
destroy_watchedVol(watched);
}
return rval;
}
// helper: caller must remove port from other structures (e.g. waiters queue)
// The CFRelease() is releasing a CFMachPort created by createWatchedPort().
// While the volume lock waiters queue is a CFArray (which takes its own
// reference), every element has an extra retain count so that we can
// release the non-CF-contained objects here. The analyzer doesn't know
// that and thinks we shouldn't be releasing those references in the case
// where *port = (CFMachPortRef)CFArrayGetValueAtIndex(watched->waiters,i);
static int
cleanupPort(CFMachPortRef *port)
{
mach_port_t lport;
if (sReplyPorts)
CFDictionaryRemoveValue(sReplyPorts, *port); // stop tracking replyPort
CFMachPortSetInvalidationCallBack(*port, NULL); // else port_died called
lport = CFMachPortGetPort(*port);
CFRelease(*port);
*port = NULL;
return mach_port_deallocate(mach_task_self(), lport);
}
// caller responsibile for setting up the lock and cleaning up the waiter
static int signalWaiter(CFMachPortRef waiter, int status)
{
int rval = KERN_FAILURE;
mach_port_t replyPort;
// extract this client's reply port and reply
replyPort=(mach_port_t)(intptr_t)CFDictionaryGetValue(sReplyPorts,waiter);
CFDictionaryRemoveValue(sReplyPorts, waiter);
if (replyPort != MACH_PORT_NULL) {
if (waiter == sRebootWaiter) {
mountpoint_t empty;
rval = lock_reboot_reply(replyPort, KERN_SUCCESS, empty, status);
} else {
rval = lock_volume_reply(replyPort, KERN_SUCCESS, status);
}
}
if (rval) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogIPCFlag,
"signalWaiter failed: %s.",
safe_mach_error_string(rval));
}
return rval;
}
// sRebootWaiter must be set; sRebootLock is released if held
static void handleRebootHandoff()
{
mountpoint_t busyVol;
// make sure everything is clean
// (checkAllWatched() will initiate updates if needed)
if (checkAllWatched(busyVol) == EBUSY) {
OSKextLog(NULL, kOSKextLogWarningLevel | kOSKextLogIPCFlag,
"%s is still busy, delaying reboot.", busyVol);
goto finish;
}
// signal the waiter
if (signalWaiter(sRebootWaiter, KERN_SUCCESS) == 0) {
// on success, make the waiter the locker
sRebootLock = sRebootWaiter;
OSKextLog(NULL, kOSKextLogWarningLevel | kOSKextLogIPCFlag,
"%s up to date; unblocking reboot.", busyVol);
logMTMessage(kMTEndShutdownDelay, "success", "unblocking shutdown");
}
sRebootWaiter = NULL;
finish:
return;
}
// cleans up watched->lock, checks for waiters, assigns the lock, and signals
static void handleWatchedHandoff(struct watchedVol *watched)
{
CFMachPortRef waiter = NULL;
// release existing lock
if (watched->lock)
cleanupPort(&watched->lock);
// see if we have any waiters
// XX should have a loop that can try multiple waiters
if (watched->waiters && CFArrayGetCount(watched->waiters)) {
waiter = (CFMachPortRef)CFArrayGetValueAtIndex(watched->waiters, 0);
// move waiter into the pole position and remove from the array
OSKextLog(NULL, kOSKextLogDebugLevel | kOSKextLogIPCFlag,
"granting lock for %s to waiter %d", watched->caches->root,
CFMachPortGetPort(waiter));
watched->lock = waiter; // context already set to 'watched'
CFArrayRemoveValueAtIndex(watched->waiters, 0);
// signal the waiter, cleaning up on failure
if (signalWaiter(waiter, KERN_SUCCESS)) {
// XX should loop back to try next waiter if this one failed
cleanupPort(&watched->lock); // deallocates former waiter
}
}
}
/******************************************************************************
* vol_appeared checks whether a volume is interesting
* (note: the first time we see a volume, it's probably not mounted yet)
* (we rely on vol_changed to call us when the mountpoint actually appears)
* - signs up for notifications -> creates new entries in our structures
* - initiates an initial volume check
*****************************************************************************/
// set up notifications for a single path
static int watch_path(char *path, mach_port_t port, struct watchedVol* watched)
{
int rval = ELAST + 1; // cheesy
char key[PATH_MAX];
int token = 0;
int errnum;
uint64_t state;
// generate key, register for token, monitor, record pointer in token
if (strlcpy(key, kWatchKeyBase, PATH_MAX) >= PATH_MAX) goto finish;
if (strlcat(key, path, PATH_MAX) >= PATH_MAX) goto finish;
if (notify_register_mach_port(key, &port, NOTIFY_REUSE, &token))
goto finish;
state = (intptr_t)watched;
if (notify_set_state(token, state)) goto finish;
if (notify_monitor_file(token, path, /* flags; 0 means "all" */ 0)) goto finish;
#if 0
OSKextLogCFString(NULL,
kOSKextLogGeneralFlag | kOSKextLogErrorLevel,
CFSTR("%s - watching '%s' "),
__func__, path);
#endif
CFArrayAppendValue(watched->tokens, (void*)(intptr_t)token);
rval = 0;
finish:
if (rval && token != -1 && (errnum = notify_cancel(token)))
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogIPCFlag,
"watch_path: error %d canceling token.", errnum);
return rval;
}
#define WATCH(watched, fullp, relpath, fsPort) do { \
/* MAKEROOTPATH */ \
COMPILE_TIME_ASSERT(sizeof(fullp) == PATH_MAX); \
if (strlcpy(fullp, watched->caches->root, PATH_MAX) >= PATH_MAX) \
goto finish; \
if (strlcat(fullp, relpath, PATH_MAX) >= PATH_MAX) \
goto finish; \
\
if (watch_path(fullp, fsPort, watched)) \
goto finish; \
} while(0)
#define kInstallCommitPath "/private/var/run/installd.commit.pid"
#if DEV_KERNEL_SUPPORT
/******************************************************************************
* watch_kernels gets the parent of the kernel file then enumerates the given
* directory and calls watch_path for each "valid" kernel file in that
* directory. NOTE - "valid" currently means files named "kernel.SUFFIX"
*****************************************************************************/
static void
watch_kernels(
struct watchedVol * watched,
const char * kernelPath,
mach_port_t fsPort )
{
CFURLRef kernelURL = NULL; // must release
CFURLRef kernelsDirURL = NULL; // must release
CFURLEnumeratorRef myEnumerator = NULL; // must release
CFURLRef enumURL = NULL; // do not release
CFStringRef tempCFString = NULL; // must release
CFArrayRef resultArray = NULL; // must release
char tempPath[PATH_MAX];
if (kernelPath == NULL || watched == NULL || watched->caches == NULL) {
goto finish;
}
/* back up to the parent directory and enumerate from there */
if (strlcpy(tempPath,
watched->caches->root,
sizeof(tempPath)) >= sizeof(tempPath))
goto finish;
if (strlcat(tempPath,
kernelPath,
sizeof(tempPath)) >= sizeof(tempPath))
goto finish;
kernelURL = CFURLCreateFromFileSystemRepresentation(
NULL,
(const UInt8 *)tempPath,
strlen(tempPath),
true );
if (kernelURL == NULL) {
goto finish;
}
kernelsDirURL = CFURLCreateCopyDeletingLastPathComponent(NULL, kernelURL );
if (kernelsDirURL == NULL) {
goto finish;
}
// watch /System/Library/Kernels directory
if (CFURLGetFileSystemRepresentation(kernelsDirURL,
true /*resolve*/,
(UInt8*)tempPath,
sizeof(tempPath)) ) {
watch_path(tempPath, fsPort, watched);
}
myEnumerator = CFURLEnumeratorCreateForDirectoryURL(
NULL,
kernelsDirURL,
kCFURLEnumeratorDefaultBehavior,
NULL );
if (myEnumerator == NULL) {
goto finish;
}
while (CFURLEnumeratorGetNextURL(myEnumerator,
&enumURL,
NULL) == kCFURLEnumeratorSuccess) {
// make sure we have a last component and it begins with "kernel."
// NOTE - we are already watching "/S/L/Kernels/kernel"
SAFE_RELEASE_NULL(tempCFString);
tempCFString = CFURLCopyLastPathComponent(enumURL);
if (tempCFString == NULL ||
CFStringHasPrefix(tempCFString, CFSTR("kernel.")) == false) {
continue;
}
// skip "dSYM" suffix - 18098771
if (CFStringHasSuffix(tempCFString,
CFSTR("dSYM"))) {
continue;
}
// skip any kernels with more than 1 '.' character.
// For example: kernel.foo.bar is not a valid kernel name
SAFE_RELEASE_NULL(resultArray);
resultArray = CFStringCreateArrayWithFindResults(
NULL,
tempCFString,
CFSTR("."),
CFRangeMake(0, CFStringGetLength(tempCFString)),
0);
if (resultArray && CFArrayGetCount(resultArray) > 1) {
continue;
}
if (CFURLGetFileSystemRepresentation(enumURL,
true /*resolve*/,
(UInt8*)tempPath,
sizeof(tempPath)) ) {
watch_path(tempPath, fsPort, watched);
}
} // while loop
finish:
SAFE_RELEASE(kernelURL);
SAFE_RELEASE(kernelsDirURL);
SAFE_RELEASE(myEnumerator);
SAFE_RELEASE(tempCFString);
SAFE_RELEASE(resultArray);
return;
}
#endif
static void vol_appeared(DADiskRef disk, void *launchCtx)
{
int result = 0; // for now, ignore inability to get basic data (4528851)
mach_port_t fsPort;
CFDictionaryRef ddesc = NULL;
CFURLRef volURL;
CFBooleanRef traitVal;
CFUUIDRef volUUID;
struct watchedVol *watched = NULL;
Boolean launched = false;
struct bootCaches *caches;
int i;
char path[PATH_MAX];
OSKextLogCFString(NULL, kOSKextLogDebugLevel | kOSKextLogIPCFlag,
CFSTR("%s(%@)"), __FUNCTION__, disk);
// get description so we can see if the disk is writable, etc
if (!disk) goto finish;
ddesc = DADiskCopyDescription(disk);
if (!ddesc) goto finish;
// volUUID is the key in the dictionary (might we already be watching?)
volUUID = CFDictionaryGetValue(ddesc, kDADiskDescriptionVolumeUUIDKey);
if (!volUUID || CFGetTypeID(volUUID) != CFUUIDGetTypeID()) goto finish;
if ((watched = (void *)CFDictionaryGetValue(sFsysWatchDict, volUUID))) {
// until we can use a real vol_changed() [4620558] to update
// 'watched', avoid losing critical data for '/'
if (0 == strcmp(watched->caches->root, "/")) {
OSKextLog(NULL, kOSKextLogWarningLevel | kOSKextLogIPCFlag,
"'/' re-appeared; refusing to lose existing state (8755513) "
"at the risk of missing minor changes (4620558)");
goto finish;
} else {
// X vol_changed() has already handled removing it if needed?
OSKextLog(NULL, kOSKextLogWarningLevel | kOSKextLogIPCFlag,
"WARNING: vol_appeared() removing pre-existing '%s' from"
" watch table.", watched->caches->root);
vol_disappeared(disk, NULL);
}
}
// XX when DA calls vol_appeared(), the volume will always be unmounted ??
volURL = CFDictionaryGetValue(ddesc, kDADiskDescriptionVolumePathKey);
if (!volURL) goto finish; // ignore unmounted volumes
// 7628429: ignore read-only filesystems (which might be on writable media)
if (CFURLGetFileSystemRepresentation(volURL,false,(UInt8*)path,PATH_MAX)) {
struct statfs sfs;
if (statfs(path, &sfs) == -1) goto finish;
if (sfs.f_flags & MNT_RDONLY) goto finish; // ignore r-only
if (sfs.f_flags & MNT_DONTBROWSE) goto finish; // respect nobrowse
} else {
// couldn't get a path, we don't care about this one
goto finish;
}
// check description traits (XX need custom match dict - 4528851)
// with fix for 7628429, not clear we need to check this any more
traitVal = CFDictionaryGetValue(ddesc, kDADiskDescriptionMediaWritableKey);
if (!traitVal || CFGetTypeID(traitVal) != CFBooleanGetTypeID()) goto finish;
if (CFEqual(traitVal, kCFBooleanFalse)) goto finish;
traitVal = CFDictionaryGetValue(ddesc, kDADiskDescriptionVolumeNetworkKey);
if (!traitVal || CFGetTypeID(traitVal) != CFBooleanGetTypeID()) goto finish;
if (CFEqual(traitVal, kCFBooleanTrue)) goto finish;
// does it have a usable bootcaches.plist? (if not, ignore)
if (!(watched = create_watchedVol(disk))) goto finish;
result = -1; // anything after this is an error
caches = watched->caches;
// set up notifications on the change port
fsPort = CFMachPortGetPort(sFsysChangedPort);
if (fsPort == MACH_PORT_NULL) goto finish;
/* for path in { bootcaches.plist, installd.commit.pid, exts, kernel,
* locSrcs, rpspaths[], booters, miscpaths[] }
* rpspaths contains mkext, bootconfig; miscpaths the label file
* cache paths are relative; WATCH() makes absolute */
WATCH(watched, path, kBootCachesPath, fsPort);
WATCH(watched, path, kInstallCommitPath, fsPort);
/* support multiple extensions directories - 11860417 */
char *bufptr;
bufptr = caches->exts;
for (i = 0; i < caches->nexts; i++) {
WATCH(watched, path, bufptr, fsPort);
bufptr += (strlen(bufptr) + 1);
}
// newer systems kernelpath is /System/Library/Kernels/kernel
// older systems kernelpath is /mach_kernel
WATCH(watched, path, caches->kernelpath, fsPort);
#if DEV_KERNEL_SUPPORT
// look for other kernels and watch them too.
if (caches->kernelsCount > 0) {
watch_kernels(watched, caches->kernelpath, fsPort);
// watch any other kernelcache files (kernelcache.SUFFIX)
if (watched->caches->extraKernelCachePaths) {
for (i = 0; i < watched->caches->nekcp; i++) {
WATCH(watched, path, caches->extraKernelCachePaths[i].rpath, fsPort);
}
}
}
#endif
WATCH(watched, path, caches->locSource, fsPort);
WATCH(watched, path, caches->bgImage, fsPort);
// XXX commenting out until 9498428 makes watching this file
// more efficient (and probably replaces locPref with an array).
// WATCH(watched, path, caches->locPref, fsPort);
// loop over RPS paths
for (i = 0; i < caches->nrps; i++) {
WATCH(watched, path, caches->rpspaths[i].rpath, fsPort);
}
if (caches->efibooter.rpath[0]) {
WATCH(watched, path, caches->efibooter.rpath, fsPort);
}
if (caches->ofbooter.rpath[0]) {
WATCH(watched, path, caches->ofbooter.rpath, fsPort);
}
// loop over misc paths
for (i = 0; i < caches->nmisc; i++) {
WATCH(watched, path, caches->miscpaths[i].rpath, fsPort);
}
// we handled any pre-existing entry for volUUID above
CFDictionarySetValue(sFsysWatchDict, volUUID, watched);
// if startup delay hasn't yet passed, skip the usual checks & updates
if (sAutoUpdateDelayer) {
OSKextLog(NULL, kOSKextLogDetailLevel | kOSKextLogDirectoryScanFlag,
"ignoring '%s' until boot is complete",
watched->caches->root);
} else {
launched = check_rebuild(watched);
}
// reconsiderVolume() uses launchCtx to get its return value
if (launchCtx) {
Boolean *didLaunch = launchCtx;
*didLaunch = launched;
}
result = 0; // we made it
finish:
if (ddesc) CFRelease(ddesc);
if (result) {
if (watched) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"Error setting up notifications on '%s'.",
watched->caches->root);
destroy_watchedVol(watched);
}
}
return;
}
#undef WATCH
/******************************************************************************
* vol_changed updates our structures if the mountpoint changed
* - includes the initial mount after a device appears
* - thus we only call appeared and disappeared as appropriate
*
* Multiple notifications fire multiple times as disks come and go.
* Depending on how predictable it is, we might be able to get away
* with just using vol_changed to see when the volume is mounted.
*****************************************************************************/
static void
check_boots_set_nvram(struct watchedVol *watched)
{
char *volbsdname = watched->caches->bsdname;
CFArrayRef dparts, bparts;
Boolean hasBoots;
Boolean curSDPreferred = true; // XXX 8011916
char *s;
CFStringRef firstPart;
char bsdName[DEVMAXPATHSIZE];
BLContext blctx = { 0, BRBLLogFunc, NULL };
// logs errors
hasBoots = hasBootRootBoots(watched->caches, &bparts, &dparts, NULL);
if (!bparts || !dparts) goto finish;
s = (CFArrayGetCount(bparts) == 1) ? "" : "s";
if (hasBoots) {
if (!watched->isBootRoot) {
// gained Apple_Boot partition(s)
OSKextLog(NULL, kOSKextLogWarningLevel | kOSKextLogGeneralFlag,
"%s now has Apple_Boot partition%s", volbsdname, s);
watched->isBootRoot = true;
check_rebuild(watched);
// and if it was the root volume, re-point NVRAM
if (0 == strcmp(watched->caches->root, "/") && curSDPreferred) {
firstPart = CFArrayGetValueAtIndex(bparts, 0);
if (!firstPart) goto finish;
if (CFStringGetFileSystemRepresentation(firstPart, bsdName,
DEVMAXPATHSIZE)) {
(void)BLSetEFIBootDevice(&blctx, bsdName);
}
}