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.
4
5#include <pwd.h>
6#include <sys/types.h>
7#include <unistd.h>
8
9#include "chrome/browser/policy/policy_path_parser.h"
10
11#include "base/logging.h"
12
13namespace policy {
14
15namespace path_parser {
16
17const char* kMachineNamePolicyVarName = "${machine_name}";
18const char* kUserNamePolicyVarName = "${user_name}";
19
20// Replaces all variable occurrences in the policy string with the respective
21// system settings values.
22base::FilePath::StringType ExpandPathVariables(
23    const base::FilePath::StringType& untranslated_string) {
24  base::FilePath::StringType result(untranslated_string);
25  if (result.length() == 0)
26    return result;
27  // Sanitize quotes in case of any around the whole string.
28  if (result.length() > 1 &&
29      ((result[0] == '"' && result[result.length() - 1] == '"') ||
30      (result[0] == '\'' && result[result.length() - 1] == '\''))) {
31    // Strip first and last char which should be matching quotes now.
32    result = result.substr(1, result.length() - 2);
33  }
34  // Translate two special variables ${user_name} and ${machine_name}
35  size_t position = result.find(kUserNamePolicyVarName);
36  if (position != std::string::npos) {
37    struct passwd* user = getpwuid(geteuid());
38    if (user) {
39      result.replace(position, strlen(kUserNamePolicyVarName), user->pw_name);
40    } else {
41      LOG(ERROR) << "Username variable can not be resolved. ";
42    }
43  }
44  position = result.find(kMachineNamePolicyVarName);
45  if (position != std::string::npos) {
46    char machinename[255];
47    if (gethostname(machinename, 255) == 0) {
48      result.replace(position, strlen(kMachineNamePolicyVarName), machinename);
49    } else {
50      LOG(ERROR) << "Machine name variable can not be resolved.";
51    }
52  }
53  return result;
54}
55
56void CheckUserDataDirPolicy(base::FilePath* user_data_dir) {
57  // This function is not implemented in Linux because we don't support the
58  // policy on this platform.
59  NOTREACHED();
60}
61
62}  // namespace path_parser
63
64}  // namespace policy
65