pwd_grp.c 14 KB

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