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)), 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 extract_token(c->whoami, &buf[4], 0, '|', sizeof c->whoami);
208 syslog(LOG_DEBUG, "Logged in as %s", c->whoami);
210 // Re-encode the auth string so it contains the properly formatted username
211 char new_auth_string[1024];
212 snprintf(new_auth_string, sizeof(new_auth_string), "%s:%s", c->whoami, supplied_password);
213 CtdlEncodeBase64(c->auth, new_auth_string, strlen(new_auth_string), 0);
218 syslog(LOG_DEBUG, "Login failed: %s", &buf[4]);
219 return(1); // login failed; resultbuf will explain why
223 // This is a variant of the "server connection pool" design pattern. We go through our list
224 // of connections to Citadel Server, looking for a connection that is at once:
225 // 1. Not currently serving a WebCit transaction (is_bound)
226 // 2a. Is logged in to Citadel as the correct user, if the HTTP session is logged in; or
227 // 2b. Is NOT logged in to Citadel, if the HTTP session is not logged in.
228 // If we find a qualifying connection, we bind to it for the duration of this WebCit HTTP transaction.
229 // Otherwise, we create a new connection to Citadel Server and add it to the pool.
230 struct ctdlsession *connect_to_citadel(struct http_transaction *h) {
231 struct ctdlsession *cptr = NULL;
232 struct ctdlsession *my_session = NULL;
233 int is_new_session = 0;
238 // Does the request carry a username and password?
239 extract_auth(h, auth, sizeof auth);
241 // Lock the connection pool while we claim our connection
242 pthread_mutex_lock(&cpool_mutex);
244 for (cptr = cpool; ((cptr != NULL) && (my_session == NULL)); cptr = cptr->next) {
245 if ((cptr->is_bound == 0) && (!strcmp(cptr->auth, auth))) {
247 my_session->is_bound = 1;
251 if (my_session == NULL) {
252 syslog(LOG_DEBUG, "No qualifying sessions , starting a new one");
253 my_session = malloc(sizeof(struct ctdlsession));
254 if (my_session != NULL) {
255 memset(my_session, 0, sizeof(struct ctdlsession));
257 my_session->next = cpool;
259 my_session->is_bound = 1;
262 pthread_mutex_unlock(&cpool_mutex);
263 if (my_session == NULL) {
264 return(NULL); // Could not create a new session (yikes!)
267 if (my_session->sock < 3) {
270 else { // make sure our Citadel session is still working
272 test_conn = ctdl_write(my_session, HKEY("NOOP\n"));
274 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
275 close(my_session->sock);
276 my_session->sock = 0;
280 test_conn = ctdl_readline(my_session, buf, sizeof(buf));
282 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
283 close(my_session->sock);
284 my_session->sock = 0;
290 if (is_new_session) {
291 strcpy(my_session->room, "");
292 static char *ctdl_sock_path = NULL;
293 if (!ctdl_sock_path) {
294 ctdl_sock_path = malloc(PATH_MAX);
295 snprintf(ctdl_sock_path, PATH_MAX, "%s/citadel.socket", ctdl_dir);
297 my_session->sock = uds_connectsock(ctdl_sock_path);
298 ctdl_readline(my_session, buf, sizeof(buf)); // skip past the server greeting banner
300 if (!IsEmptyStr(auth)) { // do we need to log in to Citadel?
301 r = login_to_citadel(my_session, auth, NULL); // FIXME figure out what happens if login failed
305 ctdl_printf(my_session, "NOOP");
306 ctdl_readline(my_session, buf, sizeof(buf));
307 my_session->last_access = time(NULL);
308 ++my_session->num_requests_handled;
313 // Release our Citadel Server connection back into the pool.
314 void disconnect_from_citadel(struct ctdlsession *ctdl) {
315 pthread_mutex_lock(&cpool_mutex);
317 pthread_mutex_unlock(&cpool_mutex);