It is safer to walk the pointers given at gr_mem since there is no * guarantee the gr_mem + strings are contiguous in the given struct group * but compactify the new group into the following form. * * The new struct is laid out like this in memory. The example given is * for a group with two members only. * * { * (char *name) * (char *passwd) * (int gid) * (gr_mem * newgrp + sizeof(stru
| 514 | * Copy the contents of a group plus given name to a preallocated group struct |
| 515 | */ |
| 516 | static struct group * |
| 517 | grcopy(const struct group *gr, char *dst, const char *name, int ndx) |
| 518 | { |
| 519 | int i; |
| 520 | struct group *newgr; |
| 521 | |
| 522 | newgr = (struct group *)(void *)dst; /* avoid alignment warning */ |
| 523 | dst += sizeof(*newgr); |
| 524 | if (ndx != 0) { |
| 525 | newgr->gr_mem = (char **)(void *)(dst); /* avoid alignment warning */ |
| 526 | dst += (ndx + 1) * sizeof(*newgr->gr_mem); |
| 527 | } else |
| 528 | newgr->gr_mem = NULL; |
| 529 | if (gr->gr_name != NULL) { |
| 530 | newgr->gr_name = dst; |
| 531 | dst = stpcpy(dst, gr->gr_name) + 1; |
| 532 | } else |
| 533 | newgr->gr_name = NULL; |
| 534 | if (gr->gr_passwd != NULL) { |
| 535 | newgr->gr_passwd = dst; |
| 536 | dst = stpcpy(dst, gr->gr_passwd) + 1; |
| 537 | } else |
| 538 | newgr->gr_passwd = NULL; |
| 539 | newgr->gr_gid = gr->gr_gid; |
| 540 | i = 0; |
| 541 | /* Original group struct might have a NULL gr_mem */ |
| 542 | if (gr->gr_mem != NULL) { |
| 543 | for (; gr->gr_mem[i] != NULL; i++) { |
| 544 | newgr->gr_mem[i] = dst; |
| 545 | dst = stpcpy(dst, gr->gr_mem[i]) + 1; |
| 546 | } |
| 547 | } |
| 548 | /* If name is not NULL, newgr->gr_mem is known to be not NULL */ |
| 549 | if (name != NULL) { |
| 550 | newgr->gr_mem[i++] = dst; |
| 551 | dst = stpcpy(dst, name) + 1; |
| 552 | } |
| 553 | /* if newgr->gr_mem is not NULL add NULL marker */ |
| 554 | if (newgr->gr_mem != NULL) |
| 555 | newgr->gr_mem[i] = NULL; |
| 556 | |
| 557 | return (newgr); |
| 558 | } |
| 559 | |
| 560 | /* |
| 561 | * Calculate length of a struct group + given name |