2

I'm trying to make a web logging and I use getpwnam() function to check username existing. But for valid username getpwnam returns error: No such file or directory. So I tried getpwnam_r(), but it also failed with the same error. I'm running on embedded arm linux and I use /etc/passwd for password storing (I don't have /etc/shadow). My test program is:

#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int
main(int argc, char *argv[])
{
    struct passwd pwd;
    struct passwd *result;
    char *buf;
    size_t bufsize;
    int s;

   if (argc != 2) {
        fprintf(stderr, "Usage: %s username\n", argv[0]);
        exit(EXIT_FAILURE);
    }

   bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
    if (bufsize == -1)          /* Value was indeterminate */
        bufsize = 16384;        /* Should be more than enough */

   buf = malloc(bufsize);
    if (buf == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

   s = getpwnam_r(argv[1], &pwd, buf, bufsize, &result);
    if (result == NULL) {
        if (s == 0)
            printf("Not found\n");
        else {
            errno = s;
            perror("getpwnam_r");
        }
        exit(EXIT_FAILURE);
    }

   printf("Name: %s; UID: %ld\n", pwd.pw_gecos, (long) pwd.pw_uid);
    exit(EXIT_SUCCESS);
} 

Password file can be written only by root:

/ # ls -l /etc/passwd
-rw-r--r--    1 root     root           207 Jan  1 00:29 /etc/passwd
/ #

I also tried to run my program (test) with root rights, but it also failed when I gave it an existing username.

/ # /tmp/test admin
getpwnam_r: No such file or directory
/ # 

1) So, what I forgot about, or what should do additionally?

2) Do I need to use /etc/shadow file for storing passwords for system users?


Update:

My passwd file is:

~ # cat /etc/passwd 
root:b6MVch7fPLasN:0:0:root:/home/root:/bin/ash      
admin:8Mt/Jtxcyg8AY:1000:1000:admin:/tmp:/tmp/cli 
user:5v4HoPrA9NtUo:1001:1000:user:/tmp:/tmp/cli
~ #

Thanks in advance! Bakir

4

1 回答 1

1

1)密码数据库( /etc/passwd )中使用的搜索服务或方法在/etc/nsswitch.conf中定义。要使用此服务,getpwnam函数调用 lib 目录中的共享库:/lib/libnss_SERVICE.so.x,其中 SERVICE 是搜索方法。在我的情况下, compat是默认方法,因为没有/etc/nsswitch.conf。所以,我需要将 libnss_compat.so.2 添加到 /lib。

strace是有用的东西!

非常感谢osqxalk

于 2013-05-22T10:34:14.183 回答