pwd_grp.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Copyright (C) 2014 Tito Ragusa <farmatito@tiscali.it>
  4. *
  5. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  6. */
  7. /* This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY!!
  9. *
  10. * Rewrite of some parts. Main differences are:
  11. *
  12. * 1) the buffer for getpwuid, getgrgid, getpwnam, getgrnam is dynamically
  13. * allocated.
  14. * If ENABLE_FEATURE_CLEAN_UP is set the buffers are freed at program
  15. * exit using the atexit function to make valgrind happy.
  16. * 2) the passwd/group files:
  17. * a) must contain the expected number of fields (as per count of field
  18. * delimiters ":") or we will complain with a error message.
  19. * b) leading and trailing whitespace in fields is stripped.
  20. * c) some fields are not allowed to be empty (e.g. username, uid/gid),
  21. * and in this case NULL is returned and errno is set to EINVAL.
  22. * This behaviour could be easily changed by modifying PW_DEF, GR_DEF,
  23. * SP_DEF strings (uppercase makes a field mandatory).
  24. * d) the string representing uid/gid must be convertible by strtoXX
  25. * functions, or errno is set to EINVAL.
  26. * e) leading and trailing whitespace in group member names is stripped.
  27. * 3) the internal function for getgrouplist uses dynamically allocated buffer.
  28. * 4) at the moment only the functions really used by busybox code are
  29. * implemented, if you need a particular missing function it should be
  30. * easy to write it by using the internal common code.
  31. */
  32. #include "libbb.h"
  33. struct const_passdb {
  34. const char *filename;
  35. char def[7 + 2*ENABLE_USE_BB_SHADOW];
  36. uint8_t off[7 + 2*ENABLE_USE_BB_SHADOW];
  37. uint8_t numfields;
  38. uint8_t size_of;
  39. };
  40. struct passdb {
  41. const char *filename;
  42. char def[7 + 2*ENABLE_USE_BB_SHADOW];
  43. uint8_t off[7 + 2*ENABLE_USE_BB_SHADOW];
  44. uint8_t numfields;
  45. uint8_t size_of;
  46. FILE *fp;
  47. char *malloced;
  48. };
  49. /* Note: for shadow db, def[] will not contain terminating NUL,
  50. * but convert_to_struct() logic detects def[] end by "less than SP?",
  51. * not by "is it NUL?" condition; and off[0] happens to be zero
  52. * for every db anyway, so there _is_ in fact a terminating NUL there.
  53. */
  54. /* S = string not empty, s = string maybe empty,
  55. * I = uid,gid, l = long maybe empty, m = members,
  56. * r = reserved
  57. */
  58. #define PW_DEF "SsIIsss"
  59. #define GR_DEF "SsIm"
  60. #define SP_DEF "Ssllllllr"
  61. static const struct const_passdb const_pw_db = {
  62. _PATH_PASSWD, PW_DEF,
  63. {
  64. offsetof(struct passwd, pw_name), /* 0 S */
  65. offsetof(struct passwd, pw_passwd), /* 1 s */
  66. offsetof(struct passwd, pw_uid), /* 2 I */
  67. offsetof(struct passwd, pw_gid), /* 3 I */
  68. offsetof(struct passwd, pw_gecos), /* 4 s */
  69. offsetof(struct passwd, pw_dir), /* 5 s */
  70. offsetof(struct passwd, pw_shell) /* 6 s */
  71. },
  72. sizeof(PW_DEF)-1, sizeof(struct passwd)
  73. };
  74. static const struct const_passdb const_gr_db = {
  75. _PATH_GROUP, GR_DEF,
  76. {
  77. offsetof(struct group, gr_name), /* 0 S */
  78. offsetof(struct group, gr_passwd), /* 1 s */
  79. offsetof(struct group, gr_gid), /* 2 I */
  80. offsetof(struct group, gr_mem) /* 3 m (char **) */
  81. },
  82. sizeof(GR_DEF)-1, sizeof(struct group)
  83. };
  84. #if ENABLE_USE_BB_SHADOW
  85. static const struct const_passdb const_sp_db = {
  86. _PATH_SHADOW, SP_DEF,
  87. {
  88. offsetof(struct spwd, sp_namp), /* 0 S Login name */
  89. offsetof(struct spwd, sp_pwdp), /* 1 s Encrypted password */
  90. offsetof(struct spwd, sp_lstchg), /* 2 l */
  91. offsetof(struct spwd, sp_min), /* 3 l */
  92. offsetof(struct spwd, sp_max), /* 4 l */
  93. offsetof(struct spwd, sp_warn), /* 5 l */
  94. offsetof(struct spwd, sp_inact), /* 6 l */
  95. offsetof(struct spwd, sp_expire), /* 7 l */
  96. offsetof(struct spwd, sp_flag) /* 8 r Reserved */
  97. },
  98. sizeof(SP_DEF)-1, sizeof(struct spwd)
  99. };
  100. #endif
  101. /* We avoid having big global data. */
  102. struct statics {
  103. /* We use same buffer (db[0].malloced) for getpwuid and getpwnam.
  104. * Manpage says:
  105. * "The return value may point to a static area, and may be overwritten
  106. * by subsequent calls to getpwent(), getpwnam(), or getpwuid()."
  107. */
  108. struct passdb db[2 + ENABLE_USE_BB_SHADOW];
  109. char *tokenize_end;
  110. unsigned string_size;
  111. };
  112. static struct statics *ptr_to_statics;
  113. #define S (*ptr_to_statics)
  114. #define has_S (ptr_to_statics)
  115. #if ENABLE_FEATURE_CLEAN_UP
  116. static void free_static(void)
  117. {
  118. free(S.db[0].malloced);
  119. free(S.db[1].malloced);
  120. # if ENABLE_USE_BB_SHADOW
  121. free(S.db[2].malloced);
  122. # endif
  123. free(ptr_to_statics);
  124. }
  125. #endif
  126. static struct statics *get_S(void)
  127. {
  128. if (!ptr_to_statics) {
  129. ptr_to_statics = xzalloc(sizeof(S));
  130. memcpy(&S.db[0], &const_pw_db, sizeof(const_pw_db));
  131. memcpy(&S.db[1], &const_gr_db, sizeof(const_gr_db));
  132. #if ENABLE_USE_BB_SHADOW
  133. memcpy(&S.db[2], &const_sp_db, sizeof(const_sp_db));
  134. #endif
  135. #if ENABLE_FEATURE_CLEAN_UP
  136. atexit(free_static);
  137. #endif
  138. }
  139. return ptr_to_statics;
  140. }
  141. /* Internal functions */
  142. /* Divide the passwd/group/shadow record in fields
  143. * by substituting the given delimiter
  144. * e.g. ':' or ',' with '\0'.
  145. * Returns the number of fields found.
  146. * Strips leading and trailing whitespace in fields.
  147. */
  148. static int tokenize(char *buffer, int ch)
  149. {
  150. char *p = buffer;
  151. char *s = p;
  152. int num_fields = 0;
  153. for (;;) {
  154. if (isblank(*s)) {
  155. overlapping_strcpy(s, skip_whitespace(s));
  156. }
  157. if (*p == ch || *p == '\0') {
  158. char *end = p;
  159. while (p != s && isblank(p[-1]))
  160. p--;
  161. if (p != end)
  162. overlapping_strcpy(p, end);
  163. num_fields++;
  164. if (*end == '\0') {
  165. S.tokenize_end = p + 1;
  166. return num_fields;
  167. }
  168. *p = '\0';
  169. s = p + 1;
  170. }
  171. p++;
  172. }
  173. }
  174. /* Returns !NULL on success and matching line broken up in fields by '\0' in buf.
  175. * We require the expected number of fields to be found.
  176. */
  177. static char *parse_common(FILE *fp, struct passdb *db,
  178. const char *key, int field_pos)
  179. {
  180. char *buf;
  181. while ((buf = xmalloc_fgetline(fp)) != NULL) {
  182. /* Skip empty lines, comment lines */
  183. if (buf[0] == '\0' || buf[0] == '#')
  184. goto free_and_next;
  185. if (tokenize(buf, ':') != db->numfields) {
  186. /* number of fields is wrong */
  187. bb_error_msg("%s: bad record", db->filename);
  188. goto free_and_next;
  189. }
  190. if (field_pos == -1) {
  191. /* no key specified: sequential read, return a record */
  192. break;
  193. }
  194. if (strcmp(key, nth_string(buf, field_pos)) == 0) {
  195. /* record found */
  196. break;
  197. }
  198. free_and_next:
  199. free(buf);
  200. }
  201. S.string_size = S.tokenize_end - buf;
  202. /*
  203. * Ugly hack: group db requires additional buffer space
  204. * for members[] array. If there is only one group, we need space
  205. * for 3 pointers: alignment padding, group name, NULL.
  206. * +1 for every additional group.
  207. */
  208. if (buf && db->numfields == sizeof(GR_DEF)-1) { /* if we read group file... */
  209. int cnt = 3;
  210. char *p = buf;
  211. while (p < S.tokenize_end)
  212. if (*p++ == ',')
  213. cnt++;
  214. S.string_size += cnt * sizeof(char*);
  215. //bb_error_msg("+%d words = %u key:%s buf:'%s'", cnt, S.string_size, key, buf);
  216. buf = xrealloc(buf, S.string_size);
  217. }
  218. return buf;
  219. }
  220. static char *parse_file(struct passdb *db,
  221. const char *key, int field_pos)
  222. {
  223. char *buf = NULL;
  224. FILE *fp = fopen_for_read(db->filename);
  225. if (fp) {
  226. buf = parse_common(fp, db, key, field_pos);
  227. fclose(fp);
  228. }
  229. return buf;
  230. }
  231. /* Convert passwd/group/shadow file record in buffer to a struct */
  232. static void *convert_to_struct(struct passdb *db,
  233. char *buffer, void *result)
  234. {
  235. const char *def = db->def;
  236. const uint8_t *off = db->off;
  237. /* For consistency, zero out all fields */
  238. memset(result, 0, db->size_of);
  239. for (;;) {
  240. void *member = (char*)result + (*off++);
  241. if ((*def | 0x20) == 's') { /* s or S */
  242. *(char **)member = (char*)buffer;
  243. if (!buffer[0] && (*def == 'S')) {
  244. errno = EINVAL;
  245. }
  246. }
  247. if (*def == 'I') {
  248. *(int *)member = bb_strtou(buffer, NULL, 10);
  249. }
  250. #if ENABLE_USE_BB_SHADOW
  251. if (*def == 'l') {
  252. long n = -1;
  253. if (buffer[0])
  254. n = bb_strtol(buffer, NULL, 10);
  255. *(long *)member = n;
  256. }
  257. #endif
  258. if (*def == 'm') {
  259. char **members;
  260. int i = tokenize(buffer, ',');
  261. /* Store members[] after buffer's end.
  262. * This is safe ONLY because there is a hack
  263. * in parse_common() which allocates additional space
  264. * at the end of malloced buffer!
  265. */
  266. members = (char **)
  267. ( ((intptr_t)S.tokenize_end + sizeof(members[0]))
  268. & -(intptr_t)sizeof(members[0])
  269. );
  270. ((struct group *)result)->gr_mem = members;
  271. while (--i >= 0) {
  272. if (buffer[0]) {
  273. *members++ = buffer;
  274. // bb_error_msg("member[]='%s'", buffer);
  275. }
  276. buffer += strlen(buffer) + 1;
  277. }
  278. *members = NULL;
  279. }
  280. /* def "r" does nothing */
  281. def++;
  282. if ((unsigned char)*def <= (unsigned char)' ')
  283. break;
  284. buffer += strlen(buffer) + 1;
  285. }
  286. if (errno)
  287. result = NULL;
  288. return result;
  289. }
  290. static int massage_data_for_r_func(struct passdb *db,
  291. char *buffer, size_t buflen,
  292. void **result,
  293. char *buf)
  294. {
  295. void *result_buf = *result;
  296. *result = NULL;
  297. if (buf) {
  298. if (S.string_size > buflen) {
  299. errno = ERANGE;
  300. } else {
  301. memcpy(buffer, buf, S.string_size);
  302. *result = convert_to_struct(db, buffer, result_buf);
  303. }
  304. free(buf);
  305. }
  306. /* "The reentrant functions return zero on success.
  307. * In case of error, an error number is returned."
  308. * NB: not finding the record is also a "success" here:
  309. */
  310. return errno;
  311. }
  312. static void* massage_data_for_non_r_func(struct passdb *db, char *buf)
  313. {
  314. if (!buf)
  315. return NULL;
  316. free(db->malloced);
  317. /* We enlarge buf and move string data up, freeing space
  318. * for struct passwd/group/spwd at the beginning. This way,
  319. * entire result of getXXnam is in a single malloced block.
  320. * This enables easy creation of xmalloc_getpwnam() API.
  321. */
  322. db->malloced = buf = xrealloc(buf, db->size_of + S.string_size);
  323. memmove(buf + db->size_of, buf, S.string_size);
  324. return convert_to_struct(db, buf + db->size_of, buf);
  325. }
  326. /****** getXXnam/id_r */
  327. static int FAST_FUNC getXXnam_r(const char *name, uintptr_t db_and_field_pos,
  328. char *buffer, size_t buflen,
  329. void *result)
  330. {
  331. char *buf;
  332. struct passdb *db = &get_S()->db[db_and_field_pos >> 2];
  333. buf = parse_file(db, name, 0 /*db_and_field_pos & 3*/);
  334. /* "db_and_field_pos & 3" is commented out since so far we don't implement
  335. * getXXXid_r() functions which would use that to pass 2 here */
  336. return massage_data_for_r_func(db, buffer, buflen, result, buf);
  337. }
  338. int FAST_FUNC getpwnam_r(const char *name, struct passwd *struct_buf,
  339. char *buffer, size_t buflen,
  340. struct passwd **result)
  341. {
  342. /* Why the "store buffer address in result" trick?
  343. * This way, getXXnam_r has the same ABI signature as getpwnam_r,
  344. * hopefully compiler can optimize tail call better in this case.
  345. */
  346. *result = struct_buf;
  347. return getXXnam_r(name, (0 << 2) + 0, buffer, buflen, result);
  348. }
  349. #if ENABLE_USE_BB_SHADOW
  350. int FAST_FUNC getspnam_r(const char *name, struct spwd *struct_buf, char *buffer, size_t buflen,
  351. struct spwd **result)
  352. {
  353. *result = struct_buf;
  354. return getXXnam_r(name, (2 << 2) + 0, buffer, buflen, result);
  355. }
  356. #endif
  357. #ifdef UNUSED
  358. /****** getXXent_r */
  359. static int FAST_FUNC getXXent_r(uintptr_t db_idx, char *buffer, size_t buflen,
  360. void *result)
  361. {
  362. char *buf;
  363. struct passdb *db = &get_S()->db[db_idx];
  364. if (!db->fp) {
  365. db->fp = fopen_for_read(db->filename);
  366. if (!db->fp) {
  367. return errno;
  368. }
  369. close_on_exec_on(fileno(db->fp));
  370. }
  371. buf = parse_common(db->fp, db, /*no search key:*/ NULL, -1);
  372. if (!buf && !errno)
  373. errno = ENOENT;
  374. return massage_data_for_r_func(db, buffer, buflen, result, buf);
  375. }
  376. int FAST_FUNC getpwent_r(struct passwd *struct_buf, char *buffer, size_t buflen,
  377. struct passwd **result)
  378. {
  379. *result = struct_buf;
  380. return getXXent_r(0, buffer, buflen, result);
  381. }
  382. #endif
  383. /****** getXXent */
  384. static void* FAST_FUNC getXXent(uintptr_t db_idx)
  385. {
  386. char *buf;
  387. struct passdb *db = &get_S()->db[db_idx];
  388. if (!db->fp) {
  389. db->fp = fopen_for_read(db->filename);
  390. if (!db->fp) {
  391. return NULL;
  392. }
  393. close_on_exec_on(fileno(db->fp));
  394. }
  395. buf = parse_common(db->fp, db, /*no search key:*/ NULL, -1);
  396. return massage_data_for_non_r_func(db, buf);
  397. }
  398. struct passwd* FAST_FUNC getpwent(void)
  399. {
  400. return getXXent(0);
  401. }
  402. /****** getXXnam/id */
  403. static void* FAST_FUNC getXXnam(const char *name, unsigned db_and_field_pos)
  404. {
  405. char *buf;
  406. struct passdb *db = &get_S()->db[db_and_field_pos >> 2];
  407. buf = parse_file(db, name, db_and_field_pos & 3);
  408. return massage_data_for_non_r_func(db, buf);
  409. }
  410. struct passwd* FAST_FUNC getpwnam(const char *name)
  411. {
  412. return getXXnam(name, (0 << 2) + 0);
  413. }
  414. struct group* FAST_FUNC getgrnam(const char *name)
  415. {
  416. return getXXnam(name, (1 << 2) + 0);
  417. }
  418. struct passwd* FAST_FUNC getpwuid(uid_t id)
  419. {
  420. return getXXnam(utoa(id), (0 << 2) + 2);
  421. }
  422. struct group* FAST_FUNC getgrgid(gid_t id)
  423. {
  424. return getXXnam(utoa(id), (1 << 2) + 2);
  425. }
  426. /****** end/setXXend */
  427. void FAST_FUNC endpwent(void)
  428. {
  429. if (has_S && S.db[0].fp) {
  430. fclose(S.db[0].fp);
  431. S.db[0].fp = NULL;
  432. }
  433. }
  434. void FAST_FUNC setpwent(void)
  435. {
  436. if (has_S && S.db[0].fp) {
  437. rewind(S.db[0].fp);
  438. }
  439. }
  440. void FAST_FUNC endgrent(void)
  441. {
  442. if (has_S && S.db[1].fp) {
  443. fclose(S.db[1].fp);
  444. S.db[1].fp = NULL;
  445. }
  446. }
  447. /****** initgroups and getgrouplist */
  448. static gid_t* FAST_FUNC getgrouplist_internal(int *ngroups_ptr,
  449. const char *user, gid_t gid)
  450. {
  451. FILE *fp;
  452. gid_t *group_list;
  453. int ngroups;
  454. /* We alloc space for 8 gids at a time. */
  455. group_list = xzalloc(8 * sizeof(group_list[0]));
  456. group_list[0] = gid;
  457. ngroups = 1;
  458. fp = fopen_for_read(_PATH_GROUP);
  459. if (fp) {
  460. struct passdb *db = &get_S()->db[1];
  461. char *buf;
  462. while ((buf = parse_common(fp, db, NULL, -1)) != NULL) {
  463. char **m;
  464. struct group group;
  465. if (!convert_to_struct(db, buf, &group))
  466. goto next;
  467. if (group.gr_gid == gid)
  468. goto next;
  469. for (m = group.gr_mem; *m; m++) {
  470. if (strcmp(*m, user) != 0)
  471. continue;
  472. group_list = xrealloc_vector(group_list, /*8=2^3:*/ 3, ngroups);
  473. group_list[ngroups++] = group.gr_gid;
  474. goto next;
  475. }
  476. next:
  477. free(buf);
  478. }
  479. fclose(fp);
  480. }
  481. *ngroups_ptr = ngroups;
  482. return group_list;
  483. }
  484. int FAST_FUNC initgroups(const char *user, gid_t gid)
  485. {
  486. int ngroups;
  487. gid_t *group_list = getgrouplist_internal(&ngroups, user, gid);
  488. ngroups = setgroups(ngroups, group_list);
  489. free(group_list);
  490. return ngroups;
  491. }
  492. int FAST_FUNC getgrouplist(const char *user, gid_t gid, gid_t *groups, int *ngroups)
  493. {
  494. int ngroups_old = *ngroups;
  495. gid_t *group_list = getgrouplist_internal(ngroups, user, gid);
  496. if (*ngroups <= ngroups_old) {
  497. ngroups_old = *ngroups;
  498. memcpy(groups, group_list, ngroups_old * sizeof(groups[0]));
  499. } else {
  500. ngroups_old = -1;
  501. }
  502. free(group_list);
  503. return ngroups_old;
  504. }