2 // Functions that handle communication with a Citadel Server
4 // Copyright (c) 1987-2022 by the citadel.org team
6 // This program is open source software. It runs great on the
7 // Linux operating system (and probably elsewhere). You can use,
8 // copy, and run it under the terms of the GNU General Public
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
18 struct ctdlsession *cpool = NULL; // linked list of connections to the Citadel server
19 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.
24 int ctdl_read_binary(struct ctdlsession *ctdl, char *buf, int bytes_requested) {
28 while (bytes_read < bytes_requested) {
29 c = read(ctdl->sock, &buf[bytes_read], bytes_requested-bytes_read);
31 syslog(LOG_DEBUG, "Socket error or zero-length read");
40 // Read a newline-terminated line of text from the Citadel server.
41 // Returns the string length or -1 for error.
42 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[33m[ %s\033[0m", buf);
65 // syslog(LOG_DEBUG, "\033[33m[ %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) {
142 char *authheader = header_val(h, "Authorization");
144 if (!strncasecmp(authheader, "Basic ", 6)) {
145 safestrncpy(authbuf, &authheader[6], authbuflen);
146 return; // HTTP-AUTH was found -- stop here
150 char *cookieheader = header_val(h, "Cookie");
152 char *wcauth = strstr(cookieheader, "wcauth=");
154 safestrncpy(authbuf, &cookieheader[7], authbuflen);
155 char *semicolon = strchr(authbuf, ';');
156 if (semicolon != NULL) {
159 if (strlen(authbuf) < 3) { // impossibly small
162 return; // Cookie auth was found -- stop here
165 // no authorization found in headers ... this is an anonymous session
169 // Log in to the Citadel server. Returns 0 on success or nonzero on error.
171 // 'auth' should be a base64-encoded "username:password" combination (like in http-auth)
173 // If 'resultbuf' is not NULL, it should be a buffer of at least 1024 characters,
174 // and will be filled with the result from a Citadel server command.
175 int login_to_citadel(struct ctdlsession *c, char *auth, char *resultbuf) {
179 char supplied_username[AUTH_MAX];
180 char supplied_password[AUTH_MAX];
182 if (resultbuf != NULL) {
189 buflen = CtdlDecodeBase64(buf, auth, strlen(auth));
190 extract_token(supplied_username, buf, 0, ':', sizeof supplied_username);
191 extract_token(supplied_password, buf, 1, ':', sizeof supplied_password);
192 syslog(LOG_DEBUG, "Supplied credentials: username=%s, pwlen=%d", supplied_username, (int) strlen(supplied_password));
194 ctdl_printf(c, "USER %s", supplied_username);
195 ctdl_readline(c, buf, 1024);
197 syslog(LOG_DEBUG, "No such user: %s", buf);
198 return (1); // no such user; resultbuf will explain why
201 ctdl_printf(c, "PASS %s", supplied_password);
202 ctdl_readline(c, buf, 1024);
205 strcpy(c->auth, auth);
206 extract_token(c->whoami, &buf[4], 0, '|', sizeof c->whoami);
207 syslog(LOG_DEBUG, "Login succeeded: %s", buf);
211 syslog(LOG_DEBUG, "Login failed: %s", buf);
212 return (1); // login failed; resultbuf will explain why
216 // Hunt for, or create, a connection to our Citadel Server
217 struct ctdlsession *connect_to_citadel(struct http_transaction *h) {
218 struct ctdlsession *cptr = NULL;
219 struct ctdlsession *my_session = NULL;
220 int is_new_session = 0;
225 // Does the request carry a username and password?
226 extract_auth(h, auth, sizeof auth);
227 syslog(LOG_DEBUG, "Session auth: %s", auth); // remove this log when development is done
229 // Lock the connection pool while we claim our connection
230 pthread_mutex_lock(&cpool_mutex);
232 for (cptr = cpool; ((cptr != NULL) && (my_session == NULL)); cptr = cptr->next) {
233 if ((cptr->is_bound == 0) && (!strcmp(cptr->auth, auth))) {
235 my_session->is_bound = 1;
238 if (my_session == NULL) {
239 syslog(LOG_DEBUG, "No qualifying sessions , starting a new one");
240 my_session = malloc(sizeof(struct ctdlsession));
241 if (my_session != NULL) {
242 memset(my_session, 0, sizeof(struct ctdlsession));
244 my_session->next = cpool;
246 my_session->is_bound = 1;
249 pthread_mutex_unlock(&cpool_mutex);
250 if (my_session == NULL) {
251 return (NULL); // oh well
254 if (my_session->sock < 3) {
257 else { // make sure our Citadel session is still good
259 test_conn = ctdl_write(my_session, HKEY("NOOP\n"));
261 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
262 close(my_session->sock);
263 my_session->sock = 0;
267 test_conn = ctdl_readline(my_session, buf, sizeof(buf));
269 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
270 close(my_session->sock);
271 my_session->sock = 0;
277 if (is_new_session) {
278 strcpy(my_session->room, "");
279 static char *ctdl_sock_path = NULL;
280 if (!ctdl_sock_path) {
281 ctdl_sock_path = malloc(PATH_MAX);
282 snprintf(ctdl_sock_path, PATH_MAX, "%s/citadel.socket", ctdl_dir);
284 my_session->sock = uds_connectsock(ctdl_sock_path);
285 ctdl_readline(my_session, buf, sizeof(buf)); // skip past the server greeting banner
287 if (!IsEmptyStr(auth)) { // do we need to log in to Citadel?
288 r = login_to_citadel(my_session, auth, NULL); // FIXME figure out what happens if login failed
291 ctdl_printf(my_session, "NOOP");
292 ctdl_readline(my_session, buf, sizeof(buf));
293 my_session->last_access = time(NULL);
294 ++my_session->num_requests_handled;
300 // Release our Citadel Server connection back into the pool.
301 void disconnect_from_citadel(struct ctdlsession *ctdl) {
302 pthread_mutex_lock(&cpool_mutex);
304 pthread_mutex_unlock(&cpool_mutex);