2 * Functions that handle communication with a Citadel Server
4 * Copyright (c) 1987-2018 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)
34 while (len < maxbytes) {
35 c = read(ctdl->sock, &buf[len], 1);
37 syslog(LOG_DEBUG, "Socket error or zero-length read");
40 if (buf[len] == '\n') {
41 if ((len > 0) && (buf[len - 1] == '\r')) {
45 // syslog(LOG_DEBUG, "\033[33m[ %s\033[0m", buf);
50 // syslog(LOG_DEBUG, "\033[33m[ %s\033[0m", buf);
56 * Read lines of text from the Citadel server until a 000 terminator is received.
57 * Implemented in terms of ctdl_readline() and is therefore transparent...
58 * Returns a newly allocated StrBuf or NULL for error.
60 StrBuf *ctdl_readtextmsg(struct ctdlsession * ctdl)
63 StrBuf *sj = NewStrBuf();
68 while ((ctdl_readline(ctdl, buf, sizeof(buf)) >= 0) && (strcmp(buf, "000"))) {
69 StrBufAppendPrintf(sj, "%s\n", buf);
77 * Write to the Citadel server. For now we're just wrapping write() in case we
78 * need to add anything else later.
80 ssize_t ctdl_write(struct ctdlsession * ctdl, const void *buf, size_t count)
82 return write(ctdl->sock, buf, count);
87 * printf() type function to send data to the Citadel Server.
89 void ctdl_printf(struct ctdlsession *ctdl, const char *format, ...)
92 StrBuf *Buf = NewStrBuf();
94 va_start(arg_ptr, format);
95 StrBufVAppendPrintf(Buf, format, arg_ptr);
98 syslog(LOG_DEBUG, "\033[32m] %s\033[0m", ChrPtr(Buf));
99 ctdl_write(ctdl, (char *) ChrPtr(Buf), StrLength(Buf));
100 ctdl_write(ctdl, "\n", 1);
106 * Client side - connect to a unix domain socket
108 int uds_connectsock(char *sockpath)
110 struct sockaddr_un addr;
113 memset(&addr, 0, sizeof(addr));
114 addr.sun_family = AF_UNIX;
115 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
117 s = socket(AF_UNIX, SOCK_STREAM, 0);
119 syslog(LOG_WARNING, "Can't create socket [%s]: %s", sockpath, strerror(errno));
123 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
124 syslog(LOG_WARNING, "Can't connect [%s]: %s", sockpath, strerror(errno));
133 * TCP client - connect to a host/port
135 int tcp_connectsock(char *host, char *service)
137 struct in6_addr serveraddr;
138 struct addrinfo hints;
139 struct addrinfo *res = NULL;
140 struct addrinfo *ai = NULL;
144 if ((host == NULL) || IsEmptyStr(host))
146 if ((service == NULL) || IsEmptyStr(service))
149 syslog(LOG_DEBUG, "tcp_connectsock(%s,%s)", host, service);
151 memset(&hints, 0x00, sizeof(hints));
152 hints.ai_flags = AI_NUMERICSERV;
153 hints.ai_family = AF_UNSPEC;
154 hints.ai_socktype = SOCK_STREAM;
157 * Handle numeric IPv4 and IPv6 addresses
159 rc = inet_pton(AF_INET, host, &serveraddr);
160 if (rc == 1) { /* dotted quad */
161 hints.ai_family = AF_INET;
162 hints.ai_flags |= AI_NUMERICHOST;
164 rc = inet_pton(AF_INET6, host, &serveraddr);
165 if (rc == 1) { /* IPv6 address */
166 hints.ai_family = AF_INET6;
167 hints.ai_flags |= AI_NUMERICHOST;
171 /* Begin the connection process */
173 rc = getaddrinfo(host, service, &hints, &res);
175 syslog(LOG_DEBUG, "%s: %s", host, gai_strerror(rc));
181 * Try all available addresses until we connect to one or until we run out.
183 for (ai = res; ai != NULL; ai = ai->ai_next) {
185 if (ai->ai_family == AF_INET)
186 syslog(LOG_DEBUG, "Trying IPv4");
187 else if (ai->ai_family == AF_INET6)
188 syslog(LOG_DEBUG, "Trying IPv6");
190 syslog(LOG_WARNING, "This is going to fail.");
192 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
194 syslog(LOG_WARNING, "socket() failed: %s", strerror(errno));
198 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
203 fdflags = fcntl(rc, F_GETFL);
205 syslog(LOG_ERR, "unable to get socket %d flags! %s", rc, strerror(errno));
209 fdflags = fdflags | O_NONBLOCK;
210 if (fcntl(rc, F_SETFL, fdflags) < 0) {
211 syslog(LOG_ERR, "unable to set socket %d nonblocking flags! %s", rc, strerror(errno));
218 syslog(LOG_WARNING, "connect() failed: %s", strerror(errno));
228 * Extract from the headers, the username and password the client is attempting to use.
229 * This could be HTTP AUTH or it could be in the cookies.
231 void extract_auth(struct http_transaction *h, char *authbuf, int authbuflen)
237 char *authheader = header_val(h, "Authorization");
239 if (!strncasecmp(authheader, "Basic ", 6)) {
240 safestrncpy(authbuf, &authheader[6], authbuflen);
241 return; // HTTP-AUTH was found -- stop here
245 char *cookieheader = header_val(h, "Cookie");
247 char *wcauth = strstr(cookieheader, "wcauth=");
249 safestrncpy(authbuf, &cookieheader[7], authbuflen);
250 char *semicolon = strchr(authbuf, ';');
251 if (semicolon != NULL) {
254 if (strlen(authbuf) < 3) { // impossibly small
257 return; // Cookie auth was found -- stop here
260 // no authorization found in headers ... this is an anonymous session
265 * Log in to the Citadel server. Returns 0 on success or nonzero on error.
267 * 'auth' should be a base64-encoded "username:password" combination (like in http-auth)
269 * If 'resultbuf' is not NULL, it should be a buffer of at least 1024 characters,
270 * and will be filled with the result from a Citadel server command.
272 int login_to_citadel(struct ctdlsession *c, char *auth, char *resultbuf)
277 char supplied_username[AUTH_MAX];
278 char supplied_password[AUTH_MAX];
280 if (resultbuf != NULL) {
286 buflen = CtdlDecodeBase64(buf, auth, strlen(auth));
287 extract_token(supplied_username, buf, 0, ':', sizeof supplied_username);
288 extract_token(supplied_password, buf, 1, ':', sizeof supplied_password);
289 syslog(LOG_DEBUG, "Supplied credentials: username=%s, pwlen=%d", supplied_username, (int) strlen(supplied_password));
291 ctdl_printf(c, "USER %s", supplied_username);
292 ctdl_readline(c, buf, 1024);
294 syslog(LOG_DEBUG, "No such user: %s", buf);
295 return (1); // no such user; resultbuf will explain why
298 ctdl_printf(c, "PASS %s", supplied_password);
299 ctdl_readline(c, buf, 1024);
302 strcpy(c->auth, auth);
303 extract_token(c->whoami, &buf[4], 0, '|', sizeof c->whoami);
304 syslog(LOG_DEBUG, "Login succeeded: %s", buf);
308 syslog(LOG_DEBUG, "Login failed: %s", buf);
309 return (1); // login failed; resultbuf will explain why
314 * Hunt for, or create, a connection to our Citadel Server
316 struct ctdlsession *connect_to_citadel(struct http_transaction *h)
318 struct ctdlsession *cptr = NULL;
319 struct ctdlsession *my_session = NULL;
320 int is_new_session = 0;
325 // Does the request carry a username and password?
326 extract_auth(h, auth, sizeof auth);
327 syslog(LOG_DEBUG, "Session auth: %s", auth); // remove this log when development is done
329 // Lock the connection pool while we claim our connection
330 pthread_mutex_lock(&cpool_mutex);
332 for (cptr = cpool; ((cptr != NULL) && (my_session == NULL)); cptr = cptr->next) {
333 if ((cptr->is_bound == 0) && (!strcmp(cptr->auth, auth))) {
335 my_session->is_bound = 1;
338 if (my_session == NULL) {
339 syslog(LOG_DEBUG, "No qualifying sessions , starting a new one");
340 my_session = malloc(sizeof(struct ctdlsession));
341 if (my_session != NULL) {
342 memset(my_session, 0, sizeof(struct ctdlsession));
344 my_session->next = cpool;
346 my_session->is_bound = 1;
349 pthread_mutex_unlock(&cpool_mutex);
350 if (my_session == NULL) {
351 return (NULL); // oh well
354 if (my_session->sock < 3) {
356 } else { // make sure our Citadel session is still good
358 test_conn = ctdl_write(my_session, HKEY("NOOP\n"));
360 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
361 close(my_session->sock);
362 my_session->sock = 0;
365 test_conn = ctdl_readline(my_session, buf, sizeof(buf));
367 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
368 close(my_session->sock);
369 my_session->sock = 0;
375 if (is_new_session) {
376 strcpy(my_session->room, "");
377 my_session->sock = tcp_connectsock(ctdlhost, ctdlport);
378 ctdl_readline(my_session, buf, sizeof(buf)); // skip past the server greeting banner
380 if (!IsEmptyStr(auth)) { // do we need to log in to Citadel?
381 r = login_to_citadel(my_session, auth, NULL); // FIXME figure out what happens if login failed
384 ctdl_printf(my_session, "NOOP");
385 ctdl_readline(my_session, buf, sizeof(buf));
386 my_session->last_access = time(NULL);
387 ++my_session->num_requests_handled;
394 * Release our Citadel Server connection back into the pool.
396 void disconnect_from_citadel(struct ctdlsession *ctdl)
398 pthread_mutex_lock(&cpool_mutex);
400 pthread_mutex_unlock(&cpool_mutex);