]> git.saurik.com Git - apple/system_cmds.git/blob - dirhelper.tproj/dirhelper.c
e92533297721b442338fbc9af50eb3e12806cffc
[apple/system_cmds.git] / dirhelper.tproj / dirhelper.c
1 /*
2 * Copyright (c) 2006-2007 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <fts.h>
30 #include <pthread.h>
31 #include <pwd.h>
32 #include <unistd.h>
33 #include <sys/stat.h>
34 #include <sys/sysctl.h>
35 #include <sys/time.h>
36
37 #include <mach/mach.h>
38 #include <mach/mach_error.h>
39 #include <servers/bootstrap.h>
40
41 #include <bsm/libbsm.h>
42
43 #include <asl.h>
44 #include <membership.h>
45 #include <launch.h>
46 #include <dirhelper_priv.h>
47
48 #include "dirhelper_server.h"
49
50 // globals for idle exit
51 struct idle_globals {
52 mach_port_t mp;
53 long timeout;
54 struct timeval lastmsg;
55 };
56
57 struct idle_globals idle_globals;
58
59 void* idle_thread(void* param __attribute__((unused)));
60
61 int file_check(const char* path, int mode, int uid, int gid);
62 #define is_file(x) file_check((x), S_IFREG, -1, -1)
63 #define is_directory(x) file_check((x), S_IFDIR, -1, -1)
64 #define is_root_wheel_directory(x) file_check((x), S_IFDIR, 0, 0)
65
66 int is_safeboot(void);
67
68 void clean_files_older_than(const char* path, time_t when);
69 void clean_directory(const char* name, int);
70
71 kern_return_t
72 do___dirhelper_create_user_local(
73 mach_port_t server_port __attribute__((unused)),
74 audit_token_t au_tok)
75 {
76 int res = 0;
77 uid_t euid;
78 gid_t gid = 0;
79 struct passwd* pwd = NULL;
80
81 gettimeofday(&idle_globals.lastmsg, NULL);
82
83 audit_token_to_au32(au_tok,
84 NULL, // audit uid
85 &euid, // euid
86 NULL, // egid
87 NULL, // ruid
88 NULL, // rgid
89 NULL, // remote_pid
90 NULL, // asid
91 NULL); // aud_tid_t
92
93 // Look-up the primary gid of the user. We'll use this for chown(2)
94 // so that the created directory is owned by a group that the user
95 // belongs to, avoiding warnings if files are moved outside this dir.
96 pwd = getpwuid(euid);
97 if (pwd) gid = pwd->pw_gid;
98
99 do { // begin block
100 char path[PATH_MAX];
101 char *next;
102
103 if (__user_local_dirname(euid, DIRHELPER_USER_LOCAL, path, sizeof(path)) == NULL) {
104 asl_log(NULL, NULL, ASL_LEVEL_ERR,
105 "__user_local_dirname: %s", strerror(errno));
106 break;
107 }
108
109 //
110 // 1. Starting with VAR_FOLDERS_PATH, make each subdirectory
111 // in path, ignoring failure if it already exists.
112 // 2. Change ownership of directory to the user.
113 //
114 next = path + strlen(VAR_FOLDERS_PATH);
115 while ((next = strchr(next, '/')) != NULL) {
116 *next = 0; // temporarily truncate
117 res = mkdir(path, 0755);
118 if (res != 0 && errno != EEXIST) {
119 asl_log(NULL, NULL, ASL_LEVEL_ERR,
120 "mkdir(%s): %s", path, strerror(errno));
121 break;
122 }
123 *next++ = '/'; // restore the slash and increment
124 }
125 if(next || res) // an error occurred
126 break;
127 res = chown(path, euid, gid);
128 if (res != 0) {
129 asl_log(NULL, NULL, ASL_LEVEL_ERR,
130 "chown(%s): %s", path, strerror(errno));
131 }
132 } while(0); // end block
133 return KERN_SUCCESS;
134 }
135
136 kern_return_t
137 do___dirhelper_idle_exit(
138 mach_port_t server_port __attribute__((unused)),
139 audit_token_t au_tok __attribute__((unused))) {
140
141 struct timeval now;
142 gettimeofday(&now, NULL);
143 long delta = now.tv_sec - idle_globals.lastmsg.tv_sec;
144 if (delta >= idle_globals.timeout) {
145 asl_log(NULL, NULL, ASL_LEVEL_DEBUG,
146 "idle exit after %ld seconds", delta);
147 exit(EXIT_SUCCESS);
148 }
149
150 return KERN_SUCCESS;
151 }
152
153 void*
154 idle_thread(void* param __attribute__((unused))) {
155 for(;;) {
156 struct timeval now;
157 gettimeofday(&now, NULL);
158 long delta = (now.tv_sec - idle_globals.lastmsg.tv_sec);
159 if (delta < idle_globals.timeout) {
160 // sleep for remainder of timeout
161 sleep(idle_globals.timeout - delta);
162 } else {
163 // timeout has elapsed, attempt to idle exit
164 __dirhelper_idle_exit(idle_globals.mp);
165 }
166 }
167 return NULL;
168 }
169
170 // If when == 0, all files are removed. Otherwise, only regular files older than when.
171 void
172 clean_files_older_than(const char* path, time_t when) {
173 FTS* fts;
174
175 char* path_argv[] = { (char*)path, NULL };
176 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_XDEV, NULL);
177 if (fts) {
178 FTSENT* ent;
179 asl_log(NULL, NULL, ASL_LEVEL_INFO, "Cleaning %s", path);
180 while ((ent = fts_read(fts))) {
181 switch(ent->fts_info) {
182 case FTS_F:
183 case FTS_DEFAULT:
184 // Unlink the file if it has not been accessed since
185 // the specified time. Obtain an exclusive lock so
186 // that we can avoid a race with other processes
187 // attempting to open the file.
188 if (when == 0) {
189 (void)unlink(ent->fts_path);
190 } else if (S_ISREG(ent->fts_statp->st_mode) && ent->fts_statp->st_atime < when) {
191 int fd = open(ent->fts_path, O_RDONLY | O_NONBLOCK);
192 if (fd != -1) {
193 int res = flock(fd, LOCK_EX | LOCK_NB);
194 if (res == 0) {
195 struct stat sb;
196 res = fstat(fd, &sb);
197 if (res == 0 && sb.st_atime < when) {
198 (void)unlink(ent->fts_path);
199 }
200 (void)flock(fd, LOCK_UN);
201 }
202 close(fd);
203 }
204 }
205 break;
206
207 case FTS_SL:
208 case FTS_SLNONE:
209 if (when == 0) {
210 (void)unlink(ent->fts_path);
211 }
212 break;
213
214 case FTS_DP:
215 if (when == 0) {
216 (void)rmdir(ent->fts_path);
217 }
218 break;
219
220 case FTS_ERR:
221 case FTS_NS:
222 asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s: %s", ent->fts_path, strerror(ent->fts_errno));
223 break;
224
225 default:
226 break;
227 }
228 }
229 fts_close(fts);
230 } else {
231 asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s: %s", path, strerror(errno));
232 }
233 }
234
235 int
236 file_check(const char* path, int mode, int uid, int gid) {
237 int check = 1;
238 struct stat sb;
239 if (lstat(path, &sb) == 0) {
240 check = check && ((sb.st_mode & S_IFMT) == mode);
241 check = check && ((sb.st_uid == (uid_t)uid) || uid == -1);
242 check = check && ((sb.st_gid == (gid_t)gid) || gid == -1);
243 } else {
244 if (errno != ENOENT) {
245 asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s: %s", path, strerror(errno));
246 }
247 check = 0;
248 }
249 return check;
250 }
251
252 int
253 is_safeboot(void) {
254 uint32_t sb = 0;
255 size_t sbsz = sizeof(sb);
256
257 if (sysctlbyname("kern.safeboot", &sb, &sbsz, NULL, 0) != 0) {
258 return 0;
259 } else {
260 return (int)sb;
261 }
262 }
263
264 void
265 clean_directory(const char* name, int machineBoot) {
266 DIR* d;
267 time_t when = 0;
268
269 if (!machineBoot) {
270 struct timeval now;
271 long days = 3;
272 const char* str = getenv("CLEAN_FILES_OLDER_THAN_DAYS");
273 if (str) {
274 days = strtol(str, NULL, 0);
275 }
276 (void)gettimeofday(&now, NULL);
277
278 asl_log(NULL, NULL, ASL_LEVEL_INFO, "Cleaning %s older than %ld days", name, days);
279
280 when = now.tv_sec - (days * 60 * 60 * 24);
281 }
282
283 // Look up the boot time
284 struct timespec boottime;
285 size_t len = sizeof(boottime);
286 if (sysctlbyname("kern.boottime", &boottime, &len, NULL, 0) == -1) {
287 asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s: %s", "sysctl kern.boottime", strerror(errno));
288 return;
289 }
290
291 if (!is_root_wheel_directory(VAR_FOLDERS_PATH)) {
292 asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s: %s", VAR_FOLDERS_PATH, "invalid ownership");
293 return;
294 }
295
296 if ((d = opendir(VAR_FOLDERS_PATH))) {
297 struct dirent* e;
298 char path[PATH_MAX];
299
300 // /var/folders/*
301 while ((e = readdir(d))) {
302 if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue;
303
304 snprintf(path, sizeof(path), "%s%s", VAR_FOLDERS_PATH, e->d_name);
305 if (is_root_wheel_directory(path)) {
306 DIR* d2 = opendir(path);
307 if (d2) {
308 struct dirent* e2;
309
310 // /var/folders/*/*
311 while ((e2 = readdir(d2))) {
312 char temporary_items[PATH_MAX];
313 if (strcmp(e2->d_name, ".") == 0 || strcmp(e2->d_name, "..") == 0) continue;
314
315 snprintf(temporary_items, sizeof(temporary_items),
316 "%s/%s/%s", path, e2->d_name, name);
317 if (is_directory(temporary_items)) {
318 // at boot time we clean all files,
319 // otherwise only clean regular files.
320 clean_files_older_than(temporary_items, when);
321 }
322 }
323
324 closedir(d2);
325 } else {
326 asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s: %s", path, strerror(errno));
327 }
328 }
329 }
330
331 closedir(d);
332 } else {
333 asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s: %s", VAR_FOLDERS_PATH, strerror(errno));
334 }
335 }
336
337 int
338 main(int argc, char* argv[]) {
339 mach_msg_size_t mxmsgsz = MAX_TRAILER_SIZE;
340 kern_return_t kr;
341 long idle_timeout = 30; // default 30 second timeout
342
343 // Clean up TemporaryItems directory when launched at boot.
344 // It is safe to clean all file types at this time.
345 if (argc > 1 && strcmp(argv[1], "-machineBoot") == 0) {
346 clean_directory(DIRHELPER_TEMP_STR, 1);
347 clean_directory("TemporaryItems", 1);
348 clean_directory("Cleanup At Startup", 1);
349 if (is_safeboot()) clean_directory(DIRHELPER_CACHE_STR, 1);
350 exit(EXIT_SUCCESS);
351 } else if (argc > 1 && strcmp(argv[1], "-cleanTemporaryItems") == 0) {
352 clean_directory(DIRHELPER_TEMP_STR, 0);
353 clean_directory("TemporaryItems", 0);
354 exit(EXIT_SUCCESS);
355 } else if (argc > 1) {
356 exit(EXIT_FAILURE);
357 }
358
359 launch_data_t config = NULL, checkin = NULL;
360 checkin = launch_data_new_string(LAUNCH_KEY_CHECKIN);
361 config = launch_msg(checkin);
362 if (!config || launch_data_get_type(config) == LAUNCH_DATA_ERRNO) {
363 asl_log(NULL, NULL, ASL_LEVEL_ERR, "launchd checkin failed");
364 exit(EXIT_FAILURE);
365 }
366
367 launch_data_t tmv;
368 tmv = launch_data_dict_lookup(config, LAUNCH_JOBKEY_TIMEOUT);
369 if (tmv) {
370 idle_timeout = launch_data_get_integer(tmv);
371 asl_log(NULL, NULL, ASL_LEVEL_DEBUG,
372 "idle timeout set: %ld seconds", idle_timeout);
373 }
374
375 launch_data_t svc;
376 svc = launch_data_dict_lookup(config, LAUNCH_JOBKEY_MACHSERVICES);
377 if (!svc) {
378 asl_log(NULL, NULL, ASL_LEVEL_ERR, "no mach services");
379 exit(EXIT_FAILURE);
380 }
381
382 svc = launch_data_dict_lookup(svc, DIRHELPER_BOOTSTRAP_NAME);
383 if (!svc) {
384 asl_log(NULL, NULL, ASL_LEVEL_ERR, "no mach service: %s",
385 DIRHELPER_BOOTSTRAP_NAME);
386 exit(EXIT_FAILURE);
387 }
388
389 mach_port_t mp = launch_data_get_machport(svc);
390 if (mp == MACH_PORT_NULL) {
391 asl_log(NULL, NULL, ASL_LEVEL_ERR, "NULL mach service: %s",
392 DIRHELPER_BOOTSTRAP_NAME);
393 exit(EXIT_FAILURE);
394 }
395
396 // insert a send right so we can send our idle exit message
397 kr = mach_port_insert_right(mach_task_self(), mp, mp,
398 MACH_MSG_TYPE_MAKE_SEND);
399 if (kr != KERN_SUCCESS) {
400 asl_log(NULL, NULL, ASL_LEVEL_ERR, "send right failed: %s",
401 mach_error_string(kr));
402 exit(EXIT_FAILURE);
403 }
404
405 // spawn a thread for our idle timeout
406 pthread_t thread;
407 idle_globals.mp = mp;
408 idle_globals.timeout = idle_timeout;
409 gettimeofday(&idle_globals.lastmsg, NULL);
410 pthread_create(&thread, NULL, &idle_thread, NULL);
411
412 // look to see if we have any messages queued. if not, assume
413 // we were launched because of the calendar interval, and attempt
414 // to clean the temporary items.
415 mach_msg_type_number_t status_count = MACH_PORT_RECEIVE_STATUS_COUNT;
416 mach_port_status_t status;
417 kr = mach_port_get_attributes(mach_task_self(), mp,
418 MACH_PORT_RECEIVE_STATUS, (mach_port_info_t)&status, &status_count);
419 if (kr == KERN_SUCCESS && status.mps_msgcount == 0) {
420 clean_directory(DIRHELPER_TEMP_STR, 0);
421 clean_directory("TemporaryItems", 0);
422 }
423
424 // main event loop
425
426 kr = mach_msg_server(dirhelper_server, mxmsgsz, mp,
427 MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT) |
428 MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0));
429 if (kr != KERN_SUCCESS) {
430 asl_log(NULL, NULL, ASL_LEVEL_ERR,
431 "mach_msg_server(mp): %s", mach_error_string(kr));
432 exit(EXIT_FAILURE);
433 }
434
435 exit(EXIT_SUCCESS);
436 }