1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/common/service_process_util_posix.h"
7 #import <Foundation/Foundation.h>
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/files/file_path.h"
15 #include "base/mac/bundle_locations.h"
16 #include "base/mac/foundation_util.h"
17 #include "base/mac/mac_util.h"
18 #include "base/mac/scoped_nsautorelease_pool.h"
19 #include "base/mac/scoped_nsobject.h"
20 #include "base/metrics/histogram_macros.h"
21 #include "base/path_service.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/strings/sys_string_conversions.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/version.h"
27 #include "chrome/common/chrome_paths.h"
28 #include "chrome/common/chrome_switches.h"
29 #include "chrome/common/mac/launchd.h"
30 #include "components/version_info/version_info.h"
31 #include "ipc/unix_domain_socket_util.h"
33 using ::base::FilePathWatcher;
37 #define kServiceProcessSessionType "Aqua"
39 CFStringRef CopyServiceProcessLaunchDName() {
40 base::mac::ScopedNSAutoreleasePool pool;
41 NSBundle* bundle = base::mac::FrameworkBundle();
42 return CFStringCreateCopy(kCFAllocatorDefault,
43 base::mac::NSToCFCast([bundle bundleIdentifier]));
46 NSString* GetServiceProcessLaunchDLabel() {
47 base::scoped_nsobject<NSString> name(
48 base::mac::CFToNSCast(CopyServiceProcessLaunchDName()));
49 NSString* label = [name stringByAppendingString:@".service_process"];
50 base::FilePath user_data_dir;
51 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
52 std::string user_data_dir_path = user_data_dir.value();
53 NSString* ns_path = base::SysUTF8ToNSString(user_data_dir_path);
54 ns_path = [ns_path stringByReplacingOccurrencesOfString:@" "
56 label = [label stringByAppendingString:ns_path];
60 NSString* GetServiceProcessLaunchDSocketKey() {
61 return @"ServiceProcessSocket";
64 bool GetParentFSRef(const FSRef& child, FSRef* parent) {
65 return FSGetCatalogInfo(&child, 0, NULL, NULL, NULL, parent) == noErr;
68 bool RemoveFromLaunchd() {
69 // We're killing a file.
70 base::ThreadRestrictions::AssertIOAllowed();
71 base::ScopedCFTypeRef<CFStringRef> name(CopyServiceProcessLaunchDName());
72 return Launchd::GetInstance()->DeletePlist(Launchd::User,
77 class ExecFilePathWatcherCallback {
79 ExecFilePathWatcherCallback() {}
80 ~ExecFilePathWatcherCallback() {}
82 bool Init(const base::FilePath& path);
83 void NotifyPathChanged(const base::FilePath& path, bool error);
86 FSRef executable_fsref_;
89 base::FilePath GetServiceProcessSocketName() {
90 base::FilePath socket_name;
91 PathService::Get(base::DIR_TEMP, &socket_name);
92 std::string pipe_name = GetServiceProcessScopedName("srv");
93 socket_name = socket_name.Append(pipe_name);
94 UMA_HISTOGRAM_CUSTOM_COUNTS("CloudPrint.ServiceProcessSocketLength",
95 socket_name.value().size(), 75, 124, 50);
96 if (socket_name.value().size() < IPC::kMaxSocketNameLength)
98 // Fallback to /tmp if $TMPDIR is too long.
99 // TODO(vitalybuka): Investigate how often we get there.
100 // See http://crbug.com/466644
101 return base::FilePath("/tmp").Append(pipe_name);
106 IPC::ChannelHandle GetServiceProcessChannel() {
107 base::FilePath socket_name = GetServiceProcessSocketName();
108 VLOG(1) << "ServiceProcessChannel: " << socket_name.value();
109 return IPC::ChannelHandle(socket_name.value());
112 bool ForceServiceProcessShutdown(const std::string& /* version */,
113 base::ProcessId /* process_id */) {
114 base::mac::ScopedNSAutoreleasePool pool;
115 CFStringRef label = base::mac::NSToCFCast(GetServiceProcessLaunchDLabel());
116 CFErrorRef err = NULL;
117 bool ret = Launchd::GetInstance()->RemoveJob(label, &err);
119 DLOG(ERROR) << "ForceServiceProcessShutdown: " << err << " "
120 << base::SysCFStringRefToUTF8(label);
126 bool GetServiceProcessData(std::string* version, base::ProcessId* pid) {
127 base::mac::ScopedNSAutoreleasePool pool;
128 CFStringRef label = base::mac::NSToCFCast(GetServiceProcessLaunchDLabel());
129 base::scoped_nsobject<NSDictionary> launchd_conf(
130 base::mac::CFToNSCast(Launchd::GetInstance()->CopyJobDictionary(label)));
131 if (!launchd_conf.get()) {
134 // Anything past here will return true in that there does appear
135 // to be a service process of some sort registered with launchd.
138 NSString* exe_path = [launchd_conf objectForKey:@ LAUNCH_JOBKEY_PROGRAM];
140 NSString* bundle_path = [[[exe_path stringByDeletingLastPathComponent]
141 stringByDeletingLastPathComponent]
142 stringByDeletingLastPathComponent];
143 NSBundle* bundle = [NSBundle bundleWithPath:bundle_path];
145 NSString* ns_version =
146 [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
148 *version = base::SysNSStringToUTF8(ns_version);
150 DLOG(ERROR) << "Unable to get version at: "
151 << reinterpret_cast<CFStringRef>(bundle_path);
154 // The bundle has been deleted out from underneath the registered
156 DLOG(ERROR) << "Unable to get bundle at: "
157 << reinterpret_cast<CFStringRef>(bundle_path);
160 DLOG(ERROR) << "Unable to get executable path for service process";
165 NSNumber* ns_pid = [launchd_conf objectForKey:@ LAUNCH_JOBKEY_PID];
167 *pid = [ns_pid intValue];
173 bool ServiceProcessState::Initialize() {
174 CFErrorRef err = NULL;
175 CFDictionaryRef dict =
176 Launchd::GetInstance()->CopyDictionaryByCheckingIn(&err);
178 DLOG(ERROR) << "ServiceProcess must be launched by launchd. "
179 << "CopyLaunchdDictionaryByCheckingIn: " << err;
183 state_->launchd_conf.reset(dict);
187 IPC::ChannelHandle ServiceProcessState::GetServiceProcessChannel() {
189 NSDictionary* ns_launchd_conf = base::mac::CFToNSCast(state_->launchd_conf);
190 NSDictionary* socket_dict =
191 [ns_launchd_conf objectForKey:@ LAUNCH_JOBKEY_SOCKETS];
193 [socket_dict objectForKey:GetServiceProcessLaunchDSocketKey()];
194 DCHECK_EQ([sockets count], 1U);
195 int socket = [[sockets objectAtIndex:0] intValue];
196 base::FileDescriptor fd(socket, false);
197 return IPC::ChannelHandle(std::string(), fd);
200 bool CheckServiceProcessReady() {
203 if (!GetServiceProcessData(&version, &pid)) {
206 Version service_version(version);
208 if (!service_version.IsValid()) {
211 Version running_version(version_info::GetVersionNumber());
212 if (!running_version.IsValid()) {
213 // Our own version is invalid. This is an error case. Pretend that we
217 } else if (running_version.CompareTo(service_version) > 0) {
224 ForceServiceProcessShutdown(version, pid);
229 CFDictionaryRef CreateServiceProcessLaunchdPlist(base::CommandLine* cmd_line,
230 bool for_auto_launch) {
231 base::mac::ScopedNSAutoreleasePool pool;
234 base::SysUTF8ToNSString(cmd_line->GetProgram().value());
236 std::vector<std::string> args = cmd_line->argv();
237 NSMutableArray* ns_args = [NSMutableArray arrayWithCapacity:args.size()];
239 for (std::vector<std::string>::iterator iter = args.begin();
242 [ns_args addObject:base::SysUTF8ToNSString(*iter)];
245 NSString* socket_name =
246 base::SysUTF8ToNSString(GetServiceProcessSocketName().value());
248 NSDictionary* socket =
249 [NSDictionary dictionaryWithObject:socket_name
250 forKey:@LAUNCH_JOBSOCKETKEY_PATHNAME];
251 NSDictionary* sockets =
252 [NSDictionary dictionaryWithObject:socket
253 forKey:GetServiceProcessLaunchDSocketKey()];
255 // See the man page for launchd.plist.
256 NSMutableDictionary* launchd_plist =
257 [[NSMutableDictionary alloc] initWithObjectsAndKeys:
258 GetServiceProcessLaunchDLabel(), @LAUNCH_JOBKEY_LABEL,
259 program, @LAUNCH_JOBKEY_PROGRAM,
260 ns_args, @LAUNCH_JOBKEY_PROGRAMARGUMENTS,
261 sockets, @LAUNCH_JOBKEY_SOCKETS,
264 if (for_auto_launch) {
265 // We want the service process to be able to exit if there are no services
266 // enabled. With a value of NO in the SuccessfulExit key, launchd will
267 // relaunch the service automatically in any other case than exiting
268 // cleanly with a 0 return code.
269 NSDictionary* keep_alive =
271 dictionaryWithObject:[NSNumber numberWithBool:NO]
272 forKey:@LAUNCH_JOBKEY_KEEPALIVE_SUCCESSFULEXIT];
273 NSDictionary* auto_launchd_plist =
274 [[NSDictionary alloc] initWithObjectsAndKeys:
275 [NSNumber numberWithBool:YES], @LAUNCH_JOBKEY_RUNATLOAD,
276 keep_alive, @LAUNCH_JOBKEY_KEEPALIVE,
277 @kServiceProcessSessionType, @LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE,
279 [launchd_plist addEntriesFromDictionary:auto_launchd_plist];
281 return reinterpret_cast<CFDictionaryRef>(launchd_plist);
284 // Writes the launchd property list into the user's LaunchAgents directory,
285 // creating that directory if needed. This will cause the service process to be
286 // auto launched on the next user login.
287 bool ServiceProcessState::AddToAutoRun() {
288 // We're creating directories and writing a file.
289 base::ThreadRestrictions::AssertIOAllowed();
290 DCHECK(autorun_command_line_.get());
291 base::ScopedCFTypeRef<CFStringRef> name(CopyServiceProcessLaunchDName());
292 base::ScopedCFTypeRef<CFDictionaryRef> plist(
293 CreateServiceProcessLaunchdPlist(autorun_command_line_.get(), true));
294 return Launchd::GetInstance()->WritePlistToFile(Launchd::User,
300 bool ServiceProcessState::RemoveFromAutoRun() {
301 return RemoveFromLaunchd();
304 bool ServiceProcessState::StateData::WatchExecutable() {
305 base::mac::ScopedNSAutoreleasePool pool;
306 NSDictionary* ns_launchd_conf = base::mac::CFToNSCast(launchd_conf);
307 NSString* exe_path = [ns_launchd_conf objectForKey:@ LAUNCH_JOBKEY_PROGRAM];
309 DLOG(ERROR) << "No " LAUNCH_JOBKEY_PROGRAM;
313 base::FilePath executable_path =
314 base::FilePath([exe_path fileSystemRepresentation]);
315 scoped_ptr<ExecFilePathWatcherCallback> callback(
316 new ExecFilePathWatcherCallback);
317 if (!callback->Init(executable_path)) {
318 DLOG(ERROR) << "executable_watcher.Init " << executable_path.value();
321 if (!executable_watcher.Watch(
324 base::Bind(&ExecFilePathWatcherCallback::NotifyPathChanged,
325 base::Owned(callback.release())))) {
326 DLOG(ERROR) << "executable_watcher.watch " << executable_path.value();
332 bool ExecFilePathWatcherCallback::Init(const base::FilePath& path) {
333 return base::mac::FSRefFromPath(path.value(), &executable_fsref_);
336 void ExecFilePathWatcherCallback::NotifyPathChanged(const base::FilePath& path,
339 NOTREACHED(); // TODO(darin): Do something smarter?
343 base::mac::ScopedNSAutoreleasePool pool;
344 bool needs_shutdown = false;
345 bool needs_restart = false;
346 bool good_bundle = false;
349 if (GetParentFSRef(executable_fsref_, &macos_fsref)) {
350 FSRef contents_fsref;
351 if (GetParentFSRef(macos_fsref, &contents_fsref)) {
353 if (GetParentFSRef(contents_fsref, &bundle_fsref)) {
354 base::ScopedCFTypeRef<CFURLRef> bundle_url(
355 CFURLCreateFromFSRef(kCFAllocatorDefault, &bundle_fsref));
356 if (bundle_url.get()) {
357 base::ScopedCFTypeRef<CFBundleRef> bundle(
358 CFBundleCreate(kCFAllocatorDefault, bundle_url));
359 // Check to see if the bundle still has a minimal structure.
360 good_bundle = CFBundleGetIdentifier(bundle) != NULL;
366 needs_shutdown = true;
369 OSErr err = FSDetermineIfRefIsEnclosedByFolder(kOnAppropriateDisk,
373 if (err == noErr && in_trash) {
374 needs_shutdown = true;
376 bool was_moved = true;
378 if (base::mac::FSRefFromPath(path.value(), &path_ref)) {
379 if (FSCompareFSRefs(&path_ref, &executable_fsref_) == noErr) {
384 needs_restart = true;
388 if (needs_shutdown || needs_restart) {
389 // First deal with the plist.
390 base::ScopedCFTypeRef<CFStringRef> name(CopyServiceProcessLaunchDName());
392 base::ScopedCFTypeRef<CFMutableDictionaryRef> plist(
393 Launchd::GetInstance()->CreatePlistFromFile(
394 Launchd::User, Launchd::Agent, name));
396 NSMutableDictionary* ns_plist = base::mac::CFToNSCast(plist);
397 std::string new_path = base::mac::PathFromFSRef(executable_fsref_);
398 NSString* ns_new_path = base::SysUTF8ToNSString(new_path);
399 [ns_plist setObject:ns_new_path forKey:@ LAUNCH_JOBKEY_PROGRAM];
400 base::scoped_nsobject<NSMutableArray> args([[ns_plist
401 objectForKey:@LAUNCH_JOBKEY_PROGRAMARGUMENTS] mutableCopy]);
402 [args replaceObjectAtIndex:0 withObject:ns_new_path];
403 [ns_plist setObject:args forKey:@ LAUNCH_JOBKEY_PROGRAMARGUMENTS];
404 if (!Launchd::GetInstance()->WritePlistToFile(Launchd::User,
408 DLOG(ERROR) << "Unable to rewrite plist.";
409 needs_shutdown = true;
412 DLOG(ERROR) << "Unable to read plist.";
413 needs_shutdown = true;
416 if (needs_shutdown) {
417 if (!RemoveFromLaunchd()) {
418 DLOG(ERROR) << "Unable to RemoveFromLaunchd.";
422 // Then deal with the process.
423 CFStringRef session_type = CFSTR(kServiceProcessSessionType);
425 if (!Launchd::GetInstance()->RestartJob(Launchd::User,
429 DLOG(ERROR) << "RestartLaunchdJob";
430 needs_shutdown = true;
433 if (needs_shutdown) {
435 base::mac::NSToCFCast(GetServiceProcessLaunchDLabel());
436 CFErrorRef err = NULL;
437 if (!Launchd::GetInstance()->RemoveJob(label, &err)) {
438 base::ScopedCFTypeRef<CFErrorRef> scoped_err(err);
439 DLOG(ERROR) << "RemoveJob " << err;
440 // Exiting with zero, so launchd doesn't restart the process.