The functions to access the shadow password file on Linux and Solaris are discussed in Section 6.3. We can't use the value returned in the pw_passwd field by the functions described in Section 6.2 to compare an encrypted password, since that field is not the encrypted password. Instead, we need to find the user's entry in the shadow file and use its encrypted password field.
On FreeBSD and Mac OS X, the password file is shadowed automatically. In the passwd structure returned by getpwnam and getpwuid, the pw_passwd field contains the encrypted password (only if the caller's effective user ID is 0 on FreeBSD, however).
6.2
The program in Figure C.4 prints the encrypted password on Linux and Solaris. Unless this program is run with superuser permissions, the call to getspnam fails with an error of EACCES.
Figure C.4. Print encrypted password under Linux and Solaris
Under FreeBSD, the program in Figure C.5 prints the encrypted password if the program is run with superuser permissions. Otherwise, the value returned in pw_passwd is an asterisk. On Mac OS X, the encrypted password is printed regardless of the permissions with which it is run.
Figure C.5. Print encrypted password under FreeBSD and Mac OS X
#include "apue.h" #include <pwd.h> int main(void) /* FreeBSD/Mac OS X version */ { struct passwd *ptr; if ((ptr = getpwnam("sar")) == NULL) err_sys("getpwnam error"); printf("pw_passwd = %s\n", ptr->pw_passwd == NULL || ptr->pw_passwd[0] == 0 ? "(null)" : ptr->pw_passwd); exit(0); }
6.5
The program shown in Figure C.6 prints the date in a format similar to date.
Figure C.6. Print the time and date in a format similar to date(1)
$ ./a.outauthor's default is US/Eastern Sun Feb 06 16:53:57 EST 2005 $ TZ=US/Mountain ./a.outU.S. Mountain time zone Sun Feb 06 14:53:57 MST 2005 $ TZ=Japan ./a.outJapan Mon Feb 07 06:53:57 JST 2005