2 * Functions that handle communication with a Citadel Server
4 * Copyright (c) 1987-2016 by the citadel.org team
6 * This program is open source software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 3.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
17 struct ctdlsession *cpool = NULL; // linked list of connections to the Citadel server
18 pthread_mutex_t cpool_mutex = PTHREAD_MUTEX_INITIALIZER; // Lock it before modifying
22 * Read a newline-terminated line of text from the Citadel server.
23 * Implemented in terms of client_read() and is therefore transparent...
24 * Returns the string length or -1 for error.
26 int ctdl_readline(struct ctdlsession *ctdl, char *buf, int maxbytes)
31 if (buf == NULL) return;
33 while (len < maxbytes) {
34 c = read(ctdl->sock, &buf[len], 1);
36 syslog(LOG_DEBUG, "Socket error or zero-length read");
39 if (buf[len] == '\n') {
40 if ( (len >0) && (buf[len-1] == '\r') ) {
44 // syslog(LOG_DEBUG, "[ %s", buf);
49 // syslog(LOG_DEBUG, "[ %s", buf);
55 * Read lines of text from the Citadel server until a 000 terminator is received.
56 * Implemented in terms of ctdl_readline() and is therefore transparent...
57 * Returns a newly allocated StrBuf or NULL for error.
59 StrBuf *ctdl_readtextmsg(struct ctdlsession *ctdl)
62 StrBuf *sj = NewStrBuf();
67 while ( (ctdl_readline(ctdl, buf, sizeof(buf)) >= 0) && (strcmp(buf, "000")) ) {
68 StrBufAppendPrintf(sj, "%s\n", buf);
76 * Write to the Citadel server. For now we're just wrapping write() in case we
77 * need to add anything else later.
79 ssize_t ctdl_write(struct ctdlsession *ctdl, const void *buf, size_t count) {
80 return write(ctdl->sock, buf, count);
85 * printf() type function to send data to the Citadel Server.
87 void ctdl_printf(struct ctdlsession *ctdl, const char *format,...)
90 StrBuf *Buf = NewStrBuf();
92 va_start(arg_ptr, format);
93 StrBufVAppendPrintf(Buf, format, arg_ptr);
96 // syslog(LOG_DEBUG, "] %s", ChrPtr(Buf));
97 ctdl_write(ctdl, (char *)ChrPtr(Buf), StrLength(Buf));
98 ctdl_write(ctdl, "\n", 1);
104 * Client side - connect to a unix domain socket
106 int uds_connectsock(char *sockpath)
108 struct sockaddr_un addr;
111 memset(&addr, 0, sizeof(addr));
112 addr.sun_family = AF_UNIX;
113 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
115 s = socket(AF_UNIX, SOCK_STREAM, 0);
117 syslog(LOG_WARNING, "Can't create socket [%s]: %s", sockpath, strerror(errno));
121 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
122 syslog(LOG_WARNING, "Can't connect [%s]: %s", sockpath, strerror(errno));
131 * TCP client - connect to a host/port
133 int tcp_connectsock(char *host, char *service)
135 struct in6_addr serveraddr;
136 struct addrinfo hints;
137 struct addrinfo *res = NULL;
138 struct addrinfo *ai = NULL;
142 if ((host == NULL) || IsEmptyStr(host))
144 if ((service == NULL) || IsEmptyStr(service))
147 syslog(LOG_DEBUG, "tcp_connectsock(%s,%s)", host, service);
149 memset(&hints, 0x00, sizeof(hints));
150 hints.ai_flags = AI_NUMERICSERV;
151 hints.ai_family = AF_UNSPEC;
152 hints.ai_socktype = SOCK_STREAM;
155 * Handle numeric IPv4 and IPv6 addresses
157 rc = inet_pton(AF_INET, host, &serveraddr);
158 if (rc == 1) { /* dotted quad */
159 hints.ai_family = AF_INET;
160 hints.ai_flags |= AI_NUMERICHOST;
162 rc = inet_pton(AF_INET6, host, &serveraddr);
163 if (rc == 1) { /* IPv6 address */
164 hints.ai_family = AF_INET6;
165 hints.ai_flags |= AI_NUMERICHOST;
169 /* Begin the connection process */
171 rc = getaddrinfo(host, service, &hints, &res);
173 syslog(LOG_DEBUG, "%s: %s", host, gai_strerror(rc));
179 * Try all available addresses until we connect to one or until we run out.
181 for (ai = res; ai != NULL; ai = ai->ai_next) {
183 if (ai->ai_family == AF_INET) syslog(LOG_DEBUG, "Trying IPv4");
184 else if (ai->ai_family == AF_INET6) syslog(LOG_DEBUG, "Trying IPv6");
185 else syslog(LOG_WARNING, "This is going to fail.");
187 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
189 syslog(LOG_WARNING, "socket() failed: %s", strerror(errno));
193 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
198 fdflags = fcntl(rc, F_GETFL);
201 "unable to get socket %d flags! %s",
207 fdflags = fdflags | O_NONBLOCK;
208 if (fcntl(rc, F_SETFL, fdflags) < 0) {
210 "unable to set socket %d nonblocking flags! %s",
220 syslog(LOG_WARNING, "connect() failed: %s", strerror(errno));
230 * Extract from the headers, the username and password the client is attempting to use.
231 * This could be HTTP AUTH or it could be in the cookies.
233 void extract_auth(struct http_transaction *h, char *authbuf, int authbuflen)
235 if (authbuf == NULL) return;
238 char *authheader = header_val(h, "Authorization");
240 if (!strncasecmp(authheader, "Basic ", 6)) {
241 safestrncpy(authbuf, &authheader[6], authbuflen);
242 return; // HTTP-AUTH was found -- stop here
246 char *cookieheader = header_val(h, "Cookie");
248 char *wcauth = strstr(cookieheader, "wcauth=");
250 safestrncpy(authbuf, &cookieheader[7], authbuflen);
251 char *semicolon = strchr(authbuf, ';');
252 if (semicolon != NULL) {
255 if (strlen(authbuf) < 3) { // impossibly small
258 return; // Cookie auth was found -- stop here
262 // no authorization found in headers ... this is an anonymous session
267 * Log in to the Citadel server. Returns 0 on success or nonzero on error.
269 * 'auth' should be a base64-encoded "username:password" combination (like in http-auth)
271 * If 'resultbuf' is not NULL, it should be a buffer of at least 1024 characters,
272 * and will be filled with the result from a Citadel server command.
274 int login_to_citadel(struct ctdlsession *c, char *auth, char *resultbuf)
279 char supplied_username[AUTH_MAX];
280 char supplied_password[AUTH_MAX];
282 if (resultbuf != NULL) {
289 buflen = CtdlDecodeBase64(buf, auth, strlen(auth));
290 extract_token(supplied_username, buf, 0, ':', sizeof supplied_username);
291 extract_token(supplied_password, buf, 1, ':', sizeof supplied_password);
292 syslog(LOG_DEBUG, "Supplied credentials: username=%s, pwlen=%d", supplied_username, (int)strlen(supplied_password));
294 ctdl_printf(c, "USER %s", supplied_username);
295 ctdl_readline(c, buf, 1024);
297 syslog(LOG_DEBUG, "No such user: %s", buf);
298 return(1); // no such user; resultbuf will explain why
301 ctdl_printf(c, "PASS %s", supplied_password);
302 ctdl_readline(c, buf, 1024);
305 strcpy(c->auth, auth);
306 extract_token(c->whoami, &buf[4], 0, '|', sizeof c->whoami);
307 syslog(LOG_DEBUG, "Login succeeded: %s", buf);
311 syslog(LOG_DEBUG, "Login failed: %s", buf);
312 return(1); // login failed; resultbuf will explain why
317 * Hunt for, or create, a connection to our Citadel Server
319 struct ctdlsession *connect_to_citadel(struct http_transaction *h) {
320 struct ctdlsession *cptr = NULL;
321 struct ctdlsession *my_session = NULL;
322 int is_new_session = 0;
327 // Does the request carry a username and password?
328 extract_auth(h, auth, sizeof auth);
329 syslog(LOG_DEBUG, "Session auth: %s", auth); // remove this log when development is done
331 // Lock the connection pool while we claim our connection
332 pthread_mutex_lock(&cpool_mutex);
333 if (cpool != NULL) for (cptr = cpool; ((cptr != NULL) && (my_session == NULL)); cptr = cptr->next) {
334 if ( (cptr->is_bound == 0) && (!strcmp(cptr->auth, auth)) ) {
336 my_session->is_bound = 1;
339 if (my_session == NULL) {
340 syslog(LOG_DEBUG, "No qualifying sessions , starting a new one");
341 my_session = malloc(sizeof(struct ctdlsession));
342 if (my_session != NULL) {
343 memset(my_session, 0, sizeof(struct ctdlsession));
345 my_session->next = cpool;
347 my_session->is_bound = 1;
350 pthread_mutex_unlock(&cpool_mutex);
351 if (my_session == NULL) {
352 return(NULL); // oh well
355 if (my_session->sock < 3) {
358 else { // make sure our Citadel session is still good
360 test_conn = ctdl_write(my_session, HKEY("NOOP\n"));
362 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
363 close(my_session->sock);
364 my_session->sock = 0;
368 test_conn = ctdl_readline(my_session, buf, sizeof(buf));
370 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
371 close(my_session->sock);
372 my_session->sock = 0;
378 if (is_new_session) {
379 strcpy(my_session->room, "");
380 my_session->sock = tcp_connectsock(ctdlhost, ctdlport);
381 ctdl_readline(my_session, buf, sizeof(buf)); // skip past the server greeting banner
383 if (!IsEmptyStr(auth)) { // do we need to log in to Citadel?
384 r = login_to_citadel(my_session, auth, NULL); // FIXME figure out what happens if login failed
387 ctdl_printf(my_session, "NOOP");
388 ctdl_readline(my_session, buf, sizeof(buf));
389 my_session->last_access = time(NULL);
390 ++my_session->num_requests_handled;
397 * Release our Citadel Server connection back into the pool.
399 void disconnect_from_citadel(struct ctdlsession *ctdl) {
400 pthread_mutex_lock(&cpool_mutex);
402 pthread_mutex_unlock(&cpool_mutex);