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 specific number of bytes of binary data from the Citadel server.
23 * Returns the number of bytes read or -1 for error.
25 int ctdl_read_binary(struct ctdlsession *ctdl, char *buf, int bytes_requested)
30 while (bytes_read < bytes_requested) {
31 c = read(ctdl->sock, &buf[bytes_read], bytes_requested-bytes_read);
33 syslog(LOG_DEBUG, "Socket error or zero-length read");
43 * Read a newline-terminated line of text from the Citadel server.
44 * Returns the string length or -1 for error.
46 int ctdl_readline(struct ctdlsession *ctdl, char *buf, int maxbytes)
54 while (len < maxbytes) {
55 c = read(ctdl->sock, &buf[len], 1);
57 syslog(LOG_DEBUG, "Socket error or zero-length read");
60 if (buf[len] == '\n') {
61 if ((len > 0) && (buf[len - 1] == '\r')) {
65 // syslog(LOG_DEBUG, "\033[33m[ %s\033[0m", buf);
70 // syslog(LOG_DEBUG, "\033[33m[ %s\033[0m", buf);
76 * Read lines of text from the Citadel server until a 000 terminator is received.
77 * Implemented in terms of ctdl_readline() and is therefore transparent...
78 * Returns a newly allocated StrBuf or NULL for error.
80 StrBuf *ctdl_readtextmsg(struct ctdlsession * ctdl)
83 StrBuf *sj = NewStrBuf();
88 while ((ctdl_readline(ctdl, buf, sizeof(buf)) >= 0) && (strcmp(buf, "000"))) {
89 StrBufAppendPrintf(sj, "%s\n", buf);
97 * Write to the Citadel server. For now we're just wrapping write() in case we
98 * need to add anything else later.
100 ssize_t ctdl_write(struct ctdlsession * ctdl, const void *buf, size_t count)
102 return write(ctdl->sock, buf, count);
107 * printf() type function to send data to the Citadel Server.
109 void ctdl_printf(struct ctdlsession *ctdl, const char *format, ...)
112 StrBuf *Buf = NewStrBuf();
114 va_start(arg_ptr, format);
115 StrBufVAppendPrintf(Buf, format, arg_ptr);
118 syslog(LOG_DEBUG, "\033[32m] %s\033[0m", ChrPtr(Buf));
119 ctdl_write(ctdl, (char *) ChrPtr(Buf), StrLength(Buf));
120 ctdl_write(ctdl, "\n", 1);
126 * Client side - connect to a unix domain socket
128 int uds_connectsock(char *sockpath)
130 struct sockaddr_un addr;
133 memset(&addr, 0, sizeof(addr));
134 addr.sun_family = AF_UNIX;
135 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
137 s = socket(AF_UNIX, SOCK_STREAM, 0);
139 syslog(LOG_WARNING, "Can't create socket [%s]: %s", sockpath, strerror(errno));
143 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
144 syslog(LOG_WARNING, "Can't connect [%s]: %s", sockpath, strerror(errno));
153 * TCP client - connect to a host/port
155 int tcp_connectsock(char *host, char *service)
157 struct in6_addr serveraddr;
158 struct addrinfo hints;
159 struct addrinfo *res = NULL;
160 struct addrinfo *ai = NULL;
164 if ((host == NULL) || IsEmptyStr(host))
166 if ((service == NULL) || IsEmptyStr(service))
169 syslog(LOG_DEBUG, "tcp_connectsock(%s,%s)", host, service);
171 memset(&hints, 0x00, sizeof(hints));
172 hints.ai_flags = AI_NUMERICSERV;
173 hints.ai_family = AF_UNSPEC;
174 hints.ai_socktype = SOCK_STREAM;
177 * Handle numeric IPv4 and IPv6 addresses
179 rc = inet_pton(AF_INET, host, &serveraddr);
180 if (rc == 1) { /* dotted quad */
181 hints.ai_family = AF_INET;
182 hints.ai_flags |= AI_NUMERICHOST;
184 rc = inet_pton(AF_INET6, host, &serveraddr);
185 if (rc == 1) { /* IPv6 address */
186 hints.ai_family = AF_INET6;
187 hints.ai_flags |= AI_NUMERICHOST;
191 /* Begin the connection process */
193 rc = getaddrinfo(host, service, &hints, &res);
195 syslog(LOG_DEBUG, "%s: %s", host, gai_strerror(rc));
201 * Try all available addresses until we connect to one or until we run out.
203 for (ai = res; ai != NULL; ai = ai->ai_next) {
205 if (ai->ai_family == AF_INET)
206 syslog(LOG_DEBUG, "Trying IPv4");
207 else if (ai->ai_family == AF_INET6)
208 syslog(LOG_DEBUG, "Trying IPv6");
210 syslog(LOG_WARNING, "This is going to fail.");
212 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
214 syslog(LOG_WARNING, "socket() failed: %s", strerror(errno));
218 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
223 fdflags = fcntl(rc, F_GETFL);
225 syslog(LOG_ERR, "unable to get socket %d flags! %s", rc, strerror(errno));
229 fdflags = fdflags | O_NONBLOCK;
230 if (fcntl(rc, F_SETFL, fdflags) < 0) {
231 syslog(LOG_ERR, "unable to set socket %d nonblocking flags! %s", rc, strerror(errno));
238 syslog(LOG_WARNING, "connect() failed: %s", strerror(errno));
248 * Extract from the headers, the username and password the client is attempting to use.
249 * This could be HTTP AUTH or it could be in the cookies.
251 void extract_auth(struct http_transaction *h, char *authbuf, int authbuflen)
257 char *authheader = header_val(h, "Authorization");
259 if (!strncasecmp(authheader, "Basic ", 6)) {
260 safestrncpy(authbuf, &authheader[6], authbuflen);
261 return; // HTTP-AUTH was found -- stop here
265 char *cookieheader = header_val(h, "Cookie");
267 char *wcauth = strstr(cookieheader, "wcauth=");
269 safestrncpy(authbuf, &cookieheader[7], authbuflen);
270 char *semicolon = strchr(authbuf, ';');
271 if (semicolon != NULL) {
274 if (strlen(authbuf) < 3) { // impossibly small
277 return; // Cookie auth was found -- stop here
280 // no authorization found in headers ... this is an anonymous session
285 * Log in to the Citadel server. Returns 0 on success or nonzero on error.
287 * 'auth' should be a base64-encoded "username:password" combination (like in http-auth)
289 * If 'resultbuf' is not NULL, it should be a buffer of at least 1024 characters,
290 * and will be filled with the result from a Citadel server command.
292 int login_to_citadel(struct ctdlsession *c, char *auth, char *resultbuf)
297 char supplied_username[AUTH_MAX];
298 char supplied_password[AUTH_MAX];
300 if (resultbuf != NULL) {
306 buflen = CtdlDecodeBase64(buf, auth, strlen(auth));
307 extract_token(supplied_username, buf, 0, ':', sizeof supplied_username);
308 extract_token(supplied_password, buf, 1, ':', sizeof supplied_password);
309 syslog(LOG_DEBUG, "Supplied credentials: username=%s, pwlen=%d", supplied_username, (int) strlen(supplied_password));
311 ctdl_printf(c, "USER %s", supplied_username);
312 ctdl_readline(c, buf, 1024);
314 syslog(LOG_DEBUG, "No such user: %s", buf);
315 return (1); // no such user; resultbuf will explain why
318 ctdl_printf(c, "PASS %s", supplied_password);
319 ctdl_readline(c, buf, 1024);
322 strcpy(c->auth, auth);
323 extract_token(c->whoami, &buf[4], 0, '|', sizeof c->whoami);
324 syslog(LOG_DEBUG, "Login succeeded: %s", buf);
328 syslog(LOG_DEBUG, "Login failed: %s", buf);
329 return (1); // login failed; resultbuf will explain why
334 * Hunt for, or create, a connection to our Citadel Server
336 struct ctdlsession *connect_to_citadel(struct http_transaction *h)
338 struct ctdlsession *cptr = NULL;
339 struct ctdlsession *my_session = NULL;
340 int is_new_session = 0;
345 // Does the request carry a username and password?
346 extract_auth(h, auth, sizeof auth);
347 syslog(LOG_DEBUG, "Session auth: %s", auth); // remove this log when development is done
349 // Lock the connection pool while we claim our connection
350 pthread_mutex_lock(&cpool_mutex);
352 for (cptr = cpool; ((cptr != NULL) && (my_session == NULL)); cptr = cptr->next) {
353 if ((cptr->is_bound == 0) && (!strcmp(cptr->auth, auth))) {
355 my_session->is_bound = 1;
358 if (my_session == NULL) {
359 syslog(LOG_DEBUG, "No qualifying sessions , starting a new one");
360 my_session = malloc(sizeof(struct ctdlsession));
361 if (my_session != NULL) {
362 memset(my_session, 0, sizeof(struct ctdlsession));
364 my_session->next = cpool;
366 my_session->is_bound = 1;
369 pthread_mutex_unlock(&cpool_mutex);
370 if (my_session == NULL) {
371 return (NULL); // oh well
374 if (my_session->sock < 3) {
376 } else { // make sure our Citadel session is still good
378 test_conn = ctdl_write(my_session, HKEY("NOOP\n"));
380 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
381 close(my_session->sock);
382 my_session->sock = 0;
385 test_conn = ctdl_readline(my_session, buf, sizeof(buf));
387 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
388 close(my_session->sock);
389 my_session->sock = 0;
395 if (is_new_session) {
396 strcpy(my_session->room, "");
397 my_session->sock = tcp_connectsock(ctdlhost, ctdlport);
398 ctdl_readline(my_session, buf, sizeof(buf)); // skip past the server greeting banner
400 if (!IsEmptyStr(auth)) { // do we need to log in to Citadel?
401 r = login_to_citadel(my_session, auth, NULL); // FIXME figure out what happens if login failed
404 ctdl_printf(my_session, "NOOP");
405 ctdl_readline(my_session, buf, sizeof(buf));
406 my_session->last_access = time(NULL);
407 ++my_session->num_requests_handled;
414 * Release our Citadel Server connection back into the pool.
416 void disconnect_from_citadel(struct ctdlsession *ctdl)
418 pthread_mutex_lock(&cpool_mutex);
420 pthread_mutex_unlock(&cpool_mutex);