user.c revision 362181
1/*
2 * user.c: APR wrapper functions for Subversion
3 *
4 * ====================================================================
5 *    Licensed to the Apache Software Foundation (ASF) under one
6 *    or more contributor license agreements.  See the NOTICE file
7 *    distributed with this work for additional information
8 *    regarding copyright ownership.  The ASF licenses this file
9 *    to you under the Apache License, Version 2.0 (the
10 *    "License"); you may not use this file except in compliance
11 *    with the License.  You may obtain a copy of the License at
12 *
13 *      http://www.apache.org/licenses/LICENSE-2.0
14 *
15 *    Unless required by applicable law or agreed to in writing,
16 *    software distributed under the License is distributed on an
17 *    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
18 *    KIND, either express or implied.  See the License for the
19 *    specific language governing permissions and limitations
20 *    under the License.
21 * ====================================================================
22 */
23
24
25#include <apr_pools.h>
26#include <apr_user.h>
27#include <apr_env.h>
28
29#include "svn_user.h"
30#include "svn_utf.h"
31#include "svn_dirent_uri.h"
32
33/* Get the current user's name from the OS */
34static const char *
35get_os_username(apr_pool_t *pool)
36{
37#if APR_HAS_USER
38  char *username;
39  apr_uid_t uid;
40  apr_gid_t gid;
41
42  if (apr_uid_current(&uid, &gid, pool) == APR_SUCCESS &&
43      apr_uid_name_get(&username, uid, pool) == APR_SUCCESS)
44    return username;
45#endif
46
47  return NULL;
48}
49
50/* Return a UTF8 version of STR, or NULL on error.
51   Use POOL for any necessary allocation. */
52static const char *
53utf8_or_nothing(const char *str, apr_pool_t *pool) {
54  if (str)
55    {
56      const char *utf8_str;
57      svn_error_t *err = svn_utf_cstring_to_utf8(&utf8_str, str, pool);
58      if (! err)
59        return utf8_str;
60      svn_error_clear(err);
61    }
62  return NULL;
63}
64
65const char *
66svn_user_get_name(apr_pool_t *pool)
67{
68  const char *username = get_os_username(pool);
69  return utf8_or_nothing(username, pool);
70}
71
72/* Most of the guts of svn_user_get_homedir(): everything except
73 * canonicalizing the path.
74 */
75static const char *
76user_get_homedir(apr_pool_t *pool)
77{
78  const char *username;
79  char *homedir;
80
81  if (apr_env_get(&homedir, "HOME", pool) == APR_SUCCESS)
82    return utf8_or_nothing(homedir, pool);
83
84  username = get_os_username(pool);
85  if (username != NULL &&
86      apr_uid_homepath_get(&homedir, username, pool) == APR_SUCCESS)
87    return utf8_or_nothing(homedir, pool);
88
89  return NULL;
90}
91
92const char *
93svn_user_get_homedir(apr_pool_t *pool)
94{
95  const char *homedir = user_get_homedir(pool);
96
97  if (homedir)
98    return svn_dirent_canonicalize(homedir, pool);
99
100  return NULL;
101}
102