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, pwlen=%d", 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 // Hunt for, or create, a connection to our Citadel Server
219 struct ctdlsession *connect_to_citadel(struct http_transaction *h) {
220 struct ctdlsession *cptr = NULL;
221 struct ctdlsession *my_session = NULL;
222 int is_new_session = 0;
227 // Does the request carry a username and password?
228 extract_auth(h, auth, sizeof auth);
229 syslog(LOG_DEBUG, "Session auth: %s", auth); // remove this log when development is done
231 // Lock the connection pool while we claim our connection
232 pthread_mutex_lock(&cpool_mutex);
234 for (cptr = cpool; ((cptr != NULL) && (my_session == NULL)); cptr = cptr->next) {
235 if ((cptr->is_bound == 0) && (!strcmp(cptr->auth, auth))) {
237 my_session->is_bound = 1;
241 if (my_session == NULL) {
242 syslog(LOG_DEBUG, "No qualifying sessions , starting a new one");
243 my_session = malloc(sizeof(struct ctdlsession));
244 if (my_session != NULL) {
245 memset(my_session, 0, sizeof(struct ctdlsession));
247 my_session->next = cpool;
249 my_session->is_bound = 1;
252 pthread_mutex_unlock(&cpool_mutex);
253 if (my_session == NULL) {
254 return (NULL); // oh well
257 if (my_session->sock < 3) {
260 else { // make sure our Citadel session is still good
262 test_conn = ctdl_write(my_session, HKEY("NOOP\n"));
264 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
265 close(my_session->sock);
266 my_session->sock = 0;
270 test_conn = ctdl_readline(my_session, buf, sizeof(buf));
272 syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
273 close(my_session->sock);
274 my_session->sock = 0;
280 if (is_new_session) {
281 strcpy(my_session->room, "");
282 static char *ctdl_sock_path = NULL;
283 if (!ctdl_sock_path) {
284 ctdl_sock_path = malloc(PATH_MAX);
285 snprintf(ctdl_sock_path, PATH_MAX, "%s/citadel.socket", ctdl_dir);
287 my_session->sock = uds_connectsock(ctdl_sock_path);
288 ctdl_readline(my_session, buf, sizeof(buf)); // skip past the server greeting banner
290 if (!IsEmptyStr(auth)) { // do we need to log in to Citadel?
291 r = login_to_citadel(my_session, auth, NULL); // FIXME figure out what happens if login failed
294 ctdl_printf(my_session, "NOOP");
295 ctdl_readline(my_session, buf, sizeof(buf));
296 my_session->last_access = time(NULL);
297 ++my_session->num_requests_handled;
303 // Release our Citadel Server connection back into the pool.
304 void disconnect_from_citadel(struct ctdlsession *ctdl) {
305 pthread_mutex_lock(&cpool_mutex);
307 pthread_mutex_unlock(&cpool_mutex);