1// Copyright (c) 2011 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. 4 5#include "chrome/browser/policy/policy_path_parser.h" 6 7#include "base/logging.h" 8#include "base/sys_string_conversions.h" 9 10#import <Cocoa/Cocoa.h> 11 12#include <string> 13 14namespace policy { 15 16namespace path_parser { 17 18const char* kUserNamePolicyVarName = "${user_name}"; 19const char* kMachineNamePolicyVarName = "${machine_name}"; 20const char* kMacUsersDirectory = "${users}"; 21const char* kMacDocumentsFolderVarName = "${documents}"; 22 23struct MacFolderNamesToSPDMaping { 24 const char* name; 25 NSSearchPathDirectory id; 26}; 27 28// Mapping from variable names to MacOS NSSearchPathDirectory ids. 29const MacFolderNamesToSPDMaping mac_folder_mapping[] = { 30 { kMacUsersDirectory, NSUserDirectory}, 31 { kMacDocumentsFolderVarName, NSDocumentDirectory} 32}; 33 34// Replaces all variable occurrences in the policy string with the respective 35// system settings values. 36FilePath::StringType ExpandPathVariables( 37 const FilePath::StringType& untranslated_string) { 38 FilePath::StringType result(untranslated_string); 39 // First translate all path variables we recognize. 40 for (size_t i = 0; i < arraysize(mac_folder_mapping); ++i) { 41 size_t position = result.find(mac_folder_mapping[i].name); 42 if (position != std::string::npos) { 43 NSArray* searchpaths = NSSearchPathForDirectoriesInDomains( 44 mac_folder_mapping[i].id, NSAllDomainsMask, true); 45 if ([searchpaths count] > 0) { 46 NSString *variable_value = [searchpaths objectAtIndex:0]; 47 result.replace(position, strlen(mac_folder_mapping[i].name), 48 base::SysNSStringToUTF8(variable_value)); 49 } 50 } 51 } 52 // Next translate two special variables ${user_name} and ${machine_name} 53 size_t position = result.find(kUserNamePolicyVarName); 54 if (position != std::string::npos) { 55 NSString* username = NSUserName(); 56 if (username) { 57 result.replace(position, strlen(kUserNamePolicyVarName), 58 base::SysNSStringToUTF8(username)); 59 } else { 60 LOG(ERROR) << "Username variable can not be resolved."; 61 } 62 } 63 position = result.find(kMachineNamePolicyVarName); 64 if (position != std::string::npos) { 65 NSString* machinename = [[NSHost currentHost] name]; 66 if (machinename) { 67 result.replace(position, strlen(kMachineNamePolicyVarName), 68 base::SysNSStringToUTF8(machinename)); 69 } else { 70 LOG(ERROR) << "Machine name variable can not be resolved."; 71 } 72 } 73 return result; 74} 75 76} // namespace path_parser 77 78} // namespace policy 79