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 "ruserpass.h"
11 #include "credentials.h"
12 #include "context_find.h"
16 #include "m_maildir.h"
19 char *host
; /* Hostname corresponding to credentials */
20 char *user
; /* Username corresponding to credentials */
21 char *pass
; /* (Optional) password used by credentials */
25 init_credentials_file(void)
27 if (credentials_file
== NULL
) {
28 char *cred_style
= context_find ("credentials");
30 if (cred_style
== NULL
|| ! strcmp (cred_style
, "legacy")) {
31 char *hdir
= getenv ("HOME");
33 credentials_file
= concat (hdir
? hdir
: ".", "/.netrc", NULL
);
34 } else if (! strncasecmp (cred_style
, "file:", 5) ||
35 ! strncasecmp (cred_style
, "file-nopermcheck:", 17)) {
37 char *filename
= strchr(cred_style
, ':') + 1;
39 while (isspace((unsigned char)*filename
))
42 if (*filename
== '/') {
43 credentials_file
= filename
;
45 credentials_file
= m_maildir (filename
);
46 if (stat (credentials_file
, &st
) != OK
) {
48 concat (mypath
? mypath
: ".", "/", filename
, NULL
);
49 if (stat (credentials_file
, &st
) != OK
) {
50 inform("unable to find credentials file %s, continuing...",
56 if (! strncasecmp (cred_style
, "file-nopermcheck:", 17))
57 credentials_no_perm_check
= 1;
63 nmh_get_credentials (const char *host
, const char *user
)
67 char *cred_style
= context_find ("credentials");
69 init_credentials_file ();
71 creds
= mh_xmalloc(sizeof(*creds
));
73 creds
->host
= mh_xstrdup(host
);
77 if (cred_style
== NULL
|| ! strcmp (cred_style
, "legacy")) {
78 creds
->user
= user
== NULL
? mh_xstrdup(getusername ()) : mh_xstrdup(user
);
79 } else if (! strncasecmp (cred_style
, "file:", 5) ||
80 ! strncasecmp (cred_style
, "file-nopermcheck:", 17)) {
82 * Determine user using the first of:
84 * 2) matching host entry with login in a credentials file
86 * 3) interactively request from user (as long as the
87 * credentials file didn't have a "default" token)
89 creds
->user
= user
== NULL
? NULL
: mh_xstrdup(user
);
91 inform("unknown credentials style %s, continuing...", cred_style
);
95 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
,
96 RUSERPASS_NO_PROMPT_USER
| RUSERPASS_NO_PROMPT_PASSWORD
);
102 * Retrieve the username
106 nmh_cred_get_user(nmh_creds_t creds
)
109 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
,
110 RUSERPASS_NO_PROMPT_PASSWORD
);
117 * Retrieve the password
121 nmh_cred_get_password(nmh_creds_t creds
)
124 ruserpass(creds
->host
, &creds
->user
, &creds
->pass
, 0);
131 * Free our credentials
135 nmh_credentials_free(nmh_creds_t creds
)
141 memset(creds
->pass
, 0, strlen(creds
->pass
));