Add ICU message format support
[chromium-blink-merge.git] / chrome / common / service_process_util_mac.mm
blob5a229eb017d404b02aa1c41205f109da0d5da9f3
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>
8 #include <launch.h>
10 #include <vector>
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;
35 namespace {
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:@" "
55                                                withString:@"_"];
56   label = [label stringByAppendingString:ns_path];
57   return label;
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,
73                                              Launchd::Agent,
74                                              name);
77 class ExecFilePathWatcherCallback {
78  public:
79   ExecFilePathWatcherCallback() {}
80   ~ExecFilePathWatcherCallback() {}
82   bool Init(const base::FilePath& path);
83   void NotifyPathChanged(const base::FilePath& path, bool error);
85  private:
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)
97     return socket_name;
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);
104 }  // namespace
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);
118   if (!ret) {
119     DLOG(ERROR) << "ForceServiceProcessShutdown: " << err << " "
120                 << base::SysCFStringRefToUTF8(label);
121     CFRelease(err);
122   }
123   return ret;
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()) {
132     return false;
133   }
134   // Anything past here will return true in that there does appear
135   // to be a service process of some sort registered with launchd.
136   if (version) {
137     *version = "0";
138     NSString* exe_path = [launchd_conf objectForKey:@ LAUNCH_JOBKEY_PROGRAM];
139     if (exe_path) {
140       NSString* bundle_path = [[[exe_path stringByDeletingLastPathComponent]
141                                 stringByDeletingLastPathComponent]
142                                stringByDeletingLastPathComponent];
143       NSBundle* bundle = [NSBundle bundleWithPath:bundle_path];
144       if (bundle) {
145         NSString* ns_version =
146             [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
147         if (ns_version) {
148           *version = base::SysNSStringToUTF8(ns_version);
149         } else {
150           DLOG(ERROR) << "Unable to get version at: "
151                       << reinterpret_cast<CFStringRef>(bundle_path);
152         }
153       } else {
154         // The bundle has been deleted out from underneath the registered
155         // job.
156         DLOG(ERROR) << "Unable to get bundle at: "
157                     << reinterpret_cast<CFStringRef>(bundle_path);
158       }
159     } else {
160       DLOG(ERROR) << "Unable to get executable path for service process";
161     }
162   }
163   if (pid) {
164     *pid = -1;
165     NSNumber* ns_pid = [launchd_conf objectForKey:@ LAUNCH_JOBKEY_PID];
166     if (ns_pid) {
167      *pid = [ns_pid intValue];
168     }
169   }
170   return true;
173 bool ServiceProcessState::Initialize() {
174   CFErrorRef err = NULL;
175   CFDictionaryRef dict =
176       Launchd::GetInstance()->CopyDictionaryByCheckingIn(&err);
177   if (!dict) {
178     DLOG(ERROR) << "ServiceProcess must be launched by launchd. "
179                 << "CopyLaunchdDictionaryByCheckingIn: " << err;
180     CFRelease(err);
181     return false;
182   }
183   state_->launchd_conf.reset(dict);
184   return true;
187 IPC::ChannelHandle ServiceProcessState::GetServiceProcessChannel() {
188   DCHECK(state_);
189   NSDictionary* ns_launchd_conf = base::mac::CFToNSCast(state_->launchd_conf);
190   NSDictionary* socket_dict =
191       [ns_launchd_conf objectForKey:@ LAUNCH_JOBKEY_SOCKETS];
192   NSArray* 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() {
201   std::string version;
202   pid_t pid;
203   if (!GetServiceProcessData(&version, &pid)) {
204     return false;
205   }
206   Version service_version(version);
207   bool ready = true;
208   if (!service_version.IsValid()) {
209     ready = false;
210   } else {
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
214       // are out of date.
215       NOTREACHED();
216       ready = true;
217     } else if (running_version.CompareTo(service_version) > 0) {
218       ready = false;
219     } else {
220       ready = true;
221     }
222   }
223   if (!ready) {
224     ForceServiceProcessShutdown(version, pid);
225   }
226   return ready;
229 CFDictionaryRef CreateServiceProcessLaunchdPlist(base::CommandLine* cmd_line,
230                                                  bool for_auto_launch) {
231   base::mac::ScopedNSAutoreleasePool pool;
233   NSString* program =
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();
240        iter < args.end();
241        ++iter) {
242     [ns_args addObject:base::SysUTF8ToNSString(*iter)];
243   }
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,
262         nil];
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 =
270         [NSDictionary
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,
278           nil];
279     [launchd_plist addEntriesFromDictionary:auto_launchd_plist];
280   }
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,
295                                                   Launchd::Agent,
296                                                   name,
297                                                   plist);
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];
308   if (!exe_path) {
309     DLOG(ERROR) << "No " LAUNCH_JOBKEY_PROGRAM;
310     return false;
311   }
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();
319     return false;
320   }
321   if (!executable_watcher.Watch(
322           executable_path,
323           false,
324           base::Bind(&ExecFilePathWatcherCallback::NotifyPathChanged,
325                      base::Owned(callback.release())))) {
326     DLOG(ERROR) << "executable_watcher.watch " << executable_path.value();
327     return false;
328   }
329   return true;
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,
337                                                     bool error) {
338   if (error) {
339     NOTREACHED();  // TODO(darin): Do something smarter?
340     return;
341   }
343   base::mac::ScopedNSAutoreleasePool pool;
344   bool needs_shutdown = false;
345   bool needs_restart = false;
346   bool good_bundle = false;
348   FSRef macos_fsref;
349   if (GetParentFSRef(executable_fsref_, &macos_fsref)) {
350     FSRef contents_fsref;
351     if (GetParentFSRef(macos_fsref, &contents_fsref)) {
352       FSRef bundle_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;
361         }
362       }
363     }
364   }
365   if (!good_bundle) {
366     needs_shutdown = true;
367   } else {
368     Boolean in_trash;
369     OSErr err = FSDetermineIfRefIsEnclosedByFolder(kOnAppropriateDisk,
370                                                    kTrashFolderType,
371                                                    &executable_fsref_,
372                                                    &in_trash);
373     if (err == noErr && in_trash) {
374       needs_shutdown = true;
375     } else {
376       bool was_moved = true;
377       FSRef path_ref;
378       if (base::mac::FSRefFromPath(path.value(), &path_ref)) {
379         if (FSCompareFSRefs(&path_ref, &executable_fsref_) == noErr) {
380           was_moved = false;
381         }
382       }
383       if (was_moved) {
384         needs_restart = true;
385       }
386     }
387   }
388   if (needs_shutdown || needs_restart) {
389     // First deal with the plist.
390     base::ScopedCFTypeRef<CFStringRef> name(CopyServiceProcessLaunchDName());
391     if (needs_restart) {
392       base::ScopedCFTypeRef<CFMutableDictionaryRef> plist(
393           Launchd::GetInstance()->CreatePlistFromFile(
394               Launchd::User, Launchd::Agent, name));
395       if (plist.get()) {
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,
405                                                       Launchd::Agent,
406                                                       name,
407                                                       plist)) {
408           DLOG(ERROR) << "Unable to rewrite plist.";
409           needs_shutdown = true;
410         }
411       } else {
412         DLOG(ERROR) << "Unable to read plist.";
413         needs_shutdown = true;
414       }
415     }
416     if (needs_shutdown) {
417       if (!RemoveFromLaunchd()) {
418         DLOG(ERROR) << "Unable to RemoveFromLaunchd.";
419       }
420     }
422     // Then deal with the process.
423     CFStringRef session_type = CFSTR(kServiceProcessSessionType);
424     if (needs_restart) {
425       if (!Launchd::GetInstance()->RestartJob(Launchd::User,
426                                               Launchd::Agent,
427                                               name,
428                                               session_type)) {
429         DLOG(ERROR) << "RestartLaunchdJob";
430         needs_shutdown = true;
431       }
432     }
433     if (needs_shutdown) {
434       CFStringRef label =
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.
441         exit(0);
442       }
443     }
444   }