diff options
author | dmaclach@chromium.org <dmaclach@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-03-22 05:19:29 +0000 |
---|---|---|
committer | dmaclach@chromium.org <dmaclach@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-03-22 05:19:29 +0000 |
commit | 4130d9e2ee756e06aae9861eb4658b0578ee67bd (patch) | |
tree | 18d47b0dac25e8bf76783ce524d37b21dc9bcbe1 /chrome/common | |
parent | 9b8dea2472f7df4036f07f370ab4321f24823c8c (diff) | |
download | chromium_src-4130d9e2ee756e06aae9861eb4658b0578ee67bd.zip chromium_src-4130d9e2ee756e06aae9861eb4658b0578ee67bd.tar.gz chromium_src-4130d9e2ee756e06aae9861eb4658b0578ee67bd.tar.bz2 |
Getting service process on Mac to handle having things moved/changed underneath it.
BUG=74983
TEST=See http://code.google.com/p/chromium/issues/detail?id=74983#c16
Review URL: http://codereview.chromium.org/6660001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@78967 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome/common')
-rw-r--r-- | chrome/common/launchd_mac.h | 100 | ||||
-rw-r--r-- | chrome/common/launchd_mac.mm | 171 | ||||
-rw-r--r-- | chrome/common/service_process_util.cc | 7 | ||||
-rw-r--r-- | chrome/common/service_process_util.h | 12 | ||||
-rw-r--r-- | chrome/common/service_process_util_mac.mm | 249 | ||||
-rw-r--r-- | chrome/common/service_process_util_posix.cc | 11 | ||||
-rw-r--r-- | chrome/common/service_process_util_posix.h | 10 | ||||
-rw-r--r-- | chrome/common/service_process_util_unittest.cc | 369 | ||||
-rw-r--r-- | chrome/common/service_process_util_win.cc | 3 |
9 files changed, 839 insertions, 93 deletions
diff --git a/chrome/common/launchd_mac.h b/chrome/common/launchd_mac.h new file mode 100644 index 0000000..1f692dd --- /dev/null +++ b/chrome/common/launchd_mac.h @@ -0,0 +1,100 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_COMMON_LAUNCHD_MAC_H_ +#define CHROME_COMMON_LAUNCHD_MAC_H_ + +#include <CoreFoundation/CoreFoundation.h> + +#include "base/basictypes.h" +#include "base/singleton.h" + +class Launchd { + public: + enum Type { + Agent, // LaunchAgent + Daemon // LaunchDaemon + }; + + // Domains map to NSSearchPathDomainMask so Foundation does not need to be + // included. + enum Domain { + User = 1, // ~/Library/Launch* + Local = 2, // /Library/Launch* + Network = 4, // /Network/Library/Launch* + System = 8 // /System/Library/Launch* + }; + + // TODO(dmaclach): Get rid of this pseudo singleton, and inject it + // appropriately wherever it is used. + // http://crbug.com/76925 + static Launchd* GetInstance(); + + virtual ~Launchd(); + + // Return a dictionary with the launchd export settings. + virtual CFDictionaryRef CopyExports(); + + // Return a dictionary with the launchd entries for job labeled |name|. + virtual CFDictionaryRef CopyJobDictionary(CFStringRef label); + + // Return a dictionary for launchd process. + virtual CFDictionaryRef CopyDictionaryByCheckingIn(CFErrorRef* error); + + // Remove a launchd process from launchd. + virtual bool RemoveJob(CFStringRef label, CFErrorRef* error); + + // Used by a process controlled by launchd to restart itself. + // |session_type| can be "Aqua", "LoginWindow", "Background", "StandardIO" or + // "System". + // RestartLaunchdJob starts up a separate process to tell launchd to + // send this process a SIGTERM. This call will return, but a SIGTERM will be + // received shortly. + virtual bool RestartJob(Domain domain, + Type type, + CFStringRef name, + CFStringRef session_type); + + // Read a launchd plist from disk. + // |name| should not have an extension. + virtual CFMutableDictionaryRef CreatePlistFromFile(Domain domain, + Type type, + CFStringRef name); + // Write a launchd plist to disk. + // |name| should not have an extension. + virtual bool WritePlistToFile(Domain domain, + Type type, + CFStringRef name, + CFDictionaryRef dict); + + // Delete a launchd plist. + // |name| should not have an extension. + virtual bool DeletePlist(Domain domain, Type type, CFStringRef name); + + // TODO(dmaclach): remove this once http://crbug.com/76925 is fixed. + // Scaffolding for doing unittests with our singleton. + static void SetInstance(Launchd* instance); + class ScopedInstance { + public: + explicit ScopedInstance(Launchd* instance) { + Launchd::SetInstance(instance); + } + ~ScopedInstance() { + Launchd::SetInstance(NULL); + } + }; + + protected: + Launchd() { } + + private: + // TODO(dmaclach): remove this once http://crbug.com/76925 is fixed. + // Scaffolding for doing unittests with our singleton. + friend struct DefaultSingletonTraits<Launchd>; + static Launchd* g_instance_; + + DISALLOW_COPY_AND_ASSIGN(Launchd); +}; + +#endif // CHROME_COMMON_LAUNCHD_MAC_H_ diff --git a/chrome/common/launchd_mac.mm b/chrome/common/launchd_mac.mm new file mode 100644 index 0000000..c67ff23 --- /dev/null +++ b/chrome/common/launchd_mac.mm @@ -0,0 +1,171 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/common/launchd_mac.h" + +#import <Foundation/Foundation.h> +#include <launch.h> + +#include "base/mac/mac_util.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/mac/scoped_nsautorelease_pool.h" +#include "base/process_util.h" +#include "base/stringprintf.h" +#include "base/sys_string_conversions.h" +#include "third_party/GTM/Foundation/GTMServiceManagement.h" + +namespace { + +NSString* SanitizeShellArgument(NSString* arg) { + if (!arg) { + return nil; + } + NSString *sanitize = [arg stringByReplacingOccurrencesOfString:@"'" + withString:@"'\''"]; + return [NSString stringWithFormat:@"'%@'", sanitize]; +} + +NSURL* GetPlistURL(Launchd::Domain domain, + Launchd::Type type, + CFStringRef name) { + NSArray* library_paths = + NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, domain, YES); + DCHECK_EQ([library_paths count], 1U); + NSString* library_path = [library_paths objectAtIndex:0]; + + NSString *launch_dir_name = (type == Launchd::Daemon) ? @"LaunchDaemons" + : @"LaunchAgents"; + NSString* launch_dir = + [library_path stringByAppendingPathComponent:launch_dir_name]; + + NSError* err; + if (![[NSFileManager defaultManager] createDirectoryAtPath:launch_dir + withIntermediateDirectories:YES + attributes:nil + error:&err]) { + LOG(ERROR) << "GetPlistURL " << base::mac::NSToCFCast(err); + return nil; + } + + NSString* plist_file_path = + [launch_dir stringByAppendingPathComponent:base::mac::CFToNSCast(name)]; + plist_file_path = [plist_file_path stringByAppendingPathExtension:@"plist"]; + return [NSURL fileURLWithPath:plist_file_path isDirectory:NO]; +} + +} // namespace + +COMPILE_ASSERT(static_cast<int>(Launchd::User) == + static_cast<int>(NSUserDomainMask), + NSUserDomainMask_value_changed); +COMPILE_ASSERT(static_cast<int>(Launchd::Local) == + static_cast<int>(NSLocalDomainMask), + NSLocalDomainMask_value_changed); +COMPILE_ASSERT(static_cast<int>(Launchd::Network) == + static_cast<int>(NSNetworkDomainMask), + NSNetworkDomainMask_value_changed); +COMPILE_ASSERT(static_cast<int>(Launchd::System) == + static_cast<int>(NSSystemDomainMask), + NSSystemDomainMask_value_changed); + +Launchd* Launchd::g_instance_ = NULL; + +Launchd* Launchd::GetInstance() { + if (!g_instance_) { + g_instance_ = Singleton<Launchd>::get(); + } + return g_instance_; +} + +void Launchd::SetInstance(Launchd* instance) { + if (instance) { + CHECK(!g_instance_); + } + g_instance_ = instance; +} + +Launchd::~Launchd() { } + +CFDictionaryRef Launchd::CopyExports() { + return GTMCopyLaunchdExports(); +} + +CFDictionaryRef Launchd::CopyJobDictionary(CFStringRef label) { + return GTMSMJobCopyDictionary(label); +} + +CFDictionaryRef Launchd::CopyDictionaryByCheckingIn(CFErrorRef* error) { + return GTMSMJobCheckIn(error); +} + +bool Launchd::RemoveJob(CFStringRef label, CFErrorRef* error) { + return GTMSMJobRemove(label, error); +} + +bool Launchd::RestartJob(Domain domain, + Type type, + CFStringRef name, + CFStringRef cf_session_type) { + base::mac::ScopedNSAutoreleasePool pool; + NSURL* url = GetPlistURL(domain, type, name); + NSString* ns_path = [url path]; + ns_path = SanitizeShellArgument(ns_path); + const char* file_path = [ns_path fileSystemRepresentation]; + + NSString* ns_session_type = + SanitizeShellArgument(base::mac::CFToNSCast(cf_session_type)); + if (!file_path || !ns_session_type) { + return false; + } + + std::vector<std::string> argv; + argv.push_back("/bin/bash"); + argv.push_back("--noprofile"); + argv.push_back("-c"); + std::string command = base::StringPrintf( + "/bin/launchctl unload -S %s %s;" + "/bin/launchctl load -S %s %s;", + [ns_session_type UTF8String], file_path, + [ns_session_type UTF8String], file_path); + argv.push_back(command); + base::ProcessHandle handle; + return base::LaunchAppInNewProcessGroup(argv, + base::environment_vector(), + base::file_handle_mapping_vector(), + NO, + &handle); +} + +CFMutableDictionaryRef Launchd::CreatePlistFromFile(Domain domain, + Type type, + CFStringRef name) { + base::mac::ScopedNSAutoreleasePool pool; + NSURL* ns_url = GetPlistURL(domain, type, name); + NSMutableDictionary* plist = + [[NSMutableDictionary alloc] initWithContentsOfURL:ns_url]; + return base::mac::NSToCFCast(plist); +} + +bool Launchd::WritePlistToFile(Domain domain, + Type type, + CFStringRef name, + CFDictionaryRef dict) { + base::mac::ScopedNSAutoreleasePool pool; + NSURL* ns_url = GetPlistURL(domain, type, name); + return [base::mac::CFToNSCast(dict) writeToURL:ns_url atomically:YES]; +} + +bool Launchd::DeletePlist(Domain domain, Type type, CFStringRef name) { + base::mac::ScopedNSAutoreleasePool pool; + NSURL* ns_url = GetPlistURL(domain, type, name); + NSError* err = nil; + if (![[NSFileManager defaultManager] removeItemAtPath:[ns_url path] + error:&err]) { + if ([err code] != NSFileNoSuchFileError) { + LOG(ERROR) << "DeletePlist: " << base::mac::NSToCFCast(err); + } + return false; + } + return true; +} diff --git a/chrome/common/service_process_util.cc b/chrome/common/service_process_util.cc index b983fd5..a12a592 100644 --- a/chrome/common/service_process_util.cc +++ b/chrome/common/service_process_util.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -173,11 +173,6 @@ ServiceProcessState::~ServiceProcessState() { TearDownState(); } -// static -ServiceProcessState* ServiceProcessState::GetInstance() { - return Singleton<ServiceProcessState>::get(); -} - void ServiceProcessState::SignalStopped() { TearDownState(); shared_mem_service_data_.reset(); diff --git a/chrome/common/service_process_util.h b/chrome/common/service_process_util.h index 5db5225..3906601 100644 --- a/chrome/common/service_process_util.h +++ b/chrome/common/service_process_util.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -20,8 +20,6 @@ namespace base { class MessageLoopProxy; } -template <typename T> struct DefaultSingletonTraits; - // Return the IPC channel to connect to the service process. IPC::ChannelHandle GetServiceProcessChannel(); @@ -60,8 +58,8 @@ bool ForceServiceProcessShutdown(const std::string& version, // and this class are shared. class ServiceProcessState { public: - // Returns the singleton instance. - static ServiceProcessState* GetInstance(); + ServiceProcessState(); + ~ServiceProcessState(); // Tries to become the sole service process for the current user data dir. // Returns false if another service process is already running. @@ -89,8 +87,6 @@ class ServiceProcessState { IPC::ChannelHandle GetServiceProcessChannel(); private: - ServiceProcessState(); - ~ServiceProcessState(); #if !defined(OS_MACOSX) // Create the shared memory data for the service process. @@ -121,8 +117,6 @@ class ServiceProcessState { StateData* state_; scoped_ptr<base::SharedMemory> shared_mem_service_data_; scoped_ptr<CommandLine> autorun_command_line_; - - friend struct DefaultSingletonTraits<ServiceProcessState>; }; #endif // CHROME_COMMON_SERVICE_PROCESS_UTIL_H_ diff --git a/chrome/common/service_process_util_mac.mm b/chrome/common/service_process_util_mac.mm index a956ec8..abb0229 100644 --- a/chrome/common/service_process_util_mac.mm +++ b/chrome/common/service_process_util_mac.mm @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -7,13 +7,18 @@ #import <Foundation/Foundation.h> #include <launch.h> +#include <vector> + #include "base/command_line.h" #include "base/file_path.h" +#include "base/file_util.h" #include "base/mac/foundation_util.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/path_service.h" +#include "base/process_util.h" #include "base/scoped_nsobject.h" +#include "base/stringprintf.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "base/threading/thread_restrictions.h" @@ -21,20 +26,24 @@ #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" +#include "chrome/common/launchd_mac.h" #include "content/common/child_process_host.h" -#include "third_party/GTM/Foundation/GTMServiceManagement.h" namespace { -NSString* GetServiceProcessLaunchDFileName() { - NSString *bundle_id = [base::mac::MainAppBundle() bundleIdentifier]; - NSString *label = [bundle_id stringByAppendingPathExtension:@"plist"]; - return label; +#define kServiceProcessSessionType "Background" + +CFStringRef CopyServiceProcessLaunchDName() { + base::mac::ScopedNSAutoreleasePool pool; + NSBundle* bundle = base::mac::MainAppBundle(); + return CFStringCreateCopy(kCFAllocatorDefault, + base::mac::NSToCFCast([bundle bundleIdentifier])); } NSString* GetServiceProcessLaunchDLabel() { - NSString *bundle_id = [base::mac::MainAppBundle() bundleIdentifier]; - NSString *label = [bundle_id stringByAppendingString:@".service_process"]; + scoped_nsobject<NSString> name( + base::mac::CFToNSCast(CopyServiceProcessLaunchDName())); + NSString *label = [name stringByAppendingString:@".service_process"]; FilePath user_data_dir; PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); std::string user_data_dir_path = user_data_dir.value(); @@ -58,36 +67,30 @@ NSString* GetServiceProcessLaunchDSocketEnvVar() { return env_var; } -// Creates the path that it returns. Must be called on the FILE thread. -NSURL* GetUserAgentPath() { - NSArray* library_paths = NSSearchPathForDirectoriesInDomains( - NSLibraryDirectory, NSUserDomainMask, true); - DCHECK_EQ([library_paths count], 1U); - NSString* library_path = [library_paths objectAtIndex:0]; - NSString* launch_agents_path = - [library_path stringByAppendingPathComponent:@"LaunchAgents"]; - - NSError* err; - if (![[NSFileManager defaultManager] createDirectoryAtPath:launch_agents_path - withIntermediateDirectories:YES - attributes:nil - error:&err]) { - LOG(ERROR) << "GetUserAgentPath: " << err; - } - - NSString* plist_file_path = - [launch_agents_path - stringByAppendingPathComponent:GetServiceProcessLaunchDFileName()]; - return [NSURL fileURLWithPath:plist_file_path isDirectory:NO]; +bool GetParentFSRef(const FSRef& child, FSRef* parent) { + return FSGetCatalogInfo(&child, 0, NULL, NULL, NULL, parent) == noErr; } -} +class ExecFilePathWatcherDelegate : public FilePathWatcher::Delegate { + public: + ExecFilePathWatcherDelegate() : process_state_(NULL) { } + bool Init(const FilePath& path, ServiceProcessState *process_state); + virtual ~ExecFilePathWatcherDelegate() { } + virtual void OnFilePathChanged(const FilePath& path) OVERRIDE; + + private: + FSRef executable_fsref_; + ServiceProcessState* process_state_; +}; + +} // namespace // Gets the name of the service process IPC channel. IPC::ChannelHandle GetServiceProcessChannel() { + base::mac::ScopedNSAutoreleasePool pool; std::string socket_path; scoped_nsobject<NSDictionary> dictionary( - base::mac::CFToNSCast(GTMCopyLaunchdExports())); + base::mac::CFToNSCast(Launchd::GetInstance()->CopyExports())); NSString *ns_socket_path = [dictionary objectForKey:GetServiceProcessLaunchDSocketEnvVar()]; if (ns_socket_path) { @@ -98,9 +101,10 @@ IPC::ChannelHandle GetServiceProcessChannel() { bool ForceServiceProcessShutdown(const std::string& /* version */, base::ProcessId /* process_id */) { - NSString* label = GetServiceProcessLaunchDLabel(); + base::mac::ScopedNSAutoreleasePool pool; + CFStringRef label = base::mac::NSToCFCast(GetServiceProcessLaunchDLabel()); CFErrorRef err = NULL; - bool ret = GTMSMJobRemove(reinterpret_cast<CFStringRef>(label), &err); + bool ret = Launchd::GetInstance()->RemoveJob(label, &err); if (!ret) { LOG(ERROR) << "ForceServiceProcessShutdown: " << err; CFRelease(err); @@ -109,10 +113,10 @@ bool ForceServiceProcessShutdown(const std::string& /* version */, } bool GetServiceProcessData(std::string* version, base::ProcessId* pid) { - CFStringRef label = - reinterpret_cast<CFStringRef>(GetServiceProcessLaunchDLabel()); - scoped_nsobject<NSDictionary> launchd_conf( - base::mac::CFToNSCast(GTMSMJobCopyDictionary(label))); + base::mac::ScopedNSAutoreleasePool pool; + CFStringRef label = base::mac::NSToCFCast(GetServiceProcessLaunchDLabel()); + scoped_nsobject<NSDictionary> launchd_conf(base::mac::CFToNSCast( + Launchd::GetInstance()->CopyJobDictionary(label))); if (!launchd_conf.get()) { return false; } @@ -160,12 +164,16 @@ bool ServiceProcessState::Initialize() { return false; } CFErrorRef err = NULL; - state_->launchd_conf_.reset(GTMSMJobCheckIn(&err)); - if (!state_->launchd_conf_.get()) { - LOG(ERROR) << "InitializePlatformState: " << err; + CFDictionaryRef dict = + Launchd::GetInstance()->CopyDictionaryByCheckingIn(&err); + + if (!dict) { + LOG(ERROR) << "CopyLaunchdDictionaryByCheckingIn: " << err; CFRelease(err); return false; } + state_->launchd_conf_.reset(dict); + state_->ui_message_loop_= base::MessageLoopProxy::CreateForCurrentThread(); return true; } @@ -266,7 +274,7 @@ CFDictionaryRef CreateServiceProcessLaunchdPlist(CommandLine* cmd_line, [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithBool:YES], @ LAUNCH_JOBKEY_RUNATLOAD, keep_alive, @ LAUNCH_JOBKEY_KEEPALIVE, - @"Background", @ LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE, + @ kServiceProcessSessionType, @ LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE, nil]; [launchd_plist addEntriesFromDictionary:auto_launchd_plist]; } @@ -280,25 +288,162 @@ bool ServiceProcessState::AddToAutoRun() { // We're creating directories and writing a file. base::ThreadRestrictions::AssertIOAllowed(); DCHECK(autorun_command_line_.get()); - - base::mac::ScopedNSAutoreleasePool pool; - scoped_nsobject<NSDictionary> plist( - base::mac::CFToNSCast(CreateServiceProcessLaunchdPlist( - autorun_command_line_.get(), true))); - NSURL* plist_url = GetUserAgentPath(); - return [plist writeToURL:plist_url atomically:YES]; + base::mac::ScopedCFTypeRef<CFStringRef> name(CopyServiceProcessLaunchDName()); + base::mac::ScopedCFTypeRef<CFDictionaryRef> plist( + CreateServiceProcessLaunchdPlist(autorun_command_line_.get(), true)); + return Launchd::GetInstance()->WritePlistToFile(Launchd::User, + Launchd::Agent, + name, + plist); } bool ServiceProcessState::RemoveFromAutoRun() { // We're killing a file. base::ThreadRestrictions::AssertIOAllowed(); + base::mac::ScopedCFTypeRef<CFStringRef> name(CopyServiceProcessLaunchDName()); + return Launchd::GetInstance()->DeletePlist(Launchd::User, + Launchd::Agent, + name); +} +void ServiceProcessState::StateData::WatchExecutable() { base::mac::ScopedNSAutoreleasePool pool; - NSURL* plist_url = GetUserAgentPath(); - SInt32 error = 0; - if (!CFURLDestroyResource(reinterpret_cast<CFURLRef>(plist_url), &error)) { - LOG(ERROR) << "RemoveFromAutoRun: " << error; + NSDictionary* ns_launchd_conf = base::mac::CFToNSCast(launchd_conf_); + NSString* exe_path = [ns_launchd_conf objectForKey:@ LAUNCH_JOBKEY_PROGRAM]; + if (!exe_path) { + LOG(ERROR) << "No " LAUNCH_JOBKEY_PROGRAM; + return; + } + + FilePath executable_path = FilePath([exe_path fileSystemRepresentation]); + scoped_ptr<ExecFilePathWatcherDelegate> delegate( + new ExecFilePathWatcherDelegate); + if (!delegate->Init(executable_path, state_)) { + LOG(ERROR) << "executable_watcher_.Init " << executable_path.value(); + return; + } + if (!executable_watcher_.Watch(executable_path, + delegate.release(), + ui_message_loop_)) { + LOG(ERROR) << "executable_watcher_.watch " << executable_path.value(); + return; + } +} + +bool ExecFilePathWatcherDelegate::Init(const FilePath& path, + ServiceProcessState *process_state) { + if (!process_state || + !base::mac::FSRefFromPath(path.value(), &executable_fsref_)) { return false; } + process_state_ = process_state; return true; } + +void ExecFilePathWatcherDelegate::OnFilePathChanged(const FilePath& path) { + base::mac::ScopedNSAutoreleasePool pool; + bool needs_shutdown = false; + bool needs_restart = false; + bool good_bundle = false; + + FSRef macos_fsref; + if (GetParentFSRef(executable_fsref_, &macos_fsref)) { + FSRef contents_fsref; + if (GetParentFSRef(macos_fsref, &contents_fsref)) { + FSRef bundle_fsref; + if (GetParentFSRef(contents_fsref, &bundle_fsref)) { + base::mac::ScopedCFTypeRef<CFURLRef> bundle_url( + CFURLCreateFromFSRef(kCFAllocatorDefault, &bundle_fsref)); + if (bundle_url.get()) { + base::mac::ScopedCFTypeRef<CFBundleRef> bundle( + CFBundleCreate(kCFAllocatorDefault, bundle_url)); + // Check to see if the bundle still has a minimal structure. + good_bundle = CFBundleGetIdentifier(bundle) != NULL; + } + } + } + } + if (!good_bundle) { + needs_shutdown = true; + } else { + Boolean in_trash; + OSErr err = FSDetermineIfRefIsEnclosedByFolder(kOnAppropriateDisk, + kTrashFolderType, + &executable_fsref_, + &in_trash); + if (err == noErr && in_trash) { + needs_shutdown = true; + } else { + bool was_moved = true; + FSRef path_ref; + if (base::mac::FSRefFromPath(path.value(), &path_ref)) { + if (FSCompareFSRefs(&path_ref, &executable_fsref_) == noErr) { + was_moved = false; + } + } + if (was_moved) { + needs_restart = true; + } + } + } + if (needs_shutdown || needs_restart) { + // First deal with the plist. + base::mac::ScopedCFTypeRef<CFStringRef> name( + CopyServiceProcessLaunchDName()); + if (needs_restart) { + base::mac::ScopedCFTypeRef<CFMutableDictionaryRef> plist( + Launchd::GetInstance()->CreatePlistFromFile(Launchd::User, + Launchd::Agent, + name)); + if (plist.get()) { + NSMutableDictionary* ns_plist = base::mac::CFToNSCast(plist); + std::string new_path = base::mac::PathFromFSRef(executable_fsref_); + NSString* ns_new_path = base::SysUTF8ToNSString(new_path); + [ns_plist setObject:ns_new_path forKey:@ LAUNCH_JOBKEY_PROGRAM]; + scoped_nsobject<NSMutableArray> args( + [[ns_plist objectForKey:@ LAUNCH_JOBKEY_PROGRAMARGUMENTS] + mutableCopy]); + [args replaceObjectAtIndex:0 withObject:ns_new_path]; + [ns_plist setObject:args forKey:@ LAUNCH_JOBKEY_PROGRAMARGUMENTS]; + if (!Launchd::GetInstance()->WritePlistToFile(Launchd::User, + Launchd::Agent, + name, + plist)) { + LOG(ERROR) << "Unable to rewrite plist."; + needs_shutdown = true; + } + } else { + LOG(ERROR) << "Unable to read plist."; + needs_shutdown = true; + } + } + if (needs_shutdown) { + if (!process_state_->RemoveFromAutoRun()) { + LOG(ERROR) << "Unable to RemoveFromAutoRun."; + } + } + + // Then deal with the process. + CFStringRef session_type = CFSTR(kServiceProcessSessionType); + if (needs_restart) { + if (!Launchd::GetInstance()->RestartJob(Launchd::User, + Launchd::Agent, + name, + session_type)) { + LOG(ERROR) << "RestartLaunchdJob"; + needs_shutdown = true; + } + } + if (needs_shutdown) { + CFStringRef label = + base::mac::NSToCFCast(GetServiceProcessLaunchDLabel()); + CFErrorRef err = NULL; + if (!Launchd::GetInstance()->RemoveJob(label, &err)) { + base::mac::ScopedCFTypeRef<CFErrorRef> scoped_err(err); + LOG(ERROR) << "RemoveJob " << err; + // Exiting with zero, so launchd doesn't restart the process. + exit(0); + } + } + } +} diff --git a/chrome/common/service_process_util_posix.cc b/chrome/common/service_process_util_posix.cc index 504570b..771494e 100644 --- a/chrome/common/service_process_util_posix.cc +++ b/chrome/common/service_process_util_posix.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -96,6 +96,7 @@ bool ServiceProcessState::SignalReady( CHECK(state_); CHECK_EQ(g_signal_socket, -1); + scoped_ptr<Task> scoped_shutdown_task(shutdown_task); #if defined(OS_LINUX) state_->running_lock_.reset(TakeServiceRunningLock(true)); if (state_->running_lock_.get() == NULL) { @@ -103,11 +104,17 @@ bool ServiceProcessState::SignalReady( } #endif // OS_LINUX state_->shut_down_monitor_.reset( - new ServiceProcessShutdownMonitor(shutdown_task)); + new ServiceProcessShutdownMonitor(scoped_shutdown_task.release())); if (pipe(state_->sockets_) < 0) { PLOG(ERROR) << "pipe"; return false; } +#if defined(OS_MACOSX) + state_->state_ = this; + message_loop_proxy->PostTask(FROM_HERE, + NewRunnableMethod(state_, + &ServiceProcessState::StateData::WatchExecutable)); +#endif // OS_MACOSX message_loop_proxy->PostTask(FROM_HERE, NewRunnableMethod(state_, &ServiceProcessState::StateData::SignalReady)); return true; diff --git a/chrome/common/service_process_util_posix.h b/chrome/common/service_process_util_posix.h index c84b3b8..0eb29e8 100644 --- a/chrome/common/service_process_util_posix.h +++ b/chrome/common/service_process_util_posix.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -21,6 +21,9 @@ MultiProcessLock* TakeServiceRunningLock(bool waiting); #if defined(OS_MACOSX) #include "base/mac/scoped_cftyperef.h" +#include "base/message_loop_proxy.h" +#include "content/common/file_path_watcher/file_path_watcher.h" + class CommandLine; CFDictionaryRef CreateServiceProcessLaunchdPlist(CommandLine* cmd_line, bool for_auto_launch); @@ -61,7 +64,12 @@ struct ServiceProcessState::StateData // variables to remove the trailing underscore. #if defined(OS_MACOSX) + void WatchExecutable(); + base::mac::ScopedCFTypeRef<CFDictionaryRef> launchd_conf_; + FilePathWatcher executable_watcher_; + scoped_refptr<base::MessageLoopProxy> ui_message_loop_; + ServiceProcessState* state_; #endif // OS_MACOSX #if defined(OS_LINUX) scoped_ptr<MultiProcessLock> initializing_lock_; diff --git a/chrome/common/service_process_util_unittest.cc b/chrome/common/service_process_util_unittest.cc index 03827e0..e542f09 100644 --- a/chrome/common/service_process_util_unittest.cc +++ b/chrome/common/service_process_util_unittest.cc @@ -1,12 +1,12 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/common/service_process_util.h" + #include "base/basictypes.h" #if !defined(OS_MACOSX) -// TODO(dmaclach): Figure out tests that will work with launchd on Mac OS. - #include "base/at_exit.h" #include "base/command_line.h" #include "base/process_util.h" @@ -18,7 +18,6 @@ #include "base/utf_string_conversions.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" -#include "chrome/common/service_process_util.h" #include "testing/multiprocess_func_list.h" #if defined(OS_WIN) @@ -89,24 +88,24 @@ void ServiceProcessStateTest::LaunchAndWait(const std::string& name) { } TEST_F(ServiceProcessStateTest, Singleton) { - ServiceProcessState* state = ServiceProcessState::GetInstance(); - ASSERT_TRUE(state->Initialize()); + ServiceProcessState state; + ASSERT_TRUE(state.Initialize()); LaunchAndWait("ServiceProcessStateTestSingleton"); } TEST_F(ServiceProcessStateTest, ReadyState) { ASSERT_FALSE(CheckServiceProcessReady()); - ServiceProcessState* state = ServiceProcessState::GetInstance(); - ASSERT_TRUE(state->Initialize()); - ASSERT_TRUE(state->SignalReady(IOMessageLoopProxy(), NULL)); + ServiceProcessState state; + ASSERT_TRUE(state.Initialize()); + ASSERT_TRUE(state.SignalReady(IOMessageLoopProxy(), NULL)); LaunchAndWait("ServiceProcessStateTestReadyTrue"); - state->SignalStopped(); + state.SignalStopped(); LaunchAndWait("ServiceProcessStateTestReadyFalse"); } TEST_F(ServiceProcessStateTest, AutoRun) { - ServiceProcessState* state = ServiceProcessState::GetInstance(); - ASSERT_TRUE(state->AddToAutoRun()); + ServiceProcessState state; + ASSERT_TRUE(state.AddToAutoRun()); scoped_ptr<CommandLine> autorun_command_line; #if defined(OS_WIN) std::string value_name = GetServiceProcessScopedName("_service_run"); @@ -139,7 +138,7 @@ TEST_F(ServiceProcessStateTest, AutoRun) { EXPECT_EQ(autorun_command_line->GetSwitchValueASCII(switches::kProcessType), std::string(switches::kServiceProcess)); } - ASSERT_TRUE(state->RemoveFromAutoRun()); + ASSERT_TRUE(state.RemoveFromAutoRun()); #if defined(OS_WIN) EXPECT_FALSE(base::win::ReadCommandFromAutoRun(HKEY_CURRENT_USER, UTF8ToWide(value_name), @@ -161,8 +160,8 @@ TEST_F(ServiceProcessStateTest, SharedMem) { // implementation on Posix, this check will only execute on Windows. ASSERT_FALSE(GetServiceProcessData(&version, &pid)); #endif // defined(OS_WIN) - ServiceProcessState* state = ServiceProcessState::GetInstance(); - ASSERT_TRUE(state->Initialize()); + ServiceProcessState state; + ASSERT_TRUE(state.Initialize()); ASSERT_TRUE(GetServiceProcessData(&version, &pid)); ASSERT_EQ(base::GetCurrentProcId(), pid); } @@ -186,8 +185,8 @@ TEST_F(ServiceProcessStateTest, ForceShutdown) { } MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestSingleton) { - ServiceProcessState* state = ServiceProcessState::GetInstance(); - EXPECT_FALSE(state->Initialize()); + ServiceProcessState state; + EXPECT_FALSE(state.Initialize()); return 0; } @@ -207,11 +206,11 @@ MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestShutdown) { base::Thread io_thread_("ServiceProcessStateTestShutdownIOThread"); base::Thread::Options options(MessageLoop::TYPE_IO, 0); EXPECT_TRUE(io_thread_.StartWithOptions(options)); - ServiceProcessState* state = ServiceProcessState::GetInstance(); - EXPECT_TRUE(state->Initialize()); - EXPECT_TRUE(state->SignalReady(io_thread_.message_loop_proxy(), - NewRunnableFunction(&ShutdownTask, - MessageLoop::current()))); + ServiceProcessState state; + EXPECT_TRUE(state.Initialize()); + EXPECT_TRUE(state.SignalReady(io_thread_.message_loop_proxy(), + NewRunnableFunction(&ShutdownTask, + MessageLoop::current()))); message_loop.PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask(), TestTimeouts::action_max_timeout_ms()); @@ -221,4 +220,330 @@ MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestShutdown) { return 0; } +#else // !OS_MACOSX + +#include <CoreFoundation/CoreFoundation.h> + +#include <launch.h> +#include <sys/stat.h> + +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/mac/mac_util.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/message_loop.h" +#include "base/scoped_temp_dir.h" +#include "base/stringprintf.h" +#include "base/sys_string_conversions.h" +#include "base/test/test_timeouts.h" +#include "base/threading/thread.h" +#include "chrome/common/launchd_mac.h" +#include "testing/gtest/include/gtest/gtest.h" + +// TODO(dmaclach): Write this in terms of a real mock. +// http://crbug.com/76923 +class MockLaunchd : public Launchd { + public: + MockLaunchd(const FilePath& file, MessageLoop* loop) + : file_(file), + message_loop_(loop), + restart_called_(false), + remove_called_(false), + checkin_called_(false), + write_called_(false), + delete_called_(false) { + } + virtual ~MockLaunchd() { } + + virtual CFDictionaryRef CopyExports() OVERRIDE { + ADD_FAILURE(); + return NULL; + } + + virtual CFDictionaryRef CopyJobDictionary(CFStringRef label) OVERRIDE { + ADD_FAILURE(); + return NULL; + } + + virtual CFDictionaryRef CopyDictionaryByCheckingIn(CFErrorRef* error) + OVERRIDE { + checkin_called_ = true; + CFStringRef program = CFSTR(LAUNCH_JOBKEY_PROGRAM); + CFStringRef program_args = CFSTR(LAUNCH_JOBKEY_PROGRAMARGUMENTS); + const void *keys[] = { program, program_args }; + base::mac::ScopedCFTypeRef<CFStringRef> path( + base::SysUTF8ToCFStringRef(file_.value())); + const void *array_values[] = { path.get() }; + base::mac::ScopedCFTypeRef<CFArrayRef> args( + CFArrayCreate(kCFAllocatorDefault, + array_values, + 1, + &kCFTypeArrayCallBacks)); + const void *values[] = { path, args }; + return CFDictionaryCreate(kCFAllocatorDefault, + keys, + values, + arraysize(keys), + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + } + + virtual bool RemoveJob(CFStringRef label, CFErrorRef* error) OVERRIDE { + remove_called_ = true; + message_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask); + return true; + } + + virtual bool RestartJob(Domain domain, + Type type, + CFStringRef name, + CFStringRef session_type) OVERRIDE { + restart_called_ = true; + message_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask); + return true; + } + + virtual CFMutableDictionaryRef CreatePlistFromFile( + Domain domain, + Type type, + CFStringRef name) OVERRIDE { + base::mac::ScopedCFTypeRef<CFDictionaryRef> dict( + CopyDictionaryByCheckingIn(NULL)); + return CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, dict); + } + + virtual bool WritePlistToFile(Domain domain, + Type type, + CFStringRef name, + CFDictionaryRef dict) OVERRIDE { + write_called_ = true; + return true; + } + + virtual bool DeletePlist(Domain domain, + Type type, + CFStringRef name) OVERRIDE { + delete_called_ = true; + return true; + } + + bool restart_called() const { return restart_called_; } + bool remove_called() const { return remove_called_; } + bool checkin_called() const { return checkin_called_; } + bool write_called() const { return write_called_; } + bool delete_called() const { return delete_called_; } + + private: + FilePath file_; + MessageLoop* message_loop_; + bool restart_called_; + bool remove_called_; + bool checkin_called_; + bool write_called_; + bool delete_called_; +}; + +class ServiceProcessStateFileManipulationTest : public ::testing::Test { + protected: + ServiceProcessStateFileManipulationTest() + : io_thread_("ServiceProcessStateFileManipulationTest_IO") { + } + virtual ~ServiceProcessStateFileManipulationTest() { } + + virtual void SetUp() { + base::Thread::Options options; + options.message_loop_type = MessageLoop::TYPE_IO; + ASSERT_TRUE(io_thread_.StartWithOptions(options)); + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + ASSERT_TRUE(MakeABundle(GetTempDirPath(), + "Test", + &bundle_path_, + &executable_path_)); + mock_launchd_.reset(new MockLaunchd(executable_path_, &loop_)); + scoped_launchd_instance_.reset( + new Launchd::ScopedInstance(mock_launchd_.get())); + ASSERT_TRUE(service_process_state_.Initialize()); + ASSERT_TRUE(service_process_state_.SignalReady( + io_thread_.message_loop_proxy(), + NULL)); + loop_.PostDelayedTask(FROM_HERE, + new MessageLoop::QuitTask, + TestTimeouts::large_test_timeout_ms()); + } + + bool MakeABundle(const FilePath& dst, + const std::string& name, + FilePath* bundle_root, + FilePath* executable) { + *bundle_root = dst.Append(name + std::string(".app")); + FilePath contents = bundle_root->AppendASCII("Contents"); + FilePath mac_os = contents.AppendASCII("MacOS"); + *executable = mac_os.Append(name); + FilePath info_plist = contents.Append("Info.plist"); + + if (!file_util::CreateDirectory(mac_os)) { + return false; + } + const char *data = "#! testbundle\n"; + int len = strlen(data); + if (file_util::WriteFile(*executable, data, len) != len) { + return false; + } + if (chmod(executable->value().c_str(), 0555) != 0) { + return false; + } + + const char* info_plist_format = + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" + "<plist version=\"1.0\">\n" + "<dict>\n" + " <key>CFBundleDevelopmentRegion</key>\n" + " <string>English</string>\n" + " <key>CFBundleIdentifier</key>\n" + " <string>com.test.%s</string>\n" + " <key>CFBundleInfoDictionaryVersion</key>\n" + " <string>6.0</string>\n" + " <key>CFBundleExecutable</key>\n" + " <string>%s</string>\n" + " <key>CFBundleVersion</key>\n" + " <string>1</string>\n" + "</dict>\n" + "</plist>\n"; + std::string info_plist_data = base::StringPrintf(info_plist_format, + name.c_str(), + name.c_str()); + len = info_plist_data.length(); + if (file_util::WriteFile(info_plist, info_plist_data.c_str(), len) != len) { + return false; + } + const UInt8* bundle_root_path = + reinterpret_cast<const UInt8*>(bundle_root->value().c_str()); + base::mac::ScopedCFTypeRef<CFURLRef> url( + CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, + bundle_root_path, + bundle_root->value().length(), + true)); + base::mac::ScopedCFTypeRef<CFBundleRef> bundle( + CFBundleCreate(kCFAllocatorDefault, url)); + return bundle.get(); + } + + const MockLaunchd* mock_launchd() const { return mock_launchd_.get(); } + const FilePath& executable_path() const { return executable_path_; } + const FilePath& bundle_path() const { return bundle_path_; } + const FilePath& GetTempDirPath() const { return temp_dir_.path(); } + + base::MessageLoopProxy* GetIOMessageLoopProxy() { + return io_thread_.message_loop_proxy().get(); + } + void Run() { loop_.Run(); } + + private: + ScopedTempDir temp_dir_; + MessageLoopForUI loop_; + base::Thread io_thread_; + FilePath executable_path_, bundle_path_; + scoped_ptr<MockLaunchd> mock_launchd_; + scoped_ptr<Launchd::ScopedInstance> scoped_launchd_instance_; + ServiceProcessState service_process_state_; +}; + +void DeleteFunc(const FilePath& file) { + EXPECT_TRUE(file_util::Delete(file, true)); +} + +void MoveFunc(const FilePath& from, const FilePath& to) { + EXPECT_TRUE(file_util::Move(from, to)); +} + +void ChangeAttr(const FilePath& from, int mode) { + EXPECT_EQ(chmod(from.value().c_str(), mode), 0); +} + +class ScopedAttributesRestorer { + public: + ScopedAttributesRestorer(const FilePath& path, int mode) + : path_(path), mode_(mode) { + } + ~ScopedAttributesRestorer() { + ChangeAttr(path_, mode_); + } + private: + FilePath path_; + int mode_; +}; + +void TrashFunc(const FilePath& src) { + FSRef path_ref; + FSRef new_path_ref; + EXPECT_TRUE(base::mac::FSRefFromPath(src.value(), &path_ref)); + OSStatus status = FSMoveObjectToTrashSync(&path_ref, + &new_path_ref, + kFSFileOperationDefaultOptions); + EXPECT_EQ(status, noErr) << "FSMoveObjectToTrashSync " << status; +} + +TEST_F(ServiceProcessStateFileManipulationTest, DeleteFile) { + GetIOMessageLoopProxy()->PostTask( + FROM_HERE, + NewRunnableFunction(&DeleteFunc, executable_path())); + Run(); + ASSERT_TRUE(mock_launchd()->remove_called()); + ASSERT_TRUE(mock_launchd()->delete_called()); +} + +TEST_F(ServiceProcessStateFileManipulationTest, DeleteBundle) { + GetIOMessageLoopProxy()->PostTask( + FROM_HERE, + NewRunnableFunction(&DeleteFunc, bundle_path())); + Run(); + ASSERT_TRUE(mock_launchd()->remove_called()); + ASSERT_TRUE(mock_launchd()->delete_called()); +} + +TEST_F(ServiceProcessStateFileManipulationTest, MoveBundle) { + FilePath new_loc = GetTempDirPath().AppendASCII("MoveBundle"); + GetIOMessageLoopProxy()->PostTask( + FROM_HERE, + NewRunnableFunction(&MoveFunc, bundle_path(), new_loc)); + Run(); + ASSERT_TRUE(mock_launchd()->restart_called()); + ASSERT_TRUE(mock_launchd()->write_called()); +} + +TEST_F(ServiceProcessStateFileManipulationTest, MoveFile) { + FilePath new_loc = GetTempDirPath().AppendASCII("MoveFile"); + GetIOMessageLoopProxy()->PostTask( + FROM_HERE, + NewRunnableFunction(&MoveFunc, executable_path(), new_loc)); + Run(); + ASSERT_TRUE(mock_launchd()->remove_called()); + ASSERT_TRUE(mock_launchd()->delete_called()); +} + +TEST_F(ServiceProcessStateFileManipulationTest, TrashBundle) { + FSRef bundle_ref; + ASSERT_TRUE(base::mac::FSRefFromPath(bundle_path().value(), &bundle_ref)); + GetIOMessageLoopProxy()->PostTask( + FROM_HERE, + NewRunnableFunction(&TrashFunc, bundle_path())); + Run(); + ASSERT_TRUE(mock_launchd()->remove_called()); + ASSERT_TRUE(mock_launchd()->delete_called()); + std::string path(base::mac::PathFromFSRef(bundle_ref)); + FilePath file_path(path); + ASSERT_TRUE(file_util::Delete(file_path, true)); +} + +TEST_F(ServiceProcessStateFileManipulationTest, ChangeAttr) { + ScopedAttributesRestorer restorer(bundle_path(), 0777); + GetIOMessageLoopProxy()->PostTask( + FROM_HERE, + NewRunnableFunction(&ChangeAttr, bundle_path(), 0222)); + Run(); + ASSERT_TRUE(mock_launchd()->remove_called()); + ASSERT_TRUE(mock_launchd()->delete_called()); +} + #endif // !OS_MACOSX diff --git a/chrome/common/service_process_util_win.cc b/chrome/common/service_process_util_win.cc index 32581a1..a6385e2 100644 --- a/chrome/common/service_process_util_win.cc +++ b/chrome/common/service_process_util_win.cc @@ -128,12 +128,13 @@ bool ServiceProcessState::SignalReady( base::MessageLoopProxy* message_loop_proxy, Task* shutdown_task) { DCHECK(state_); DCHECK(state_->ready_event.IsValid()); + scoped_ptr<Task> scoped_shutdown_task(shutdown_task); if (!SetEvent(state_->ready_event.Get())) { return false; } if (shutdown_task) { state_->shutdown_monitor.reset( - new ServiceProcessShutdownMonitor(shutdown_task)); + new ServiceProcessShutdownMonitor(scoped_shutdown_task.release())); state_->shutdown_monitor->Start(); } return true; |