1 // Functions that handle communication with a Citadel Server
3 // Copyright (c) 1987-2022 by the citadel.org team
5 // This program is open source software. It runs great on the
6 // Linux operating system (and probably elsewhere). You can use,
7 // copy, and run it under the terms of the GNU General Public
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // 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
21 // Read a specific number of bytes of binary data from the Citadel server.
22 // Returns the number of bytes read or -1 for error.
23 int ctdl_read_binary(struct ctdlsession *ctdl, char *buf, int bytes_requested) {
27 while (bytes_read < bytes_requested) {
28 c = read(ctdl->sock, &buf[bytes_read], bytes_requested-bytes_read);
30 syslog(LOG_DEBUG, "Socket error or zero-length read");
39 // Read a newline-terminated line of text from the Citadel server.
40 // Returns the string length or -1 for error.
41 int ctdl_readline(struct ctdlsession *ctdl, char *buf, int maxbytes) {
49 while (len < maxbytes) {
50 c = read(ctdl->sock, &buf[len], 1);
52 syslog(LOG_DEBUG, "Socket error or zero-length read");
55 if (buf[len] == '\n') {
56 if ((len > 0) && (buf[len - 1] == '\r')) {
60 syslog(LOG_DEBUG, "\033[32m[ %s\033[0m", buf);
65 syslog(LOG_DEBUG, "\033[32m[ %s\033[0m", buf);
70 // Read lines of text from the Citadel server until a 000 terminator is received.
71 // Implemented in terms of ctdl_readline() and is therefore transparent...
72 // Returns a newly allocated StrBuf or NULL for error.
73 StrBuf *ctdl_readtextmsg(struct ctdlsession *ctdl) {
75 StrBuf *sj = NewStrBuf();
80 while ((ctdl_readline(ctdl, buf, sizeof(buf)) >= 0) && (strcmp(buf, "000"))) {
81 StrBufAppendPrintf(sj, "%s\n", buf);
88 // Write to the Citadel server. For now we're just wrapping write() in case we
89 // need to add anything else later.
90 ssize_t ctdl_write(struct ctdlsession *ctdl, const void *buf, size_t count) {
91 return write(ctdl->sock, buf, count);
95 // printf() type function to send data to the Citadel Server.
96 void ctdl_printf(struct ctdlsession *ctdl, const char *format, ...) {
98 StrBuf *Buf = NewStrBuf();
100 va_start(arg_ptr, format);
101 StrBufVAppendPrintf(Buf, format, arg_ptr);
104 syslog(LOG_DEBUG, "\033[32m] %s\033[0m", ChrPtr(Buf));
105 ctdl_write(ctdl, (char *) ChrPtr(Buf), StrLength(Buf));
106 ctdl_write(ctdl, "\n", 1);
111 // Client side - connect to a unix domain socket
112 int uds_connectsock(char *sockpath) {
113 struct sockaddr_un addr;
116 memset(&addr, 0, sizeof(addr));
117 addr.sun_family = AF_UNIX;
118 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
120 s = socket(AF_UNIX, SOCK_STREAM, 0);
122 syslog(LOG_WARNING, "Can't create socket [%s]: %s", sockpath, strerror(errno));
126 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
127 syslog(LOG_WARNING, "Can't connect [%s]: %s", sockpath, strerror(errno));
135 // Extract from the headers, the username and password the client is attempting to use.
136 // This could be HTTP AUTH or it could be in the cookies.
137 void extract_auth(struct http_transaction *h, char *authbuf, int authbuflen) {
138 if (authbuf == NULL) {
142 memset(authbuf, 0, authbuflen);
144 char *authheader = header_val(h, "Authorization");
146 if (!strncasecmp(authheader, "Basic ", 6)) {
147 safestrncpy(authbuf, &authheader[6], authbuflen);
148 return; // HTTP-AUTH was found -- stop here
152 char *cookieheader = header_val(h, "Cookie");
154 char *wcauth = strstr(cookieheader, "wcauth=");
156 safestrncpy(authbuf, &cookieheader[7], authbuflen);
157 char *semicolon = strchr(authbuf, ';');
158 if (semicolon != NULL) {
161 if (strlen(authbuf) < 3) { // impossibly small
164 return; // Cookie auth was found -- stop here
167 // no authorization found in headers ... this is an anonymous session
171 // Log in to the Citadel server. Returns 0 on success or nonzero on error.
173 // 'auth' should be a base64-encoded "username:password" combination (like in http-auth)
175 // If 'resultbuf' is not NULL, it should be a buffer of at least 1024 characters,
176 // and will be filled with the result from a Citadel server command.
177 int login_to_citadel(struct ctdlsession *c, char *auth, char *resultbuf) {
181 char supplied_username[AUTH_MAX];
182 char supplied_password[AUTH_MAX];
184 if (resultbuf != NULL) {
191 buflen = CtdlDecodeBase64(buf, auth, strlen(auth));
192 extract_token(supplied_username, buf, 0, ':', sizeof supplied_username);
193 extract_token(supplied_password, buf, 1, ':', sizeof supplied_password);
194 syslog(LOG_DEBUG, "Supplied credentials: username=%s, password=(%d bytes)", supplied_username, (int) strlen(supplied_password));
196 ctdl_printf(c, "USER %s", supplied_username);
197 ctdl_readline(c, buf, 1024);
199 syslog(LOG_DEBUG, "No such user: %s", buf);
200 return(1); // no such user; resultbuf will explain why
203 ctdl_printf(c, "PASS %s", supplied_password);
204 ctdl_readline(c, buf, 1024);
207 strcpy(c->auth, auth);
208 extract_token(c->whoami, &buf[4], 0, '|', sizeof c->whoami);
209 syslog(LOG_DEBUG, "Login succeeded: %s", buf);
213 syslog(LOG_DEBUG, "Login failed: %s", buf);
214 return(1); // login failed; resultbuf will explain why
218 // This is a variant of the "server connection pool" design pattern. We go through our list
219 // of connections to Citadel Server, looking for a connection that is at once:
220 // 1. Not currently serving a WebCit transaction (is_bound)
221 // 2a. Is logged in to Citadel as the correct user, if the HTTP session is logged in; or
222 // 2b. Is NOT logged in to Citadel, if the HTTP session is not logged in.
223 // If we find a qualifying connection, we bind to it for the duration of this WebCit HTTP transaction.
224 // Otherwise, we create a new connection to Citadel Server and add it to the pool.
225 struct ctdlsession *connect_to_citadel(struct http_transaction *h) {
226 struct ctdlsession *cptr = NULL;
227 struct ctdlsession *my_session = NULL;
228 int is_new_session = 0;
233 // Does the request carry a username and password?
234 extract_auth(h, auth, sizeof auth);
236 // Lock the connection pool while we claim our connection
237 pthread_mutex_lock(&cpool_mutex);
239 for (cptr = cpool; ((cptr != NULL) && (my_session == NULL)); cptr = cptr->next) {
240 if ((cptr->is_bound == 0) && (!strcmp(cptr->auth, auth))) {
242 my_session->is_bound = 1;
246 if (my_session == NULL) {
247 syslog(LOG_DEBUG, "No qualifying sessions , starting a new one");
248 my_session = malloc(sizeof(struct ctdlsession));
249 if (my_session != NULL) {
250 memset(my_session, 0, sizeof(struct ctdlsession));
252 my_session->next = cpool;
254 my_session->is_bound = 1;
257 pthread_mutex_unlock(&cpool_mutex);
258 if (my_session == NULL) {
259 return(NULL); // Could not create a new session (yikes!)
262 if (my_session->sock < 3) {
265 else { // make sure our Citadel session is still working
267 test_conn = ctdl_write(my_session, HKEY("NOOP\n"));
269 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
270 close(my_session->sock);
271 my_session->sock = 0;
275 test_conn = ctdl_readline(my_session, buf, sizeof(buf));
277 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
278 close(my_session->sock);
279 my_session->sock = 0;
285 if (is_new_session) {
286 strcpy(my_session->room, "");
287 static char *ctdl_sock_path = NULL;
288 if (!ctdl_sock_path) {
289 ctdl_sock_path = malloc(PATH_MAX);
290 snprintf(ctdl_sock_path, PATH_MAX, "%s/citadel.socket", ctdl_dir);
292 my_session->sock = uds_connectsock(ctdl_sock_path);
293 ctdl_readline(my_session, buf, sizeof(buf)); // skip past the server greeting banner
295 if (!IsEmptyStr(auth)) { // do we need to log in to Citadel?
296 r = login_to_citadel(my_session, auth, NULL); // FIXME figure out what happens if login failed
300 ctdl_printf(my_session, "NOOP");
301 ctdl_readline(my_session, buf, sizeof(buf));
302 my_session->last_access = time(NULL);
303 ++my_session->num_requests_handled;
308 // Release our Citadel Server connection back into the pool.
309 void disconnect_from_citadel(struct ctdlsession *ctdl) {
310 pthread_mutex_lock(&cpool_mutex);
312 pthread_mutex_unlock(&cpool_mutex);