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.
10 #include "credentials.h"
11 #include "context_find.h"
15 #include "m_maildir.h"
18 char *host
; /* Hostname corresponding to credentials */
19 char *user
; /* Username corresponding to credentials */
20 char *pass
; /* (Optional) password used by credentials */
24 init_credentials_file(void)
26 if (credentials_file
== NULL
) {
27 char *cred_style
= context_find ("credentials");
29 if (cred_style
== NULL
|| ! strcmp (cred_style
, "legacy")) {
30 char *hdir
= getenv ("HOME");
32 credentials_file
= concat (hdir
? hdir
: ".", "/.netrc", NULL
);
33 } else if (! strncasecmp (cred_style
, "file:", 5) ||
34 ! strncasecmp (cred_style
, "file-nopermcheck:", 17)) {
36 char *filename
= strchr(cred_style
, ':') + 1;
38 while (isspace((unsigned char)*filename
))
41 if (*filename
== '/') {
42 credentials_file
= filename
;
44 credentials_file
= m_maildir (filename
);
45 if (stat (credentials_file
, &st
) != OK
) {
47 concat (mypath
? mypath
: ".", "/", filename
, NULL
);
48 if (stat (credentials_file
, &st
) != OK
) {
49 inform("unable to find credentials file %s, continuing...",
55 if (! strncasecmp (cred_style
, "file-nopermcheck:", 17))
56 credentials_no_perm_check
= 1;
62 nmh_get_credentials (const char *host
, const char *user
)
66 char *cred_style
= context_find ("credentials");
68 init_credentials_file ();
70 creds
= mh_xmalloc(sizeof(*creds
));
72 creds
->host
= mh_xstrdup(host
);
76 if (cred_style
== NULL
|| ! strcmp (cred_style
, "legacy")) {
77 creds
->user
= user
== NULL
? mh_xstrdup(getusername ()) : mh_xstrdup(user
);
78 } else if (! strncasecmp (cred_style
, "file:", 5) ||
79 ! strncasecmp (cred_style
, "file-nopermcheck:", 17)) {
81 * Determine user using the first of:
83 * 2) matching host entry with login in a credentials file
85 * 3) interactively request from user (as long as the
86 * credentials file didn't have a "default" token)
88 creds
->user
= user
== NULL
? NULL
: mh_xstrdup(user
);
90 inform("unknown credentials style %s, continuing...", cred_style
);
94 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
,
95 RUSERPASS_NO_PROMPT_USER
| RUSERPASS_NO_PROMPT_PASSWORD
);
101 * Retrieve the username
105 nmh_cred_get_user(nmh_creds_t creds
)
108 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
,
109 RUSERPASS_NO_PROMPT_PASSWORD
);
116 * Retrieve the password
120 nmh_cred_get_password(nmh_creds_t creds
)
123 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
, 0);
130 * Free our credentials
134 nmh_credentials_free(nmh_creds_t creds
)
140 memset(creds
->pass
, 0, strlen(creds
->pass
));