1 /* credentials.c -- wrap configurable access to .netrc or similar files.
3 * This code is Copyright (c) 2013, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
13 char *host
; /* Hostname corresponding to credentials */
14 char *user
; /* Username corresponding to credentials */
15 char *pass
; /* (Optional) password used by credentials */
19 init_credentials_file () {
20 if (credentials_file
== NULL
) {
21 char *cred_style
= context_find ("credentials");
23 if (cred_style
== NULL
|| ! strcmp (cred_style
, "legacy")) {
24 char *hdir
= getenv ("HOME");
26 credentials_file
= concat (hdir
? hdir
: ".", "/.netrc", NULL
);
27 } else if (! strncasecmp (cred_style
, "file:", 5) ||
28 ! strncasecmp (cred_style
, "file-nopermcheck:", 17)) {
30 char *filename
= strchr(cred_style
, ':') + 1;
32 while (*filename
&& isspace ((unsigned char) *filename
)) ++filename
;
34 if (*filename
== '/') {
35 credentials_file
= filename
;
37 credentials_file
= m_maildir (filename
);
38 if (stat (credentials_file
, &st
) != OK
) {
40 concat (mypath
? mypath
: ".", "/", filename
, NULL
);
41 if (stat (credentials_file
, &st
) != OK
) {
42 inform("unable to find credentials file %s, continuing...",
48 if (! strncasecmp (cred_style
, "file-nopermcheck:", 17))
49 credentials_no_perm_check
= 1;
55 nmh_get_credentials (const char *host
, const char *user
)
59 char *cred_style
= context_find ("credentials");
61 init_credentials_file ();
63 creds
= mh_xmalloc(sizeof(*creds
));
65 creds
->host
= mh_xstrdup(host
);
69 if (cred_style
== NULL
|| ! strcmp (cred_style
, "legacy")) {
70 creds
->user
= user
== NULL
? mh_xstrdup(getusername ()) : mh_xstrdup(user
);
71 } else if (! strncasecmp (cred_style
, "file:", 5) ||
72 ! strncasecmp (cred_style
, "file-nopermcheck:", 17)) {
74 * Determine user using the first of:
76 * 2) matching host entry with login in a credentials file
78 * 3) interactively request from user (as long as the
79 * credentials file didn't have a "default" token)
81 creds
->user
= user
== NULL
? NULL
: mh_xstrdup(user
);
83 inform("unknown credentials style %s, continuing...", cred_style
);
87 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
,
88 RUSERPASS_NO_PROMPT_USER
| RUSERPASS_NO_PROMPT_PASSWORD
);
94 * Retrieve the username
98 nmh_cred_get_user(nmh_creds_t creds
)
101 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
,
102 RUSERPASS_NO_PROMPT_PASSWORD
);
109 * Retrieve the password
113 nmh_cred_get_password(nmh_creds_t creds
)
116 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
, 0);
123 * Free our credentials
127 nmh_credentials_free(nmh_creds_t creds
)
129 mh_xfree(creds
->host
);
130 mh_xfree(creds
->user
);
133 memset(creds
->pass
, 0, strlen(creds
->pass
));