1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *  * Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 *  * Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in
12 *    the documentation and/or other materials provided with the
13 *    distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <ctype.h>
30#include <errno.h>
31#include <grp.h>
32#include <mntent.h>
33#include <netdb.h>
34#include <pthread.h>
35#include <pwd.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <unistd.h>
39
40#include "private/android_filesystem_config.h"
41#include "private/ErrnoRestorer.h"
42#include "private/libc_logging.h"
43
44// Thread-specific state for the non-reentrant functions.
45static pthread_once_t stubs_once = PTHREAD_ONCE_INIT;
46static pthread_key_t stubs_key;
47struct stubs_state_t {
48  passwd passwd_;
49  group group_;
50  char* group_members_[2];
51  char app_name_buffer_[32];
52  char group_name_buffer_[32];
53  char dir_buffer_[32];
54  char sh_buffer_[32];
55};
56
57static int do_getpw_r(int by_name, const char* name, uid_t uid,
58                      passwd* dst, char* buf, size_t byte_count,
59                      passwd** result) {
60  // getpwnam_r and getpwuid_r don't modify errno, but library calls we
61  // make might.
62  ErrnoRestorer errno_restorer;
63  *result = NULL;
64
65  // Our implementation of getpwnam(3) and getpwuid(3) use thread-local
66  // storage, so we can call them as long as we copy everything out
67  // before returning.
68  const passwd* src = by_name ? getpwnam(name) : getpwuid(uid); // NOLINT: see above.
69
70  // POSIX allows failure to find a match to be considered a non-error.
71  // Reporting success (0) but with *result NULL is glibc's behavior.
72  if (src == NULL) {
73    return (errno == ENOENT) ? 0 : errno;
74  }
75
76  // Work out where our strings will go in 'buf', and whether we've got
77  // enough space.
78  size_t required_byte_count = 0;
79  dst->pw_name = buf;
80  required_byte_count += strlen(src->pw_name) + 1;
81  dst->pw_dir = buf + required_byte_count;
82  required_byte_count += strlen(src->pw_dir) + 1;
83  dst->pw_shell = buf + required_byte_count;
84  required_byte_count += strlen(src->pw_shell) + 1;
85  if (byte_count < required_byte_count) {
86    return ERANGE;
87  }
88
89  // Copy the strings.
90  snprintf(buf, byte_count, "%s%c%s%c%s", src->pw_name, 0, src->pw_dir, 0, src->pw_shell);
91
92  // pw_passwd is non-POSIX and unused (always NULL) in bionic.
93  // pw_gecos is non-POSIX and missing in bionic.
94  dst->pw_passwd = NULL;
95
96  // Copy the integral fields.
97  dst->pw_gid = src->pw_gid;
98  dst->pw_uid = src->pw_uid;
99
100  *result = dst;
101  return 0;
102}
103
104int getpwnam_r(const char* name, passwd* pwd,
105               char* buf, size_t byte_count, passwd** result) {
106  return do_getpw_r(1, name, -1, pwd, buf, byte_count, result);
107}
108
109int getpwuid_r(uid_t uid, passwd* pwd,
110               char* buf, size_t byte_count, passwd** result) {
111  return do_getpw_r(0, NULL, uid, pwd, buf, byte_count, result);
112}
113
114static stubs_state_t* stubs_state_alloc() {
115  stubs_state_t*  s = static_cast<stubs_state_t*>(calloc(1, sizeof(*s)));
116  if (s != NULL) {
117    s->group_.gr_mem = s->group_members_;
118  }
119  return s;
120}
121
122static void stubs_state_free(void* ptr) {
123  stubs_state_t* state = static_cast<stubs_state_t*>(ptr);
124  free(state);
125}
126
127static void __stubs_key_init() {
128  pthread_key_create(&stubs_key, stubs_state_free);
129}
130
131static stubs_state_t* __stubs_state() {
132  pthread_once(&stubs_once, __stubs_key_init);
133  stubs_state_t* s = static_cast<stubs_state_t*>(pthread_getspecific(stubs_key));
134  if (s == NULL) {
135    s = stubs_state_alloc();
136    if (s == NULL) {
137      errno = ENOMEM;  // Just in case.
138    } else {
139      if (pthread_setspecific(stubs_key, s) != 0) {
140        stubs_state_free(s);
141        errno = ENOMEM;
142        s = NULL;
143      }
144    }
145  }
146  return s;
147}
148
149static passwd* android_iinfo_to_passwd(stubs_state_t* state,
150                                       const android_id_info* iinfo) {
151  snprintf(state->dir_buffer_, sizeof(state->dir_buffer_), "/");
152  snprintf(state->sh_buffer_, sizeof(state->sh_buffer_), "/system/bin/sh");
153
154  passwd* pw = &state->passwd_;
155  pw->pw_name  = (char*) iinfo->name;
156  pw->pw_uid   = iinfo->aid;
157  pw->pw_gid   = iinfo->aid;
158  pw->pw_dir   = state->dir_buffer_;
159  pw->pw_shell = state->sh_buffer_;
160  return pw;
161}
162
163static group* android_iinfo_to_group(group* gr,
164                                     const android_id_info* iinfo) {
165  gr->gr_name   = (char*) iinfo->name;
166  gr->gr_gid    = iinfo->aid;
167  gr->gr_mem[0] = gr->gr_name;
168  gr->gr_mem[1] = NULL;
169  return gr;
170}
171
172static passwd* android_id_to_passwd(stubs_state_t* state, unsigned id) {
173  for (size_t n = 0; n < android_id_count; ++n) {
174    if (android_ids[n].aid == id) {
175      return android_iinfo_to_passwd(state, android_ids + n);
176    }
177  }
178  return NULL;
179}
180
181static passwd* android_name_to_passwd(stubs_state_t* state, const char* name) {
182  for (size_t n = 0; n < android_id_count; ++n) {
183    if (!strcmp(android_ids[n].name, name)) {
184      return android_iinfo_to_passwd(state, android_ids + n);
185    }
186  }
187  return NULL;
188}
189
190static group* android_id_to_group(group* gr, unsigned id) {
191  for (size_t n = 0; n < android_id_count; ++n) {
192    if (android_ids[n].aid == id) {
193      return android_iinfo_to_group(gr, android_ids + n);
194    }
195  }
196  return NULL;
197}
198
199static group* android_name_to_group(group* gr, const char* name) {
200  for (size_t n = 0; n < android_id_count; ++n) {
201    if (!strcmp(android_ids[n].name, name)) {
202      return android_iinfo_to_group(gr, android_ids + n);
203    }
204  }
205  return NULL;
206}
207
208// Translate a user/group name to the corresponding user/group id.
209// u0_a1234 -> 0 * AID_USER + AID_APP + 1234
210// u2_i1000 -> 2 * AID_USER + AID_ISOLATED_START + 1000
211// u1_system -> 1 * AID_USER + android_ids['system']
212// returns 0 and sets errno to ENOENT in case of error
213static unsigned app_id_from_name(const char* name) {
214  if (name[0] != 'u' || !isdigit(name[1])) {
215    errno = ENOENT;
216    return 0;
217  }
218
219  char* end;
220  unsigned long userid = strtoul(name+1, &end, 10);
221  if (end[0] != '_' || end[1] == 0) {
222    errno = ENOENT;
223    return 0;
224  }
225
226  unsigned long appid = 0;
227  if (end[1] == 'a' && isdigit(end[2])) {
228    // end will point to \0 if the strtoul below succeeds.
229    appid = strtoul(end+2, &end, 10) + AID_APP;
230  } else if (end[1] == 'i' && isdigit(end[2])) {
231    // end will point to \0 if the strtoul below succeeds.
232    appid = strtoul(end+2, &end, 10) + AID_ISOLATED_START;
233  } else {
234    for (size_t n = 0; n < android_id_count; n++) {
235      if (!strcmp(android_ids[n].name, end + 1)) {
236        appid = android_ids[n].aid;
237        // Move the end pointer to the null terminator.
238        end += strlen(android_ids[n].name) + 1;
239      }
240    }
241  }
242
243  // Check that the entire string was consumed by one of the 3 cases above.
244  if (end[0] != 0) {
245    errno = ENOENT;
246    return 0;
247  }
248
249  // Check that user id won't overflow.
250  if (userid > 1000) {
251    errno = ENOENT;
252    return 0;
253  }
254
255  // Check that app id is within range.
256  if (appid >= AID_USER) {
257    errno = ENOENT;
258    return 0;
259  }
260
261  return (unsigned)(appid + userid*AID_USER);
262}
263
264static void print_app_name_from_appid_userid(const uid_t appid,
265    const uid_t userid, char* buffer, const int bufferlen) {
266  if (appid >= AID_ISOLATED_START) {
267    snprintf(buffer, bufferlen, "u%u_i%u", userid, appid - AID_ISOLATED_START);
268  } else if (userid == 0 && appid >= AID_SHARED_GID_START) {
269    snprintf(buffer, bufferlen, "all_a%u", appid - AID_SHARED_GID_START);
270  } else if (appid < AID_APP) {
271    for (size_t n = 0; n < android_id_count; n++) {
272      if (android_ids[n].aid == appid) {
273        snprintf(buffer, bufferlen, "u%u_%s", userid, android_ids[n].name);
274        return;
275      }
276    }
277  } else {
278    snprintf(buffer, bufferlen, "u%u_a%u", userid, appid - AID_APP);
279  }
280}
281
282static void print_app_name_from_uid(const uid_t uid, char* buffer, const int bufferlen) {
283  const uid_t appid = uid % AID_USER;
284  const uid_t userid = uid / AID_USER;
285  return print_app_name_from_appid_userid(appid, userid, buffer, bufferlen);
286}
287
288// Translate a uid into the corresponding name.
289// 0 to AID_APP-1                   -> "system", "radio", etc.
290// AID_APP to AID_ISOLATED_START-1  -> u0_a1234
291// AID_ISOLATED_START to AID_USER-1 -> u0_i1234
292// AID_USER+                        -> u1_radio, u1_a1234, u2_i1234, etc.
293// returns a passwd structure (sets errno to ENOENT on failure).
294static passwd* app_id_to_passwd(uid_t uid, stubs_state_t* state) {
295  passwd* pw = &state->passwd_;
296
297  if (uid < AID_APP) {
298    errno = ENOENT;
299    return NULL;
300  }
301
302  const uid_t appid = uid % AID_USER;
303  const uid_t userid = uid / AID_USER;
304
305  print_app_name_from_appid_userid(appid, userid, state->app_name_buffer_,
306                                   sizeof(state->app_name_buffer_));
307
308  if (appid < AID_APP) {
309      snprintf(state->dir_buffer_, sizeof(state->dir_buffer_), "/");
310  } else {
311      snprintf(state->dir_buffer_, sizeof(state->dir_buffer_), "/data");
312  }
313
314  snprintf(state->sh_buffer_, sizeof(state->sh_buffer_), "/system/bin/sh");
315
316  pw->pw_name  = state->app_name_buffer_;
317  pw->pw_dir   = state->dir_buffer_;
318  pw->pw_shell = state->sh_buffer_;
319  pw->pw_uid   = uid;
320  pw->pw_gid   = uid;
321
322  return pw;
323}
324
325// Translate a gid into the corresponding app_<gid>
326// group structure (sets errno to ENOENT on failure).
327static group* app_id_to_group(gid_t gid, stubs_state_t* state) {
328  if (gid < AID_APP) {
329    errno = ENOENT;
330    return NULL;
331  }
332
333  print_app_name_from_uid(gid, state->group_name_buffer_,
334                          sizeof(state->group_name_buffer_));
335
336  group* gr = &state->group_;
337  gr->gr_name   = state->group_name_buffer_;
338  gr->gr_gid    = gid;
339  gr->gr_mem[0] = gr->gr_name;
340  gr->gr_mem[1] = NULL;
341  return gr;
342}
343
344
345passwd* getpwuid(uid_t uid) { // NOLINT: implementing bad function.
346  stubs_state_t* state = __stubs_state();
347  if (state == NULL) {
348    return NULL;
349  }
350
351  passwd* pw = android_id_to_passwd(state, uid);
352  if (pw != NULL) {
353    return pw;
354  }
355  return app_id_to_passwd(uid, state);
356}
357
358passwd* getpwnam(const char* login) { // NOLINT: implementing bad function.
359  stubs_state_t* state = __stubs_state();
360  if (state == NULL) {
361    return NULL;
362  }
363
364  passwd* pw = android_name_to_passwd(state, login);
365  if (pw != NULL) {
366    return pw;
367  }
368  return app_id_to_passwd(app_id_from_name(login), state);
369}
370
371// All users are in just one group, the one passed in.
372int getgrouplist(const char* /*user*/, gid_t group, gid_t* groups, int* ngroups) {
373    if (*ngroups < 1) {
374        *ngroups = 1;
375        return -1;
376    }
377    groups[0] = group;
378    return (*ngroups = 1);
379}
380
381char* getlogin() { // NOLINT: implementing bad function.
382  passwd *pw = getpwuid(getuid()); // NOLINT: implementing bad function in terms of bad function.
383  return (pw != NULL) ? pw->pw_name : NULL;
384}
385
386group* getgrgid(gid_t gid) { // NOLINT: implementing bad function.
387  stubs_state_t* state = __stubs_state();
388  if (state == NULL) {
389    return NULL;
390  }
391
392  group* gr = android_id_to_group(&state->group_, gid);
393  if (gr != NULL) {
394    return gr;
395  }
396
397  return app_id_to_group(gid, state);
398}
399
400group* getgrnam(const char* name) { // NOLINT: implementing bad function.
401  stubs_state_t* state = __stubs_state();
402  if (state == NULL) {
403    return NULL;
404  }
405
406  if (android_name_to_group(&state->group_, name) != 0) {
407    return &state->group_;
408  }
409
410  return app_id_to_group(app_id_from_name(name), state);
411}
412
413// We don't have an /etc/networks, so all inputs return NULL.
414netent* getnetbyname(const char* /*name*/) {
415  return NULL;
416}
417
418// We don't have an /etc/networks, so all inputs return NULL.
419netent* getnetbyaddr(uint32_t /*net*/, int /*type*/) {
420  return NULL;
421}
422
423// We don't have an /etc/protocols, so all inputs return NULL.
424protoent* getprotobyname(const char* /*name*/) {
425  return NULL;
426}
427
428// We don't have an /etc/protocols, so all inputs return NULL.
429protoent* getprotobynumber(int /*proto*/) {
430  return NULL;
431}
432
433static void unimplemented_stub(const char* function) {
434  const char* fmt = "%s(3) is not implemented on Android\n";
435  __libc_format_log(ANDROID_LOG_WARN, "libc", fmt, function);
436  fprintf(stderr, fmt, function);
437}
438
439#define UNIMPLEMENTED unimplemented_stub(__PRETTY_FUNCTION__)
440
441void endpwent() {
442  UNIMPLEMENTED;
443}
444
445mntent* getmntent(FILE* /*f*/) {
446  UNIMPLEMENTED;
447  return NULL;
448}
449
450char* ttyname(int /*fd*/) { // NOLINT: implementing bad function.
451  UNIMPLEMENTED;
452  return NULL;
453}
454
455int ttyname_r(int /*fd*/, char* /*buf*/, size_t /*buflen*/) {
456  UNIMPLEMENTED;
457  return -ERANGE;
458}
459
460char* getusershell() {
461  UNIMPLEMENTED;
462  return NULL;
463}
464
465void setusershell() {
466  UNIMPLEMENTED;
467}
468
469void endusershell() {
470  UNIMPLEMENTED;
471}
472