10 #include <ne_request.h>
14 #include <ne_socket.h>
21 static pthread_once_t session_once
= PTHREAD_ONCE_INIT
;
22 static pthread_key_t session_tsd_key
;
27 static const char *username
= NULL
, *password
= NULL
;
28 const char *base_directory
= NULL
;
30 static pthread_mutex_t credential_mutex
= PTHREAD_MUTEX_INITIALIZER
;
33 static char* ask_user(char *p
, int hidden
) {
40 if (!isatty(fileno(stdin
)))
43 if (tcgetattr(fileno(stdin
), &t
) < 0)
48 if (tcsetattr(fileno(stdin
), TCSANOW
, &t
) < 0)
54 fprintf(stderr
, "%s: ", p
);
55 r
= fgets(q
, sizeof(q
), stdin
);
57 if (l
&& q
[l
-1] == '\n')
62 tcsetattr(fileno(stdin
), TCSANOW
, &t
);
63 fprintf(stderr
, "\n");
66 return r
? strdup(r
) : NULL
;
69 static int ssl_verify_cb(void *userdata
, int failures
, const ne_ssl_certificate
*cert
) {
73 static int ne_auth_creds_cb(void *userdata
, const char *realm
, int attempt
, char *u
, char *p
) {
77 pthread_mutex_lock(&credential_mutex
);
80 fprintf(stderr
, "Authenication failure!\n");
81 free((void*) username
);
82 free((void*) password
);
83 username
= password
= NULL
;
87 username
= ask_user("Username", 0);
89 if (username
&& !password
)
90 password
= ask_user("Password", 1);
92 if (username
&& password
) {
93 snprintf(u
, NE_ABUFSIZ
, "%s", username
);
94 snprintf(p
, NE_ABUFSIZ
, "%s", password
);
98 pthread_mutex_unlock(&credential_mutex
);
102 static ne_session
*session_open(void) {
109 scheme
= uri
.scheme
? uri
.scheme
: "http";
111 if (!(session
= ne_session_create(scheme
, uri
.host
, uri
.port
? uri
.port
: ne_uri_defaultport(scheme
)))) {
112 fprintf(stderr
, "Failed to create session\n");
116 ne_ssl_set_verify(session
, ssl_verify_cb
, NULL
);
117 ne_set_server_auth(session
, ne_auth_creds_cb
, NULL
);
121 static void session_destroy(void *s
) {
122 ne_session
*session
= s
;
124 ne_session_destroy(session
);
127 static void session_tsd_key_init(void) {
128 pthread_key_create(&session_tsd_key
, session_destroy
);
131 ne_session
*session_get(void) {
134 pthread_once(&session_once
, session_tsd_key_init
);
136 if ((session
= pthread_getspecific(session_tsd_key
)))
139 session
= session_open();
140 pthread_setspecific(session_tsd_key
, session
);
145 int session_set_uri(const char *s
, const char *u
, const char *p
) {
146 assert(!b_uri
&& !username
&& !password
);
149 if (ne_uri_parse(s
, &uri
)) {
150 fprintf(stderr
, "Invalid URI <%s>\n", s
);
157 fprintf(stderr
, "Missing host part in URI <%s>\n", s
);
161 base_directory
= strdup(uri
.path
);
162 l
= strlen(base_directory
);
163 if (base_directory
[l
-1] == '/')
164 ((char*) base_directory
)[l
-1] = 0;
167 username
= strdup(u
);
170 password
= strdup(p
);
185 void session_free(void) {
191 free((char*) username
);
192 free((char*) password
);
193 free((char*) base_directory
);
195 username
= password
= base_directory
= NULL
;