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.
9 #include "credentials.h"
10 #include "context_find.h"
14 #include "m_maildir.h"
17 char *host
; /* Hostname corresponding to credentials */
18 char *user
; /* Username corresponding to credentials */
19 char *pass
; /* (Optional) password used by credentials */
23 init_credentials_file(void)
25 if (credentials_file
== NULL
) {
26 char *cred_style
= context_find ("credentials");
28 if (cred_style
== NULL
|| ! strcmp (cred_style
, "legacy")) {
29 char *hdir
= getenv ("HOME");
31 credentials_file
= concat (hdir
? hdir
: ".", "/.netrc", NULL
);
32 } else if (! strncasecmp (cred_style
, "file:", 5) ||
33 ! strncasecmp (cred_style
, "file-nopermcheck:", 17)) {
35 char *filename
= strchr(cred_style
, ':') + 1;
37 while (isspace((unsigned char)*filename
))
40 if (*filename
== '/') {
41 credentials_file
= filename
;
43 credentials_file
= m_maildir (filename
);
44 if (stat (credentials_file
, &st
) != OK
) {
46 concat (mypath
? mypath
: ".", "/", filename
, NULL
);
47 if (stat (credentials_file
, &st
) != OK
) {
48 inform("unable to find credentials file %s, continuing...",
54 if (! strncasecmp (cred_style
, "file-nopermcheck:", 17))
55 credentials_no_perm_check
= 1;
61 nmh_get_credentials (const char *host
, const char *user
)
65 char *cred_style
= context_find ("credentials");
67 init_credentials_file ();
69 creds
= mh_xmalloc(sizeof(*creds
));
71 creds
->host
= mh_xstrdup(host
);
75 if (cred_style
== NULL
|| ! strcmp (cred_style
, "legacy")) {
76 creds
->user
= user
== NULL
? mh_xstrdup(getusername ()) : mh_xstrdup(user
);
77 } else if (! strncasecmp (cred_style
, "file:", 5) ||
78 ! strncasecmp (cred_style
, "file-nopermcheck:", 17)) {
80 * Determine user using the first of:
82 * 2) matching host entry with login in a credentials file
84 * 3) interactively request from user (as long as the
85 * credentials file didn't have a "default" token)
87 creds
->user
= user
== NULL
? NULL
: mh_xstrdup(user
);
89 inform("unknown credentials style %s, continuing...", cred_style
);
93 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
,
94 RUSERPASS_NO_PROMPT_USER
| RUSERPASS_NO_PROMPT_PASSWORD
);
100 * Retrieve the username
104 nmh_cred_get_user(nmh_creds_t creds
)
107 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
,
108 RUSERPASS_NO_PROMPT_PASSWORD
);
115 * Retrieve the password
119 nmh_cred_get_password(nmh_creds_t creds
)
122 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
, 0);
129 * Free our credentials
133 nmh_credentials_free(nmh_creds_t creds
)
139 memset(creds
->pass
, 0, strlen(creds
->pass
));