snprintf(buf, sizeof buf, "%s:%s", username, password);
CtdlEncodeBase64(auth, buf, strlen(buf), 0);
- syslog(LOG_DEBUG, "try_login(username='%s',password=(%d bytes))", username, (int)strlen(password));
+ syslog(LOG_DEBUG, "try_login(username='%s',password=(%d bytes))", username, (int) strlen(password));
- ctdl_printf(c, "LOUT"); // log out, in case we were logged in
- ctdl_readline(c, buf, sizeof(buf)); // ignore the result
- memset(c->auth, 0, AUTH_MAX); // if this connection had auth, it doesn't now.
- memset(c->whoami, 0, 64); // if this connection had auth, it doesn't now.
+ ctdl_printf(c, "LOUT"); // log out, in case we were logged in
+ ctdl_readline(c, buf, sizeof(buf)); // ignore the result
+ memset(c->auth, 0, AUTH_MAX); // if this connection had auth, it doesn't now.
+ memset(c->whoami, 0, 64); // if this connection had auth, it doesn't now.
- login_success = login_to_citadel(c, auth, buf); // Now try logging in to Citadel
+ login_success = login_to_citadel(c, auth, buf); // Now try logging in to Citadel
- h->response_code = 200; // 'buf' will contain the relevant response
+ h->response_code = 200; // 'buf' will contain the relevant response
h->response_string = strdup("OK");
add_response_header(h, strdup("Content-type"), strdup("text/plain"));
h->response_body = strdup(buf);
char password[256];
int login_success = 0;
- ctdl_printf(c, "LOUT"); // log out
- ctdl_readline(c, buf, sizeof(buf)); // ignore the result
+ ctdl_printf(c, "LOUT"); // log out
+ ctdl_readline(c, buf, sizeof(buf)); // ignore the result
strcpy(c->auth, "x");
- //memset(c->auth, 0, AUTH_MAX); // if this connection had auth, it doesn't now.
- memset(c->whoami, 0, 64); // if this connection had auth, it doesn't now.
+ //memset(c->auth, 0, AUTH_MAX); // if this connection had auth, it doesn't now.
+ memset(c->whoami, 0, 64); // if this connection had auth, it doesn't now.
- http_redirect(h, "/ctdl/s/index.html"); // go back where we started :)
+ http_redirect(h, "/ctdl/s/index.html"); // go back where we started :)
}
*/
void ctdl_a(struct http_transaction *h, struct ctdlsession *c)
{
- if (!strcasecmp(h->uri, "/ctdl/a/login")) { // log in
+ if (!strcasecmp(h->uri, "/ctdl/a/login")) { // log in
try_login(h, c);
- return;
+ return;
}
- if (!strcasecmp(h->uri, "/ctdl/a/logout")) { // log out
+ if (!strcasecmp(h->uri, "/ctdl/a/logout")) { // log out
logout(h, c);
- return;
+ return;
}
- if (!strcasecmp(h->uri, "/ctdl/a/whoami")) { // return display name of user
+ if (!strcasecmp(h->uri, "/ctdl/a/whoami")) { // return display name of user
whoami(h, c);
- return;
+ return;
}
- do_404(h); // unknown
+ do_404(h); // unknown
}
/*
* A CalDAV REPORT can only be one type. This is stored in the report_type member.
*/
-enum cr_type
-{
+enum cr_type {
cr_calendar_query,
cr_calendar_multiget,
cr_freebusy_query
*/
void caldav_xml_start(void *data, const char *el, const char **attr)
{
- struct cr_parms *crp = (struct cr_parms *)data;
+ struct cr_parms *crp = (struct cr_parms *) data;
int i;
// syslog(LOG_DEBUG, "CALDAV ELEMENT START: <%s> %d", el, crp->tag_nesting_level);
- for (i=0; attr[i] != NULL; i+=2) {
- syslog(LOG_DEBUG, " Attribute '%s' = '%s'", attr[i], attr[i+1]);
+ for (i = 0; attr[i] != NULL; i += 2) {
+ syslog(LOG_DEBUG, " Attribute '%s' = '%s'", attr[i], attr[i + 1]);
}
if (!strcasecmp(el, "urn:ietf:params:xml:ns:caldav:calendar-multiget")) {
*/
void caldav_xml_end(void *data, const char *el)
{
- struct cr_parms *crp = (struct cr_parms *)data;
+ struct cr_parms *crp = (struct cr_parms *) data;
--crp->tag_nesting_level;
if (crp->Chardata != NULL) {
}
// syslog(LOG_DEBUG, "CALDAV ELEMENT END : <%s> %d", el, crp->tag_nesting_level);
- if ( (!strcasecmp(el, "DAV::href")) || (!strcasecmp(el, "DAV:href")) ) {
- if (crp->Hrefs == NULL) { // append crp->Chardata to crp->Hrefs
+ if ((!strcasecmp(el, "DAV::href")) || (!strcasecmp(el, "DAV:href"))) {
+ if (crp->Hrefs == NULL) { // append crp->Chardata to crp->Hrefs
crp->Hrefs = NewStrBuf();
- }
- else {
+ } else {
StrBufAppendBufPlain(crp->Hrefs, HKEY("|"), 0);
}
StrBufAppendBuf(crp->Hrefs, crp->Chardata, 0);
}
- if (crp->Chardata != NULL) { // Tag is closed; chardata is now out of scope.
- FreeStrBuf(&crp->Chardata); // Free the buffer.
+ if (crp->Chardata != NULL) { // Tag is closed; chardata is now out of scope.
+ FreeStrBuf(&crp->Chardata); // Free the buffer.
crp->Chardata = NULL;
}
}
/*
* XML parser callback
*/
-void caldav_xml_chardata(void *data, const XML_Char *s, int len)
+void caldav_xml_chardata(void *data, const XML_Char * s, int len)
{
- struct cr_parms *crp = (struct cr_parms *)data;
+ struct cr_parms *crp = (struct cr_parms *) data;
if (crp->Chardata == NULL) {
crp->Chardata = NewStrBuf();
* NOTE: this function expects that "MSGP text/calendar" was issued at the beginning
* of a REPORT operation to set our preferred MIME type to calendar data.
*/
-StrBuf *fetch_ical(struct ctdlsession *c, long msgnum)
+StrBuf *fetch_ical(struct ctdlsession * c, long msgnum)
{
char buf[1024];
StrBuf *Buf = NULL;
}
while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) {
- if (Buf != NULL) { // already in body
+ if (Buf != NULL) { // already in body
StrBufAppendPrintf(Buf, "%s\n", buf);
- }
- else if (IsEmptyStr(buf)) { // beginning of body
+ } else if (IsEmptyStr(buf)) { // beginning of body
Buf = NewStrBuf();
}
}
* Called by caldav_report() to output a single item.
* Our policy is to throw away the list of properties the client asked for, and just send everything.
*/
-void caldav_response(struct http_transaction *h, struct ctdlsession *c, StrBuf *ReportOut, StrBuf *ThisHref)
+void caldav_response(struct http_transaction *h, struct ctdlsession *c, StrBuf * ReportOut, StrBuf * ThisHref)
{
long msgnum;
StrBuf *Caldata = NULL;
euid = strrchr(ChrPtr(ThisHref), '/');
if (euid != NULL) {
++euid;
- }
- else {
- euid = (char *)ChrPtr(ThisHref);
+ } else {
+ euid = (char *) ChrPtr(ThisHref);
}
char *unescaped_euid = strdup(euid);
- if (!unescaped_euid) return;
+ if (!unescaped_euid)
+ return;
unescape_input(unescaped_euid);
StrBufAppendPrintf(ReportOut, "<D:response>");
- StrBufAppendPrintf(ReportOut, "<D:href>");
- StrBufXMLEscAppend(ReportOut, ThisHref, NULL, 0, 0);
- StrBufAppendPrintf(ReportOut, "</D:href>");
- StrBufAppendPrintf(ReportOut, "<D:propstat>");
+ StrBufAppendPrintf(ReportOut, "<D:href>");
+ StrBufXMLEscAppend(ReportOut, ThisHref, NULL, 0, 0);
+ StrBufAppendPrintf(ReportOut, "</D:href>");
+ StrBufAppendPrintf(ReportOut, "<D:propstat>");
msgnum = locate_message_by_uid(c, unescaped_euid);
free(unescaped_euid);
Caldata = fetch_ical(c, msgnum);
}
- if (Caldata != NULL)
- {
+ if (Caldata != NULL) {
// syslog(LOG_DEBUG, "caldav_response(%s) 200 OK", ChrPtr(ThisHref));
- StrBufAppendPrintf(ReportOut, "<D:status>");
- StrBufAppendPrintf(ReportOut, "HTTP/1.1 200 OK");
- StrBufAppendPrintf(ReportOut, "</D:status>");
- StrBufAppendPrintf(ReportOut, "<D:prop>");
- StrBufAppendPrintf(ReportOut, "<D:getetag>");
- StrBufAppendPrintf(ReportOut, "%ld", msgnum);
- StrBufAppendPrintf(ReportOut, "</D:getetag>");
- StrBufAppendPrintf(ReportOut, "<C:calendar-data>");
- StrBufXMLEscAppend(ReportOut, Caldata, NULL, 0, 0);
- StrBufAppendPrintf(ReportOut, "</C:calendar-data>");
- StrBufAppendPrintf(ReportOut, "</D:prop>");
+ StrBufAppendPrintf(ReportOut, "<D:status>");
+ StrBufAppendPrintf(ReportOut, "HTTP/1.1 200 OK");
+ StrBufAppendPrintf(ReportOut, "</D:status>");
+ StrBufAppendPrintf(ReportOut, "<D:prop>");
+ StrBufAppendPrintf(ReportOut, "<D:getetag>");
+ StrBufAppendPrintf(ReportOut, "%ld", msgnum);
+ StrBufAppendPrintf(ReportOut, "</D:getetag>");
+ StrBufAppendPrintf(ReportOut, "<C:calendar-data>");
+ StrBufXMLEscAppend(ReportOut, Caldata, NULL, 0, 0);
+ StrBufAppendPrintf(ReportOut, "</C:calendar-data>");
+ StrBufAppendPrintf(ReportOut, "</D:prop>");
FreeStrBuf(&Caldata);
Caldata = NULL;
- }
- else {
+ } else {
// syslog(LOG_DEBUG, "caldav_response(%s) 404 not found", ChrPtr(ThisHref));
- StrBufAppendPrintf(ReportOut, "<D:status>");
- StrBufAppendPrintf(ReportOut, "HTTP/1.1 404 not found");
- StrBufAppendPrintf(ReportOut, "</D:status>");
+ StrBufAppendPrintf(ReportOut, "<D:status>");
+ StrBufAppendPrintf(ReportOut, "HTTP/1.1 404 not found");
+ StrBufAppendPrintf(ReportOut, "</D:status>");
}
- StrBufAppendPrintf(ReportOut, "</D:propstat>");
+ StrBufAppendPrintf(ReportOut, "</D:propstat>");
StrBufAppendPrintf(ReportOut, "</D:response>");
}
XML_SetElementHandler(xp, caldav_xml_start, caldav_xml_end);
XML_SetCharacterDataHandler(xp, caldav_xml_chardata);
XML_SetUserData(xp, &crp);
- XML_SetDefaultHandler(xp, NULL); // Disable internal entity expansion to prevent "billion laughs attack"
+ XML_SetDefaultHandler(xp, NULL); // Disable internal entity expansion to prevent "billion laughs attack"
XML_Parse(xp, h->request_body, h->request_body_length, 1);
XML_ParserFree(xp);
- if (crp.Chardata != NULL) { // Discard any trailing chardata ... normally nothing here
+ if (crp.Chardata != NULL) { // Discard any trailing chardata ... normally nothing here
FreeStrBuf(&crp.Chardata);
crp.Chardata = NULL;
}
syslog(LOG_DEBUG, "CalDAV REPORT type is: %d", crp.report_type);
StrBuf *ReportOut = NewStrBuf();
StrBufAppendPrintf(ReportOut, "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
- "<D:multistatus "
- "xmlns:D=\"DAV:\" "
- "xmlns:C=\"urn:ietf:params:xml:ns:caldav\""
- ">"
- );
+ "<D:multistatus " "xmlns:D=\"DAV:\" " "xmlns:C=\"urn:ietf:params:xml:ns:caldav\"" ">");
- if (crp.Hrefs != NULL) { // Output all qualifying calendar items!
+ if (crp.Hrefs != NULL) { // Output all qualifying calendar items!
StrBuf *ThisHref = NewStrBuf();
const char *pvset = NULL;
while (StrBufExtract_NextToken(ThisHref, crp.Hrefs, &pvset, '|') >= 0) {
crp.Hrefs = NULL;
}
- StrBufAppendPrintf(ReportOut, "</D:multistatus>\n"); // End the REPORT.
+ StrBufAppendPrintf(ReportOut, "</D:multistatus>\n"); // End the REPORT.
add_response_header(h, strdup("Content-type"), strdup("text/xml"));
h->response_code = 207;
JsonValue *j = NewJsonObject(HKEY("serv_info"));
int i = 0;
- while (ctdl_readline(c, buf, sizeof(buf)) , strcmp(buf, "000")) switch(i++) {
+ while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000"))
+ switch (i++) {
case 0:
- JsonObjectAppend(j, NewJsonNumber( HKEY("serv_pid"), atol(buf)));
+ JsonObjectAppend(j, NewJsonNumber(HKEY("serv_pid"), atol(buf)));
break;
case 1:
- JsonObjectAppend(j, NewJsonPlainString( HKEY("serv_nodename"), buf, -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("serv_nodename"), buf, -1));
break;
case 2:
- JsonObjectAppend(j, NewJsonPlainString( HKEY("serv_humannode"), buf, -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("serv_humannode"), buf, -1));
break;
case 3:
- JsonObjectAppend(j, NewJsonPlainString( HKEY("serv_fqdn"), buf, -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("serv_fqdn"), buf, -1));
break;
case 4:
- JsonObjectAppend(j, NewJsonPlainString( HKEY("serv_software"), buf, -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("serv_software"), buf, -1));
break;
case 5:
- JsonObjectAppend(j, NewJsonNumber( HKEY("serv_rev_level"), atol(buf)));
+ JsonObjectAppend(j, NewJsonNumber(HKEY("serv_rev_level"), atol(buf)));
break;
case 6:
- JsonObjectAppend(j, NewJsonPlainString( HKEY("serv_bbs_city"), buf, -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("serv_bbs_city"), buf, -1));
break;
case 7:
- JsonObjectAppend(j, NewJsonPlainString( HKEY("serv_sysadm"), buf, -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("serv_sysadm"), buf, -1));
break;
case 14:
- JsonObjectAppend(j, NewJsonBool( HKEY("serv_supports_ldap"), atoi(buf)));
+ JsonObjectAppend(j, NewJsonBool(HKEY("serv_supports_ldap"), atoi(buf)));
break;
case 15:
- JsonObjectAppend(j, NewJsonBool( HKEY("serv_newuser_disabled"), atoi(buf)));
+ JsonObjectAppend(j, NewJsonBool(HKEY("serv_newuser_disabled"), atoi(buf)));
break;
case 16:
- JsonObjectAppend(j, NewJsonPlainString( HKEY("serv_default_cal_zone"), buf, -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("serv_default_cal_zone"), buf, -1));
break;
case 20:
- JsonObjectAppend(j, NewJsonBool( HKEY("serv_supports_sieve"), atoi(buf)));
+ JsonObjectAppend(j, NewJsonBool(HKEY("serv_supports_sieve"), atoi(buf)));
break;
case 21:
- JsonObjectAppend(j, NewJsonBool( HKEY("serv_fulltext_enabled"), atoi(buf)));
+ JsonObjectAppend(j, NewJsonBool(HKEY("serv_fulltext_enabled"), atoi(buf)));
break;
case 22:
- JsonObjectAppend(j, NewJsonPlainString( HKEY("serv_svn_revision"), buf, -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("serv_svn_revision"), buf, -1));
break;
case 23:
- JsonObjectAppend(j, NewJsonBool( HKEY("serv_supports_openid"), atoi(buf)));
+ JsonObjectAppend(j, NewJsonBool(HKEY("serv_supports_openid"), atoi(buf)));
break;
case 24:
- JsonObjectAppend(j, NewJsonBool( HKEY("serv_supports_guest"), atoi(buf)));
+ JsonObjectAppend(j, NewJsonBool(HKEY("serv_supports_guest"), atoi(buf)));
break;
- }
+ }
StrBuf *sj = NewStrBuf();
SerializeJson(sj, j, 1); // '1' == free the source array
{
if (!strcasecmp(h->uri, "/ctdl/c/info")) {
serv_info(h, c);
- }
- else {
+ } else {
do_404(h);
}
}
int len = 0;
int c = 0;
- if (buf == NULL) return(-1);
+ if (buf == NULL)
+ return (-1);
while (len < maxbytes) {
c = read(ctdl->sock, &buf[len], 1);
if (c <= 0) {
syslog(LOG_DEBUG, "Socket error or zero-length read");
- return(-1);
+ return (-1);
}
if (buf[len] == '\n') {
- if ( (len >0) && (buf[len-1] == '\r') ) {
+ if ((len > 0) && (buf[len - 1] == '\r')) {
--len;
}
buf[len] = 0;
// syslog(LOG_DEBUG, "\033[33m[ %s\033[0m", buf);
- return(len);
+ return (len);
}
++len;
}
// syslog(LOG_DEBUG, "\033[33m[ %s\033[0m", buf);
- return(len);
+ return (len);
}
* Implemented in terms of ctdl_readline() and is therefore transparent...
* Returns a newly allocated StrBuf or NULL for error.
*/
-StrBuf *ctdl_readtextmsg(struct ctdlsession *ctdl)
+StrBuf *ctdl_readtextmsg(struct ctdlsession * ctdl)
{
char buf[1024];
StrBuf *sj = NewStrBuf();
return NULL;
}
- while ( (ctdl_readline(ctdl, buf, sizeof(buf)) >= 0) && (strcmp(buf, "000")) ) {
+ while ((ctdl_readline(ctdl, buf, sizeof(buf)) >= 0) && (strcmp(buf, "000"))) {
StrBufAppendPrintf(sj, "%s\n", buf);
}
* Write to the Citadel server. For now we're just wrapping write() in case we
* need to add anything else later.
*/
-ssize_t ctdl_write(struct ctdlsession *ctdl, const void *buf, size_t count) {
+ssize_t ctdl_write(struct ctdlsession * ctdl, const void *buf, size_t count)
+{
return write(ctdl->sock, buf, count);
}
/*
* printf() type function to send data to the Citadel Server.
*/
-void ctdl_printf(struct ctdlsession *ctdl, const char *format,...)
+void ctdl_printf(struct ctdlsession *ctdl, const char *format, ...)
{
va_list arg_ptr;
StrBuf *Buf = NewStrBuf();
va_end(arg_ptr);
syslog(LOG_DEBUG, "\033[32m] %s\033[0m", ChrPtr(Buf));
- ctdl_write(ctdl, (char *)ChrPtr(Buf), StrLength(Buf));
+ ctdl_write(ctdl, (char *) ChrPtr(Buf), StrLength(Buf));
ctdl_write(ctdl, "\n", 1);
FreeStrBuf(&Buf);
}
s = socket(AF_UNIX, SOCK_STREAM, 0);
if (s < 0) {
syslog(LOG_WARNING, "Can't create socket [%s]: %s", sockpath, strerror(errno));
- return(-1);
+ return (-1);
}
if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
syslog(LOG_WARNING, "Can't connect [%s]: %s", sockpath, strerror(errno));
close(s);
- return(-1);
+ return (-1);
}
return s;
}
* Handle numeric IPv4 and IPv6 addresses
*/
rc = inet_pton(AF_INET, host, &serveraddr);
- if (rc == 1) { /* dotted quad */
+ if (rc == 1) { /* dotted quad */
hints.ai_family = AF_INET;
hints.ai_flags |= AI_NUMERICHOST;
} else {
rc = inet_pton(AF_INET6, host, &serveraddr);
- if (rc == 1) { /* IPv6 address */
+ if (rc == 1) { /* IPv6 address */
hints.ai_family = AF_INET6;
hints.ai_flags |= AI_NUMERICHOST;
}
if (rc != 0) {
syslog(LOG_DEBUG, "%s: %s", host, gai_strerror(rc));
freeaddrinfo(res);
- return(-1);
+ return (-1);
}
/*
*/
for (ai = res; ai != NULL; ai = ai->ai_next) {
- if (ai->ai_family == AF_INET) syslog(LOG_DEBUG, "Trying IPv4");
- else if (ai->ai_family == AF_INET6) syslog(LOG_DEBUG, "Trying IPv6");
- else syslog(LOG_WARNING, "This is going to fail.");
+ if (ai->ai_family == AF_INET)
+ syslog(LOG_DEBUG, "Trying IPv4");
+ else if (ai->ai_family == AF_INET6)
+ syslog(LOG_DEBUG, "Trying IPv6");
+ else
+ syslog(LOG_WARNING, "This is going to fail.");
s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (s < 0) {
syslog(LOG_WARNING, "socket() failed: %s", strerror(errno));
freeaddrinfo(res);
- return(-1);
+ return (-1);
}
rc = connect(s, ai->ai_addr, ai->ai_addrlen);
if (rc >= 0) {
fdflags = fcntl(rc, F_GETFL);
if (fdflags < 0) {
- syslog(LOG_ERR,
- "unable to get socket %d flags! %s",
- rc,
- strerror(errno));
+ syslog(LOG_ERR, "unable to get socket %d flags! %s", rc, strerror(errno));
close(rc);
return -1;
}
fdflags = fdflags | O_NONBLOCK;
if (fcntl(rc, F_SETFL, fdflags) < 0) {
- syslog(LOG_ERR,
- "unable to set socket %d nonblocking flags! %s",
- rc,
- strerror(errno));
+ syslog(LOG_ERR, "unable to set socket %d nonblocking flags! %s", rc, strerror(errno));
close(s);
return -1;
}
- return(s);
- }
- else {
+ return (s);
+ } else {
syslog(LOG_WARNING, "connect() failed: %s", strerror(errno));
close(s);
}
}
- freeaddrinfo(res);
- return(-1);
+ freeaddrinfo(res);
+ return (-1);
}
*/
void extract_auth(struct http_transaction *h, char *authbuf, int authbuflen)
{
- if (authbuf == NULL) return;
+ if (authbuf == NULL)
+ return;
authbuf[0] = 0;
char *authheader = header_val(h, "Authorization");
if (authheader) {
if (!strncasecmp(authheader, "Basic ", 6)) {
safestrncpy(authbuf, &authheader[6], authbuflen);
- return; // HTTP-AUTH was found -- stop here
+ return; // HTTP-AUTH was found -- stop here
}
}
if (strlen(authbuf) < 3) { // impossibly small
authbuf[0] = 0;
}
- return; // Cookie auth was found -- stop here
+ return; // Cookie auth was found -- stop here
}
}
-
// no authorization found in headers ... this is an anonymous session
}
if (resultbuf != NULL) {
buf = resultbuf;
- }
- else {
+ } else {
buf = localbuf;
}
buflen = CtdlDecodeBase64(buf, auth, strlen(auth));
extract_token(supplied_username, buf, 0, ':', sizeof supplied_username);
extract_token(supplied_password, buf, 1, ':', sizeof supplied_password);
- syslog(LOG_DEBUG, "Supplied credentials: username=%s, pwlen=%d", supplied_username, (int)strlen(supplied_password));
+ syslog(LOG_DEBUG, "Supplied credentials: username=%s, pwlen=%d", supplied_username, (int) strlen(supplied_password));
ctdl_printf(c, "USER %s", supplied_username);
ctdl_readline(c, buf, 1024);
if (buf[0] != '3') {
syslog(LOG_DEBUG, "No such user: %s", buf);
- return(1); // no such user; resultbuf will explain why
+ return (1); // no such user; resultbuf will explain why
}
ctdl_printf(c, "PASS %s", supplied_password);
strcpy(c->auth, auth);
extract_token(c->whoami, &buf[4], 0, '|', sizeof c->whoami);
syslog(LOG_DEBUG, "Login succeeded: %s", buf);
- return(0);
+ return (0);
}
syslog(LOG_DEBUG, "Login failed: %s", buf);
- return(1); // login failed; resultbuf will explain why
+ return (1); // login failed; resultbuf will explain why
}
/*
* Hunt for, or create, a connection to our Citadel Server
*/
-struct ctdlsession *connect_to_citadel(struct http_transaction *h) {
+struct ctdlsession *connect_to_citadel(struct http_transaction *h)
+{
struct ctdlsession *cptr = NULL;
struct ctdlsession *my_session = NULL;
int is_new_session = 0;
// Does the request carry a username and password?
extract_auth(h, auth, sizeof auth);
- syslog(LOG_DEBUG, "Session auth: %s", auth); // remove this log when development is done
+ syslog(LOG_DEBUG, "Session auth: %s", auth); // remove this log when development is done
// Lock the connection pool while we claim our connection
pthread_mutex_lock(&cpool_mutex);
- if (cpool != NULL) for (cptr = cpool; ((cptr != NULL) && (my_session == NULL)); cptr = cptr->next) {
- if ( (cptr->is_bound == 0) && (!strcmp(cptr->auth, auth)) ) {
- my_session = cptr;
- my_session->is_bound = 1;
+ if (cpool != NULL)
+ for (cptr = cpool; ((cptr != NULL) && (my_session == NULL)); cptr = cptr->next) {
+ if ((cptr->is_bound == 0) && (!strcmp(cptr->auth, auth))) {
+ my_session = cptr;
+ my_session->is_bound = 1;
+ }
}
- }
if (my_session == NULL) {
syslog(LOG_DEBUG, "No qualifying sessions , starting a new one");
my_session = malloc(sizeof(struct ctdlsession));
}
pthread_mutex_unlock(&cpool_mutex);
if (my_session == NULL) {
- return(NULL); // oh well
+ return (NULL); // oh well
}
if (my_session->sock < 3) {
is_new_session = 1;
- }
- else { // make sure our Citadel session is still good
+ } else { // make sure our Citadel session is still good
int test_conn;
test_conn = ctdl_write(my_session, HKEY("NOOP\n"));
if (test_conn < 5) {
close(my_session->sock);
my_session->sock = 0;
is_new_session = 1;
- }
- else {
+ } else {
test_conn = ctdl_readline(my_session, buf, sizeof(buf));
if (test_conn < 1) {
syslog(LOG_DEBUG, "Citadel session is broken , must reconnect");
my_session->last_access = time(NULL);
++my_session->num_requests_handled;
- return(my_session);
+ return (my_session);
}
/*
* Release our Citadel Server connection back into the pool.
*/
-void disconnect_from_citadel(struct ctdlsession *ctdl) {
+void disconnect_from_citadel(struct ctdlsession *ctdl)
+{
pthread_mutex_lock(&cpool_mutex);
ctdl->is_bound = 0;
pthread_mutex_unlock(&cpool_mutex);
int i = 0;
char buf[1024];
- if ( (c == NULL) || (msgnums == NULL) || (num_msgs < 1) )
- {
+ if ((c == NULL) || (msgnums == NULL) || (num_msgs < 1)) {
return;
}
strcpy(buf, "DELE ");
do {
sprintf(&buf[strlen(buf)], "%ld", msgnums[i]);
- if ( (((i+1)%50)==0) || (i==num_msgs-1)) // delete up to 50 messages with one server command
+ if ((((i + 1) % 50) == 0) || (i == num_msgs - 1)) // delete up to 50 messages with one server command
{
syslog(LOG_DEBUG, "%s", buf);
ctdl_printf(c, "%s", buf);
ctdl_readline(c, buf, sizeof(buf));
syslog(LOG_DEBUG, "%s", buf);
- }
- else {
+ } else {
strcat(buf, ",");
}
} while (++i < num_msgs);
void setup_for_forum_view(struct ctdlsession *c)
{
char buf[1024];
- ctdl_printf(c, "MSGP text/html|text/plain"); // Declare the MIME types we know how to render
- ctdl_readline(c, buf, sizeof(buf)); // Ignore the response
- ctdl_printf(c, "MSGP dont_decode"); // Tell the server we will decode base64/etc client-side
- ctdl_readline(c, buf, sizeof(buf)); // Ignore the response
+ ctdl_printf(c, "MSGP text/html|text/plain"); // Declare the MIME types we know how to render
+ ctdl_readline(c, buf, sizeof(buf)); // Ignore the response
+ ctdl_printf(c, "MSGP dont_decode"); // Tell the server we will decode base64/etc client-side
+ ctdl_readline(c, buf, sizeof(buf)); // Ignore the response
}
// Renderer for one message in the threaded view
// (This will probably work for the flat view too.)
//
-void forum_render_one_message(struct ctdlsession *c, StrBuf *sj, long msgnum)
+void forum_render_one_message(struct ctdlsession *c, StrBuf * sj, long msgnum)
{
StrBuf *raw_msg = NULL;
StrBuf *sanitized_msg = NULL;
char content_transfer_encoding[1024] = { 0 };
char content_type[1024] = { 0 };
char author[128] = { 0 };
- char datetime[128] = { 0 } ;
+ char datetime[128] = { 0 };
ctdl_printf(c, "MSG4 %ld", msgnum);
ctdl_readline(c, buf, sizeof(buf));
return;
}
- while ( (ctdl_readline(c, buf, sizeof(buf)) >= 0) && (strcmp(buf, "text")) && (strcmp(buf, "000")) ) {
+ while ((ctdl_readline(c, buf, sizeof(buf)) >= 0) && (strcmp(buf, "text")) && (strcmp(buf, "000"))) {
// citadel header parsing here
if (!strncasecmp(buf, "from=", 5)) {
safestrncpy(author, &buf[5], sizeof author);
}
if (!strcmp(buf, "text")) {
- while ( (ctdl_readline(c, buf, sizeof(buf)) >= 0) && (strcmp(buf, "")) && (strcmp(buf, "000")) ) {
+ while ((ctdl_readline(c, buf, sizeof(buf)) >= 0) && (strcmp(buf, "")) && (strcmp(buf, "000"))) {
// rfc822 header parsing here
if (!strncasecmp(buf, "Content-transfer-encoding:", 26)) {
strcpy(content_transfer_encoding, &buf[26]);
}
}
raw_msg = ctdl_readtextmsg(c);
- }
- else {
+ } else {
raw_msg = NULL;
}
// begin output
- StrBufAppendPrintf(sj, "<div>"); // begin message wrapper
- StrBufAppendPrintf(sj, "<div style=\"float:left;padding-right:2px\">"); // begin avatar FIXME move the style to a stylesheet
- StrBufAppendPrintf(sj, "<i class=\"fa fa-user-circle fa-2x\"></i> "); // FIXME temporary avatar
- StrBufAppendPrintf(sj, "</div>"); // end avatar
- StrBufAppendPrintf(sj, "<div>"); // begin content
- StrBufAppendPrintf(sj, "<div>"); // begin header
+ StrBufAppendPrintf(sj, "<div>"); // begin message wrapper
+ StrBufAppendPrintf(sj, "<div style=\"float:left;padding-right:2px\">"); // begin avatar FIXME move the style to a stylesheet
+ StrBufAppendPrintf(sj, "<i class=\"fa fa-user-circle fa-2x\"></i> "); // FIXME temporary avatar
+ StrBufAppendPrintf(sj, "</div>"); // end avatar
+ StrBufAppendPrintf(sj, "<div>"); // begin content
+ StrBufAppendPrintf(sj, "<div>"); // begin header
StrBufAppendPrintf(sj, "<span class=\"ctdl-username\"><a href=\"#\">%s</a></span> ", author); // FIXME link to user profile or whatever
StrBufAppendPrintf(sj, "<span class=\"ctdl-msgdate\">%s</span> ", datetime);
- StrBufAppendPrintf(sj, "</div>"); // end header
- StrBufAppendPrintf(sj, "<div>"); // begin body
+ StrBufAppendPrintf(sj, "</div>"); // end header
+ StrBufAppendPrintf(sj, "<div>"); // begin body
if (raw_msg) {
if (!strcasecmp(content_transfer_encoding, "quoted-printable")) {
StrBufDecodeQP(raw_msg);
}
-
// At this point, raw_msg contains the decoded message.
// Now run through the renderers we have available.
if (!strncasecmp(content_type, "text/html", 9)) {
sanitized_msg = html2html("UTF-8", 0, c->room, msgnum, raw_msg);
- }
- else if (!strncasecmp(content_type, "text/plain", 10)) {
+ } else if (!strncasecmp(content_type, "text/plain", 10)) {
sanitized_msg = text2html("UTF-8", 0, c->room, msgnum, raw_msg);
- }
- else if (!strncasecmp(content_type, "text/x-citadel-variformat", 25)) {
+ } else if (!strncasecmp(content_type, "text/x-citadel-variformat", 25)) {
sanitized_msg = variformat2html(raw_msg);
- }
- else {
+ } else {
sanitized_msg = NewStrBufPlain(HKEY("<i>No renderer for this content type</i><br>"));
}
FreeStrBuf(&raw_msg);
}
}
- StrBufAppendPrintf(sj, "</div>"); // end body
- StrBufAppendPrintf(sj, "</div>"); // end content
- StrBufAppendPrintf(sj, "</div>"); // end wrapper
+ StrBufAppendPrintf(sj, "</div>"); // end body
+ StrBufAppendPrintf(sj, "</div>"); // end content
+ StrBufAppendPrintf(sj, "</div>"); // end wrapper
}
// Threaded view (recursive section)
//
-void thread_o_print(struct ctdlsession *c, StrBuf *sj, struct mthread *m, int num_msgs, int where_parent_is, int nesting_level)
+void thread_o_print(struct ctdlsession *c, StrBuf * sj, struct mthread *m, int num_msgs, int where_parent_is, int nesting_level)
{
int i = 0;
int j = 0;
int num_printed = 0;
- for (i=0; i<num_msgs; ++i) {
+ for (i = 0; i < num_msgs; ++i) {
if (m[i].parent == where_parent_is) {
if (++num_printed == 1) {
StrBufAppendPrintf(sj, "<ul style=\"list-style-type: none;\">");
}
- StrBufAppendPrintf(sj, "<li class=\"post\" id=\"post-%ld\">", m[i].msgnum);
+ StrBufAppendPrintf(sj, "<li class=\"post\" id=\"post-%ld\">", m[i].msgnum);
forum_render_one_message(c, sj, m[i].msgnum);
StrBufAppendPrintf(sj, "</li>\r\n");
if (i != 0) {
- thread_o_print(c, sj, m, num_msgs, i, nesting_level+1);
+ thread_o_print(c, sj, m, num_msgs, i, nesting_level + 1);
}
}
}
char refs[1024];
int i, j, k;
- ctdl_printf(c, "MSGS ALL|||9"); // 9 == headers + thread references
+ ctdl_printf(c, "MSGS ALL|||9"); // 9 == headers + thread references
ctdl_readline(c, buf, sizeof(buf));
if (buf[0] != '1') {
do_404(h);
StrBuf *sj = NewStrBuf();
StrBufAppendPrintf(sj, "<html><body>\r\n");
- while (ctdl_readline(c, buf, sizeof buf), strcmp(buf,"000")) {
+ while (ctdl_readline(c, buf, sizeof buf), strcmp(buf, "000")) {
++num_msgs;
if (num_msgs > num_alloc) {
if (num_alloc == 0) {
num_alloc = 100;
m = malloc(num_alloc * sizeof(struct mthread));
- }
- else {
+ } else {
num_alloc *= 2;
m = realloc(m, (num_alloc * sizeof(struct mthread)));
}
}
- memset(&m[num_msgs-1], 0, sizeof(struct mthread));
- m[num_msgs-1].msgnum = extract_long(buf, 0);
- m[num_msgs-1].datetime = extract_long(buf, 1);
- extract_token(m[num_msgs-1].from, buf, 2, '|', sizeof m[num_msgs-1].from);
- m[num_msgs-1].threadhash = extract_int(buf, 6);
+ memset(&m[num_msgs - 1], 0, sizeof(struct mthread));
+ m[num_msgs - 1].msgnum = extract_long(buf, 0);
+ m[num_msgs - 1].datetime = extract_long(buf, 1);
+ extract_token(m[num_msgs - 1].from, buf, 2, '|', sizeof m[num_msgs - 1].from);
+ m[num_msgs - 1].threadhash = extract_int(buf, 6);
extract_token(refs, buf, 7, '|', sizeof refs);
char *t;
i = 0;
while ((t = strtok_r(r, ",", &r))) {
if (i == 0) {
- m[num_msgs-1].refhashes[0] = atoi(t); // always keep the first one
- }
- else {
- memcpy(&m[num_msgs-1].refhashes[1], &m[num_msgs-1].refhashes[2], sizeof(int)*8 ); // shift the rest
- m[num_msgs-1].refhashes[9] = atoi(t);
+ m[num_msgs - 1].refhashes[0] = atoi(t); // always keep the first one
+ } else {
+ memcpy(&m[num_msgs - 1].refhashes[1], &m[num_msgs - 1].refhashes[2], sizeof(int) * 8); // shift the rest
+ m[num_msgs - 1].refhashes[9] = atoi(t);
}
++i;
}
}
// Sort by thread. I did read jwz's sorting algorithm and it looks pretty good, but jwz is a self-righteous asshole so we do it our way.
- for (i=0; i<num_msgs; ++i) {
- for (j=9; (j>=0)&&(m[i].parent==0); --j) {
- for (k=0; (k<num_msgs)&&(m[i].parent==0); ++k) {
+ for (i = 0; i < num_msgs; ++i) {
+ for (j = 9; (j >= 0) && (m[i].parent == 0); --j) {
+ for (k = 0; (k < num_msgs) && (m[i].parent == 0); ++k) {
if (m[i].refhashes[j] == m[k].threadhash) {
m[i].parent = k;
}
// Now render it
setup_for_forum_view(c);
- thread_o_print(c, sj, m, num_msgs, 0, 0); // Render threads recursively and recursively
+ thread_o_print(c, sj, m, num_msgs, 0, 0); // Render threads recursively and recursively
// Garbage collection is for people who aren't smart enough to manage their own memory.
if (num_msgs > 0) {
long *msglist = get_msglist(c, "ALL");
if (msglist) {
int i;
- for (i=0; (msglist[i] > 0); ++i) {
+ for (i = 0; (msglist[i] > 0); ++i) {
forum_render_one_message(c, sj, msglist[i]);
}
free(msglist);
}
-// render one message (entire transaction) FIXME EXTERMINATE
+// render one message (entire transaction) FIXME EXTERMINATE
//
void html_render_one_message(struct http_transaction *h, struct ctdlsession *c, long msgnum)
{
StrBuf *sj = NewStrBuf();
StrBufAppendPrintf(sj, "<html><body>\r\n");
- setup_for_forum_view(c); // FIXME way too inefficient to do this for every message !!!!!!!!!!!!!
+ setup_for_forum_view(c); // FIXME way too inefficient to do this for every message !!!!!!!!!!!!!
forum_render_one_message(c, sj, msgnum);
StrBufAppendPrintf(sj, "</body></html>\r\n");
add_response_header(h, strdup("Content-type"), strdup("text/html; charset=utf-8"));
char content_transfer_encoding[1024] = { 0 };
char content_type[1024] = { 0 };
char author[128] = { 0 };
- char datetime[128] = { 0 } ;
+ char datetime[128] = { 0 };
setup_for_forum_view(c);
JsonValue *j = NewJsonObject(HKEY("message"));
- while ( (ctdl_readline(c, buf, sizeof(buf)) >= 0) && (strcmp(buf, "text")) && (strcmp(buf, "000")) ) {
+ while ((ctdl_readline(c, buf, sizeof(buf)) >= 0) && (strcmp(buf, "text")) && (strcmp(buf, "000"))) {
// citadel header parsing here
if (!strncasecmp(buf, "from=", 5)) {
- JsonObjectAppend(j, NewJsonPlainString( HKEY("from"), &buf[5], -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("from"), &buf[5], -1));
}
if (!strncasecmp(buf, "rfca=", 5)) {
- JsonObjectAppend(j, NewJsonPlainString( HKEY("from"), &buf[5], -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("from"), &buf[5], -1));
}
if (!strncasecmp(buf, "time=", 5)) {
time_t tt;
tt = atol(&buf[5]);
localtime_r(&tt, &tm);
strftime(datetime, sizeof datetime, "%c", &tm);
- JsonObjectAppend(j, NewJsonPlainString( HKEY("time"), datetime, -1));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("time"), datetime, -1));
}
}
if (!strcmp(buf, "text")) {
- while ( (ctdl_readline(c, buf, sizeof(buf)) >= 0) && (strcmp(buf, "")) && (strcmp(buf, "000")) ) {
+ while ((ctdl_readline(c, buf, sizeof(buf)) >= 0) && (strcmp(buf, "")) && (strcmp(buf, "000"))) {
// rfc822 header parsing here
if (!strncasecmp(buf, "Content-transfer-encoding:", 26)) {
strcpy(content_transfer_encoding, &buf[26]);
}
}
raw_msg = ctdl_readtextmsg(c);
- }
- else {
+ } else {
raw_msg = NULL;
}
if (!strcasecmp(content_transfer_encoding, "quoted-printable")) {
StrBufDecodeQP(raw_msg);
}
-
// At this point, raw_msg contains the decoded message.
// Now run through the renderers we have available.
if (!strncasecmp(content_type, "text/html", 9)) {
sanitized_msg = html2html("UTF-8", 0, c->room, msgnum, raw_msg);
- }
- else if (!strncasecmp(content_type, "text/plain", 10)) {
+ } else if (!strncasecmp(content_type, "text/plain", 10)) {
sanitized_msg = text2html("UTF-8", 0, c->room, msgnum, raw_msg);
- }
- else if (!strncasecmp(content_type, "text/x-citadel-variformat", 25)) {
+ } else if (!strncasecmp(content_type, "text/x-citadel-variformat", 25)) {
sanitized_msg = variformat2html(raw_msg);
- }
- else {
+ } else {
sanitized_msg = NewStrBufPlain(HKEY("<i>No renderer for this content type</i><br>"));
}
FreeStrBuf(&raw_msg);
}
StrBuf *sj = NewStrBuf();
- SerializeJson(sj, j, 1); // '1' == free the source object
+ SerializeJson(sj, j, 1); // '1' == free the source object
add_response_header(h, strdup("Content-type"), strdup("application/json"));
h->response_code = 200;
{
int len;
- if (!s) return;
+ if (!s)
+ return;
len = strlen(s);
- if (len < 2) return;
+ if (len < 2)
+ return;
- if ( ( (s[0] == '\"') && (s[len-1] == '\"') ) || ( (s[0] == '\'') && (s[len-1] == '\'') ) ) {
- s[len-1] = 0;
+ if (((s[0] == '\"') && (s[len - 1] == '\"')) || ((s[0] == '\'') && (s[len - 1] == '\''))) {
+ s[len - 1] = 0;
strcpy(s, &s[1]);
}
}
char *ptr;
char buf[64];
- if (!charset) return;
- if (!meta_http_equiv) return;
- if (!meta_content) return;
+ if (!charset)
+ return;
+ if (!meta_http_equiv)
+ return;
+ if (!meta_content)
+ return;
- if (strcasecmp(meta_http_equiv, "Content-type")) return;
+ if (strcasecmp(meta_http_equiv, "Content-type"))
+ return;
ptr = strchr(meta_content, ';');
- if (!ptr) return;
+ if (!ptr)
+ return;
safestrncpy(buf, ++ptr, sizeof buf);
striplt(buf);
}
/* Remove wandering punctuation */
- if ((ptr=strchr(charset, '\"'))) *ptr = 0;
+ if ((ptr = strchr(charset, '\"')))
+ *ptr = 0;
striplt(charset);
}
}
* Also fixup img src="cid:..." type inline images to fetch the image
*
*/
-StrBuf *html2html(const char *supplied_charset, int treat_as_wiki, char *roomname, long msgnum, StrBuf *Source) {
+StrBuf *html2html(const char *supplied_charset, int treat_as_wiki, char *roomname, long msgnum, StrBuf * Source)
+{
char buf[SIZ];
char *msg;
char *ptr;
char charset[128];
StrBuf *BodyArea = NULL;
- iconv_t ic = (iconv_t)(-1) ;
- char *ibuf; /* Buffer of characters to be converted */
- char *obuf; /* Buffer for converted characters */
- size_t ibuflen; /* Length of input buffer */
- size_t obuflen; /* Length of output buffer */
- char *osav; /* Saved pointer to output buffer */
+ iconv_t ic = (iconv_t) (-1);
+ char *ibuf; /* Buffer of characters to be converted */
+ char *obuf; /* Buffer for converted characters */
+ size_t ibuflen; /* Length of input buffer */
+ size_t obuflen; /* Length of output buffer */
+ char *osav; /* Saved pointer to output buffer */
if (msg == NULL) {
- return(NULL);
+ return (NULL);
}
StrBuf *Target = NewStrBuf();
if (Target == NULL) {
- return(NULL);
+ return (NULL);
}
safestrncpy(charset, supplied_charset, sizeof charset);
sprintf(new_window, "<a target=\"%s\" href=", TARGET);
content_length = StrLength(Source);
- msg = (char*) ChrPtr(Source);
+ msg = (char *) ChrPtr(Source);
buffer_length = content_length;
/* Do a first pass to isolate the message body */
/* Advance to next tag */
ptr = strchr(ptr, '<');
- if ((ptr == NULL) || (ptr >= msgend)) break;
+ if ((ptr == NULL) || (ptr >= msgend))
+ break;
++ptr;
- if ((ptr == NULL) || (ptr >= msgend)) break;
+ if ((ptr == NULL) || (ptr >= msgend))
+ break;
/*
* Look for META tags. Some messages (particularly in
/*
* Any of these tags cause everything up to and including
* the tag to be removed.
- */
- if ( (!strncasecmp(ptr, "HTML", 4))
- ||(!strncasecmp(ptr, "HEAD", 4))
- ||(!strncasecmp(ptr, "/HEAD", 5))
- ||(!strncasecmp(ptr, "BODY", 4)) ) {
+ */
+ if ((!strncasecmp(ptr, "HTML", 4))
+ || (!strncasecmp(ptr, "HEAD", 4))
+ || (!strncasecmp(ptr, "/HEAD", 5))
+ || (!strncasecmp(ptr, "BODY", 4))) {
char *pBody = NULL;
if (!strncasecmp(ptr, "BODY", 4)) {
pBody = ptr;
}
ptr = strchr(ptr, '>');
- if ((ptr == NULL) || (ptr >= msgend)) break;
+ if ((ptr == NULL) || (ptr >= msgend))
+ break;
if ((pBody != NULL) && (ptr - pBody > 4)) {
char *src;
char *cid_start, *cid_end;
*ptr = '\0';
- pBody += 4;
+ pBody += 4;
while ((isspace(*pBody)) && (pBody < ptr))
- pBody ++;
- BodyArea = NewStrBufPlain(NULL, ptr - pBody);
+ pBody++;
+ BodyArea = NewStrBufPlain(NULL, ptr - pBody);
if (pBody < ptr) {
src = strstr(pBody, "cid:");
if (src) {
cid_start = src + 4;
cid_end = cid_start;
- while ((*cid_end != '"') &&
- !isspace(*cid_end) &&
- (cid_end < ptr))
- cid_end ++;
+ while ((*cid_end != '"') && !isspace(*cid_end) && (cid_end < ptr))
+ cid_end++;
/* copy tag and attributes up to src="cid: */
StrBufAppendBufPlain(BodyArea, pBody, src - pBody, 0);
/* add in /webcit/mimepart/<msgno>/CID/
trailing / stops dumb URL filters getting excited */
- StrBufAppendPrintf(BodyArea,
- "/webcit/mimepart/%ld/",msgnum);
+ StrBufAppendPrintf(BodyArea, "/webcit/mimepart/%ld/", msgnum);
StrBufAppendBufPlain(BodyArea, cid_start, cid_end - cid_start, 0);
if (ptr - cid_end > 0)
- StrBufAppendBufPlain(BodyArea,
- cid_end + 1,
- ptr - cid_end, 0);
- }
- else
+ StrBufAppendBufPlain(BodyArea, cid_end + 1, ptr - cid_end, 0);
+ } else
StrBufAppendBufPlain(BodyArea, pBody, ptr - pBody, 0);
}
*ptr = '>';
}
++ptr;
- if ((ptr == NULL) || (ptr >= msgend)) break;
+ if ((ptr == NULL) || (ptr >= msgend))
+ break;
msgstart = ptr;
}
* Any of these tags cause everything including and following
* the tag to be removed.
*/
- if ( (!strncasecmp(ptr, "/HTML", 5)) ||(!strncasecmp(ptr, "/BODY", 5)) ) {
+ if ((!strncasecmp(ptr, "/HTML", 5)) || (!strncasecmp(ptr, "/BODY", 5))) {
--ptr;
msgend = ptr;
strcpy(ptr, "");
converted_msg = NewStrBufPlain(NULL, content_length + 8192);
/* Convert foreign character sets to UTF-8 if necessary. */
- if ( (strcasecmp(charset, "us-ascii"))
- && (strcasecmp(charset, "UTF-8"))
- && (strcasecmp(charset, ""))
- ) {
+ if ((strcasecmp(charset, "us-ascii"))
+ && (strcasecmp(charset, "UTF-8"))
+ && (strcasecmp(charset, ""))
+ ) {
syslog(LOG_DEBUG, "Converting %s to UTF-8", charset);
ctdl_iconv_open("UTF-8", charset, &ic);
- if (ic == (iconv_t)(-1) ) {
+ if (ic == (iconv_t) (-1)) {
syslog(LOG_WARNING, "%s:%d iconv_open() failed: %s", __FILE__, __LINE__, strerror(errno));
}
}
- if (Source == NULL) {
- if (ic != (iconv_t)(-1) ) {
+ if (Source == NULL) {
+ if (ic != (iconv_t) (-1)) {
ibuf = msg;
ibuflen = content_length;
- obuflen = content_length + (content_length / 2) ;
+ obuflen = content_length + (content_length / 2);
obuf = (char *) malloc(obuflen);
osav = obuf;
iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
msg = osav;
iconv_close(ic);
}
- }
- else {
- if (ic != (iconv_t)(-1) ) {
+ } else {
+ if (ic != (iconv_t) (-1)) {
StrBuf *Buf = NewStrBufPlain(NULL, StrLength(Source) + 8096);;
StrBufConvert(Source, Buf, &ic);
FreeStrBuf(&Buf);
iconv_close(ic);
- msg = (char*)ChrPtr(Source); /* TODO: get rid of this. */
+ msg = (char *) ChrPtr(Source); /* TODO: get rid of this. */
}
}
goto BAIL;
}
- if (BodyArea != NULL) { // Any attributes that were declared in the <body> tag
- StrBufAppendBufPlain(converted_msg, HKEY("<div "), 0); // are instead declared in this <div> tag
+ if (BodyArea != NULL) { // Any attributes that were declared in the <body> tag
+ StrBufAppendBufPlain(converted_msg, HKEY("<div "), 0); // are instead declared in this <div> tag
StrBufAppendBuf(converted_msg, BodyArea, 0);
StrBufAppendBufPlain(converted_msg, HKEY(">"), 0);
}
else if (!strncasecmp(ptr, "<a href=\"", 9)) {
++alevel;
++brak;
- if ( ((strchr(ptr, ':') < strchr(ptr, '/'))) && ((strchr(ptr, '/') < strchr(ptr, '>')))) {
+ if (((strchr(ptr, ':') < strchr(ptr, '/'))) && ((strchr(ptr, '/') < strchr(ptr, '>')))) {
/* open external links to new window */
StrBufAppendPrintf(converted_msg, new_window);
ptr = &ptr[8];
- }
- else if (
- (treat_as_wiki)
- && (strncasecmp(ptr, "<a href=\"wiki?", 14))
- && (strncasecmp(ptr, "<a href=\"dotgoto?", 17))
- && (strncasecmp(ptr, "<a href=\"knrooms?", 17))
- ) {
+ } else if ((treat_as_wiki)
+ && (strncasecmp(ptr, "<a href=\"wiki?", 14))
+ && (strncasecmp(ptr, "<a href=\"dotgoto?", 17))
+ && (strncasecmp(ptr, "<a href=\"knrooms?", 17))
+ ) {
content_length += 64;
StrBufAppendPrintf(converted_msg, "<a href=\"wiki?go=");
- //StrBufUrlescAppend(converted_msg, "FIXME ROOM NAME", NULL); // FIXME make compatible with webcit-ng
+ //StrBufUrlescAppend(converted_msg, "FIXME ROOM NAME", NULL); // FIXME make compatible with webcit-ng
StrBufAppendPrintf(converted_msg, "?page=");
ptr = &ptr[9];
- }
- else {
+ } else {
StrBufAppendPrintf(converted_msg, "<a href=\"");
ptr = &ptr[9];
}
/* Fixup <img src="cid:... ...> to fetch the mime part */
else if (!strncasecmp(ptr, "<img ", 5)) {
char *cid_start, *cid_end;
- char* tag_end=strchr(ptr,'>');
- char* src;
+ char *tag_end = strchr(ptr, '>');
+ char *src;
/* FIXME - handle this situation (maybe someone opened an <img cid...
* and then ended the message)
*/
if (!tag_end) {
syslog(LOG_DEBUG, "tag_end is null and ptr is:");
syslog(LOG_DEBUG, "%s", ptr);
- syslog(LOG_DEBUG, "Theoretical bytes remaining: %d", (int)(msgend - ptr));
+ syslog(LOG_DEBUG, "Theoretical bytes remaining: %d", (int) (msgend - ptr));
}
- src=strstr(ptr, "src=\"cid:");
+ src = strstr(ptr, "src=\"cid:");
++brak;
- if ( src
- && isspace(*(src-1))
- && tag_end
- && (cid_start=strchr(src,':'))
- && (cid_end=strchr(cid_start,'"'))
- && (cid_end < tag_end)
- ) {
+ if (src && isspace(*(src - 1))
+ && tag_end && (cid_start = strchr(src, ':'))
+ && (cid_end = strchr(cid_start, '"'))
+ && (cid_end < tag_end)
+ ) {
/* copy tag and attributes up to src="cid: */
StrBufAppendBufPlain(converted_msg, ptr, src - ptr, 0);
cid_start++;
StrBufAppendPrintf(converted_msg, " src=\"/ctdl/r/");
StrBufXMLEscAppend(converted_msg, NULL, roomname, strlen(roomname), 0);
syslog(LOG_DEBUG, "room name is '%s'", roomname);
- StrBufAppendPrintf(converted_msg, "/%ld/",msgnum);
+ StrBufAppendPrintf(converted_msg, "/%ld/", msgnum);
StrBufAppendBufPlain(converted_msg, cid_start, cid_end - cid_start, 0);
StrBufAppendBufPlain(converted_msg, "\"", -1, 0);
- ptr = cid_end+1;
+ ptr = cid_end + 1;
}
StrBufAppendBufPlain(converted_msg, ptr, tag_end - ptr, 0);
ptr = tag_end;
* Turn anything that looks like a URL into a real link, as long
* as it's not inside a tag already
*/
- else if ( (brak == 0) && (alevel == 0) &&
- ( (!strncasecmp(ptr, "http://", 7)) ||
- (!strncasecmp(ptr, "https://", 8)))) {
+ else if ((brak == 0) && (alevel == 0) && ((!strncasecmp(ptr, "http://", 7)) || (!strncasecmp(ptr, "https://", 8)))) {
/* Find the end of the link */
int strlenptr;
linklen = 0;
-
+
strlenptr = strlen(ptr);
- for (i=0; i<=strlenptr; ++i) {
- if ((ptr[i]==0)
- ||(isspace(ptr[i]))
- ||(ptr[i]==10)
- ||(ptr[i]==13)
- ||(ptr[i]=='(')
- ||(ptr[i]==')')
- ||(ptr[i]=='<')
- ||(ptr[i]=='>')
- ||(ptr[i]=='[')
- ||(ptr[i]==']')
- ||(ptr[i]=='"')
- ||(ptr[i]=='\'')
- ) linklen = i;
+ for (i = 0; i <= strlenptr; ++i) {
+ if ((ptr[i] == 0)
+ || (isspace(ptr[i]))
+ || (ptr[i] == 10)
+ || (ptr[i] == 13)
+ || (ptr[i] == '(')
+ || (ptr[i] == ')')
+ || (ptr[i] == '<')
+ || (ptr[i] == '>')
+ || (ptr[i] == '[')
+ || (ptr[i] == ']')
+ || (ptr[i] == '"')
+ || (ptr[i] == '\'')
+ )
+ linklen = i;
/* entity tag? */
if (ptr[i] == '&') {
- if ((ptr[i+2] ==';') ||
- (ptr[i+3] ==';') ||
- (ptr[i+5] ==';') ||
- (ptr[i+6] ==';') ||
- (ptr[i+7] ==';'))
+ if ((ptr[i + 2] == ';') ||
+ (ptr[i + 3] == ';') ||
+ (ptr[i + 5] == ';') || (ptr[i + 6] == ';') || (ptr[i + 7] == ';'))
linklen = i;
}
- if (linklen > 0) break;
+ if (linklen > 0)
+ break;
}
if (linklen > 0) {
char *ltreviewptr;
char *nbspreviewptr;
char linkedchar;
int len;
-
+
len = linklen;
linkedchar = ptr[len];
ptr[len] = '\0';
ptr += linklen;
StrBufAppendPrintf(converted_msg, "</a>");
}
- }
- else {
+ } else {
StrBufAppendBufPlain(converted_msg, ptr, 1, 0);
ptr++;
}
* so we don't turn things that look like URL's into
* links, when they're already links - or image sources.
*/
- if ((ptr > msg) && (*(ptr-1) == '<')) {
+ if ((ptr > msg) && (*(ptr - 1) == '<')) {
++brak;
}
- if ((ptr > msg) && (*(ptr-1) == '>')) {
+ if ((ptr > msg) && (*(ptr - 1) == '>')) {
--brak;
if ((scriptlevel == 0) && (script_start_pos >= 0)) {
StrBufCutRight(converted_msg, StrLength(converted_msg) - script_start_pos);
script_start_pos = (-1);
}
}
- if (!strncasecmp(ptr, "</a>", 3)) --alevel;
+ if (!strncasecmp(ptr, "</a>", 3))
+ --alevel;
}
}
if (BodyArea != NULL) {
- StrBufAppendBufPlain(converted_msg, HKEY("</div>"), 0); // Close the div where we declared attributes copied
- FreeStrBuf(&BodyArea); // from the original <body> tag
+ StrBufAppendBufPlain(converted_msg, HKEY("</div>"), 0); // Close the div where we declared attributes copied
+ FreeStrBuf(&BodyArea); // from the original <body> tag
}
- /* uncomment these two lines to override conversion */
- /* memcpy(converted_msg, msg, content_length); */
- /* output_length = content_length; */
+ /* uncomment these two lines to override conversion */
+ /* memcpy(converted_msg, msg, content_length); */
+ /* output_length = content_length; */
/* Output our big pile of markup */
StrBufAppendBuf(Target, converted_msg, 0);
-BAIL: /* A little trailing vertical whitespace... */
+ BAIL: /* A little trailing vertical whitespace... */
StrBufAppendPrintf(Target, "<br>\n");
/* Now give back the memory */
FreeStrBuf(&converted_msg);
- if ((msg != NULL) && (Source == NULL)) free(msg);
- return(Target);
+ if ((msg != NULL) && (Source == NULL))
+ free(msg);
+ return (Target);
}
* Look for URL's embedded in a buffer and make them linkable. We use a
* target window in order to keep the Citadel session in its own window.
*/
-void UrlizeText(StrBuf* Target, StrBuf *Source, StrBuf *WrkBuf)
+void UrlizeText(StrBuf * Target, StrBuf * Source, StrBuf * WrkBuf)
{
int len, UrlLen, Offset, TrailerLen;
const char *start, *end, *pos;
-
+
FlushStrBuf(Target);
start = NULL;
len = StrLength(Source);
FlushStrBuf(WrkBuf);
for (pos = ChrPtr(Source) + len; pos > start; --pos) {
- if ( (!isprint(*pos))
- || (isspace(*pos))
- || (*pos == '{')
- || (*pos == '}')
- || (*pos == '|')
- || (*pos == '\\')
- || (*pos == '^')
- || (*pos == '[')
- || (*pos == ']')
- || (*pos == '`')
- || (*pos == '<')
- || (*pos == '>')
- || (*pos == '(')
- || (*pos == ')')
- ) {
+ if ((!isprint(*pos))
+ || (isspace(*pos))
+ || (*pos == '{')
+ || (*pos == '}')
+ || (*pos == '|')
+ || (*pos == '\\')
+ || (*pos == '^')
+ || (*pos == '[')
+ || (*pos == ']')
+ || (*pos == '`')
+ || (*pos == '<')
+ || (*pos == '>')
+ || (*pos == '(')
+ || (*pos == ')')
+ ) {
end = pos;
}
}
-
+
UrlLen = end - start;
StrBufAppendBufPlain(WrkBuf, start, UrlLen, 0);
if (Offset != 0)
StrBufAppendBufPlain(Target, ChrPtr(Source), Offset, 0);
StrBufAppendPrintf(Target, "%ca href=%c%s%c TARGET=%c%s%c%c%s%c/A%c",
- LB, QU, ChrPtr(WrkBuf), QU, QU, TARGET,
- QU, RB, ChrPtr(WrkBuf), LB, RB);
+ LB, QU, ChrPtr(WrkBuf), QU, QU, TARGET, QU, RB, ChrPtr(WrkBuf), LB, RB);
TrailerLen = StrLength(Source) - (end - ChrPtr(Source));
if (TrailerLen > 0)
if (start == NULL)
return;
- for (pos = buf+len; pos > start; --pos) {
- if ( (!isprint(*pos))
- || (isspace(*pos))
- || (*pos == '{')
- || (*pos == '}')
- || (*pos == '|')
- || (*pos == '\\')
- || (*pos == '^')
- || (*pos == '[')
- || (*pos == ']')
- || (*pos == '`')
- || (*pos == '<')
- || (*pos == '>')
- || (*pos == '(')
- || (*pos == ')')
- ) {
+ for (pos = buf + len; pos > start; --pos) {
+ if ((!isprint(*pos))
+ || (isspace(*pos))
+ || (*pos == '{')
+ || (*pos == '}')
+ || (*pos == '|')
+ || (*pos == '\\')
+ || (*pos == '^')
+ || (*pos == '[')
+ || (*pos == ']')
+ || (*pos == '`')
+ || (*pos == '<')
+ || (*pos == '>')
+ || (*pos == '(')
+ || (*pos == ')')
+ ) {
end = pos;
}
}
-
+
UrlLen = end - start;
- if (UrlLen > sizeof(urlbuf)){
+ if (UrlLen > sizeof(urlbuf)) {
syslog(LOG_WARNING, "URL: content longer than buffer!");
return;
}
Offset = start - buf;
if ((Offset != 0) && (Offset < sizeof(outbuf)))
memcpy(outbuf, buf, Offset);
- outpos = snprintf(&outbuf[Offset], sizeof(outbuf) - Offset,
- "%ca href=%c%s%c TARGET=%c%s%c%c%s%c/A%c",
- LB, QU, urlbuf, QU, QU, TARGET, QU, RB, urlbuf, LB, RB);
+ outpos = snprintf(&outbuf[Offset], sizeof(outbuf) - Offset,
+ "%ca href=%c%s%c TARGET=%c%s%c%c%s%c/A%c", LB, QU, urlbuf, QU, QU, TARGET, QU, RB, urlbuf, LB, RB);
if (outpos >= sizeof(outbuf) - Offset) {
syslog(LOG_WARNING, "URL: content longer than buffer!");
return;
syslog(LOG_WARNING, "URL: content longer than buffer!");
return;
}
- memcpy (buf, outbuf, Offset + outpos + TrailerLen);
+ memcpy(buf, outbuf, Offset + outpos + TrailerLen);
*(buf + Offset + outpos + TrailerLen) = '\0';
}
{
if (is_https) {
return client_write_ssl(ch, buf, nbytes);
- }
- else {
+ } else {
return write(ch->sock, buf, nbytes);
}
}
{
if (is_https) {
return client_read_ssl(ch, buf, nbytes);
- }
- else {
+ } else {
int bytes_received = 0;
int bytes_this_block = 0;
while (bytes_received < nbytes) {
- bytes_this_block = read(ch->sock, &buf[bytes_received], nbytes-bytes_received);
+ bytes_this_block = read(ch->sock, &buf[bytes_received], nbytes - bytes_received);
if (bytes_this_block < 1) {
- return(-1);
+ return (-1);
}
bytes_received += bytes_this_block;
}
- return(nbytes);
+ return (nbytes);
}
}
int len = 0;
int c = 0;
- if (buf == NULL) return(-1);
+ if (buf == NULL)
+ return (-1);
while (len < maxbytes) {
c = client_read(ch, &buf[len], 1);
if (c <= 0) {
syslog(LOG_DEBUG, "Socket error or zero-length read");
- return(-1);
+ return (-1);
}
if (buf[len] == '\n') {
- if ( (len >0) && (buf[len-1] == '\r') ) {
+ if ((len > 0) && (buf[len - 1] == '\r')) {
--len;
}
buf[len] = 0;
- return(len);
+ return (len);
}
++len;
}
- return(len);
+ return (len);
}
/*
* printf() type function to send data to the web client.
*/
-void client_printf(struct client_handle *ch, const char *format,...)
+void client_printf(struct client_handle *ch, const char *format, ...)
{
va_list arg_ptr;
StrBuf *Buf = NewStrBuf();
StrBufVAppendPrintf(Buf, format, arg_ptr);
va_end(arg_ptr);
- client_write(ch, (char *)ChrPtr(Buf), StrLength(Buf));
+ client_write(ch, (char *) ChrPtr(Buf), StrLength(Buf));
FreeStrBuf(&Buf);
}
struct http_transaction h;
char *c, *d;
struct sockaddr_in sin;
- struct http_header *clh; // general purpose iterator variable
+ struct http_header *clh; // general purpose iterator variable
memset(&h, 0, sizeof h);
- while (len = client_readline(ch, buf, sizeof buf), (len > 0) ) {
+ while (len = client_readline(ch, buf, sizeof buf), (len > 0)) {
++lines_read;
- if (lines_read == 1) { // First line is method and URI.
- c = strchr(buf, ' '); // IGnore the HTTP-version.
+ if (lines_read == 1) { // First line is method and URI.
+ c = strchr(buf, ' '); // IGnore the HTTP-version.
if (c == NULL) {
h.method = strdup("NULL");
h.uri = strdup("/");
- }
- else {
+ } else {
*c = 0;
h.method = strdup(buf);
++c;
++c;
h.uri = strdup(d);
}
- }
- else { // Subsequent lines are headers.
- c = strchr(buf, ':'); // Header line folding is obsolete so we don't support it.
+ } else { // Subsequent lines are headers.
+ c = strchr(buf, ':'); // Header line folding is obsolete so we don't support it.
if (c != NULL) {
struct http_header *new_request_header = malloc(sizeof(struct http_header));
*c = 0;
char *hostheader = header_val(&h, "Host");
if (hostheader) {
strcat(h.site_prefix, hostheader);
- }
- else {
+ } else {
strcat(h.site_prefix, "127.0.0.1");
}
socklen_t llen = sizeof(sin);
- if (getsockname(ch->sock, (struct sockaddr *)&sin, &llen) >= 0) {
+ if (getsockname(ch->sock, (struct sockaddr *) &sin, &llen) >= 0) {
sprintf(&h.site_prefix[strlen(h.site_prefix)], ":%d", ntohs(sin.sin_port));
}
-
// Now try to read in the request body (if one is present)
if (len < 0) {
syslog(LOG_DEBUG, "Client disconnected");
- }
- else {
+ } else {
syslog(LOG_DEBUG, "< %s %s", h.method, h.uri);
// If there is a request body, read it now.
//write(2, HKEY("\033[0m\n"));
}
-
// Now pass control up to the next layer to perform the request.
perform_request(&h);
free(datestring);
}
- client_printf(ch, "Content-encoding: identity\r\n"); // change if we gzip/deflate
+ client_printf(ch, "Content-encoding: identity\r\n"); // change if we gzip/deflate
for (clh = h.response_headers; clh != NULL; clh = clh->next) {
#ifdef DEBUG_HTTP
syslog(LOG_DEBUG, "} %s: %s", clh->key, clh->val);
// free the transaction memory
while (h.request_headers) {
- if (h.request_headers->key) free(h.request_headers->key);
- if (h.request_headers->val) free(h.request_headers->val);
+ if (h.request_headers->key)
+ free(h.request_headers->key);
+ if (h.request_headers->val)
+ free(h.request_headers->val);
clh = h.request_headers->next;
free(h.request_headers);
h.request_headers = clh;
}
while (h.response_headers) {
- if (h.response_headers->key) free(h.response_headers->key);
- if (h.response_headers->val) free(h.response_headers->val);
+ if (h.response_headers->key)
+ free(h.response_headers->key);
+ if (h.response_headers->val)
+ free(h.response_headers->val);
clh = h.response_headers->next;
free(h.response_headers);
h.response_headers = clh;
}
- if (h.method) free(h.method);
- if (h.uri) free(h.uri);
- if (h.request_body) free(h.request_body);
- if (h.response_string) free(h.response_string);
- if (h.site_prefix) free(h.site_prefix);
+ if (h.method)
+ free(h.method);
+ if (h.uri)
+ free(h.uri);
+ if (h.request_body)
+ free(h.request_body);
+ if (h.response_string)
+ free(h.response_string);
+ if (h.site_prefix)
+ free(h.site_prefix);
}
*/
char *header_val(struct http_transaction *h, char *requested_header)
{
- struct http_header *clh; // general purpose iterator variable
+ struct http_header *clh; // general purpose iterator variable
for (clh = h->request_headers; clh != NULL; clh = clh->next) {
if (!strcasecmp(clh->key, requested_header)) {
- return(clh->val);
+ return (clh->val);
}
}
- return(NULL);
+ return (NULL);
}
char *pid_file = NULL;
/* Parse command line */
- while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfsS:Z:v:")) != EOF) switch(a) {
+ while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfsS:Z:v:")) != EOF)
+ switch (a) {
case 'u':
setuid(atoi(optarg));
break;
"[-d] [-Z] [-G i18ndumpfile] "
"[-u uid] [-h homedirectory] "
"[-D daemonizepid] [-v] "
- "[-g defaultlandingpage] [-B basesize] "
- "[-s] [-S cipher_suites]"
- "[remotehost [remoteport]]\n");
+ "[-g defaultlandingpage] [-B basesize] " "[-s] [-S cipher_suites]" "[remotehost [remoteport]]\n");
return 1;
- }
+ }
if (optind < argc) {
ctdlhost = argv[optind];
}
/* Start the logger */
- openlog("webcit", ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ), LOG_DAEMON);
+ openlog("webcit", (running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR)), LOG_DAEMON);
/* Tell 'em who's in da house */
syslog(LOG_NOTICE, "MAKE WEBCIT GREAT AGAIN!");
/* Ensure that we are linked to the correct version of libcitadel */
if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
- syslog(LOG_INFO, " You are running libcitadel version %d", libcitadel_version_number() );
- syslog(LOG_INFO, "WebCit was compiled against version %d", LIBCITADEL_VERSION_NUMBER );
- return(1);
+ syslog(LOG_INFO, " You are running libcitadel version %d", libcitadel_version_number());
+ syslog(LOG_INFO, "WebCit was compiled against version %d", LIBCITADEL_VERSION_NUMBER);
+ return (1);
}
/* Go into the background if we were asked to run as a daemon */
* if not found.
*
*/
-long locate_message_by_uid(struct ctdlsession *c, char *uid) {
+long locate_message_by_uid(struct ctdlsession *c, char *uid)
+{
char buf[1024];
ctdl_printf(c, "EUID %s", uid);
ctdl_readline(c, buf, sizeof buf);
if (buf[0] == '2') {
- return(atol(&buf[4]));
-
+ return (atol(&buf[4]));
+
}
/* Ugly hack to handle Mozilla Thunderbird, try stripping ".ics" if present */
- if (!strcasecmp(&uid[strlen(uid)-4], ".ics")) {
+ if (!strcasecmp(&uid[strlen(uid) - 4], ".ics")) {
safestrncpy(buf, uid, sizeof buf);
- buf[strlen(buf)-4] = 0;
+ buf[strlen(buf) - 4] = 0;
ctdl_printf(c, "EUID %s", buf);
ctdl_readline(c, buf, sizeof buf);
if (buf[0] == '2') {
- return(atol(&buf[4]));
-
+ return (atol(&buf[4]));
+
}
}
- return(-1);
+ return (-1);
}
char *etag = malloc(20);
if (etag != NULL) {
sprintf(etag, "%ld", msgnum);
- add_response_header(h, strdup("ETag"), etag); // http_transaction now owns this memory
+ add_response_header(h, strdup("ETag"), etag); // http_transaction now owns this memory
}
- while (ctdl_readline(c, buf, sizeof buf), strcmp(buf,"000"))
- {
+ while (ctdl_readline(c, buf, sizeof buf), strcmp(buf, "000")) {
if (IsEmptyStr(buf) && (in_body == 0)) {
in_body = 1;
Body = NewStrBuf();
- }
- else if (in_body == 0) {
+ } else if (in_body == 0) {
char *k = buf;
char *v = strchr(buf, ':');
if (v) {
*v = 0;
++v;
- striplt(v); // we now have a key (k) and a value (v)
- if (
- (!strcasecmp(k, "content-type")) // fields which can be passed from RFC822 to HTTP as-is
- || (!strcasecmp(k, "date"))
- ) {
+ striplt(v); // we now have a key (k) and a value (v)
+ if ((!strcasecmp(k, "content-type")) // fields which can be passed from RFC822 to HTTP as-is
+ || (!strcasecmp(k, "date"))
+ ) {
add_response_header(h, strdup(k), strdup(v));
- }
- else if (!strcasecmp(k, "content-transfer-encoding")) {
+ } else if (!strcasecmp(k, "content-transfer-encoding")) {
if (!strcasecmp(v, "base64")) {
encoding = 'b';
- }
- else if (!strcasecmp(v, "quoted-printable")) {
+ } else if (!strcasecmp(v, "quoted-printable")) {
encoding = 'q';
}
}
}
- }
- else if ( (in_body == 1) && (Body != NULL) ) {
+ } else if ((in_body == 1) && (Body != NULL)) {
StrBufAppendPrintf(Body, "%s\n", buf);
}
}
if (encoding == 'q') {
h->response_body = malloc(StrLength(Body));
if (h->response_body != NULL) {
- h->response_body_length = CtdlDecodeQuotedPrintable(h->response_body, (char *)ChrPtr(Body), StrLength(Body));
+ h->response_body_length =
+ CtdlDecodeQuotedPrintable(h->response_body, (char *) ChrPtr(Body), StrLength(Body));
}
FreeStrBuf(&Body);
- }
- else if (encoding == 'b') {
+ } else if (encoding == 'b') {
h->response_body = malloc(StrLength(Body));
if (h->response_body != NULL) {
h->response_body_length = CtdlDecodeBase64(h->response_body, ChrPtr(Body), StrLength(Body));
}
FreeStrBuf(&Body);
- }
- else {
+ } else {
h->response_body_length = StrLength(Body);
h->response_body = SmashStrBuf(&Body);
}
char new_euid[1024];
char response_string[1024];
- if ( (h->request_body == NULL) || (h->request_body_length < 1) ) {
- do_404(h); // Refuse to post a null message
+ if ((h->request_body == NULL) || (h->request_body_length < 1)) {
+ do_404(h); // Refuse to post a null message
return;
}
- ctdl_printf(c, "ENT0 1|||4|||1|"); // This protocol syntax will give us metadata back after upload
+ ctdl_printf(c, "ENT0 1|||4|||1|"); // This protocol syntax will give us metadata back after upload
ctdl_readline(c, buf, sizeof buf);
if (buf[0] != '8') {
h->response_code = 502;
/*
* Now handle the response from the Citadel server.
*/
-
+
n = 0;
new_msgnum = 0;
strcpy(new_euid, "");
strcpy(response_string, "");
- while (ctdl_readline(c, buf, sizeof buf), strcmp(buf, "000")) switch(n++) {
+ while (ctdl_readline(c, buf, sizeof buf), strcmp(buf, "000"))
+ switch (n++) {
case 0:
new_msgnum = atol(buf);
break;
break;
default:
break;
- }
+ }
/* Tell the client what happened. */
/* Citadel failed in some way? */
char *new_location = malloc(1024);
- if ( (new_msgnum < 0L) || (new_location == NULL) ) {
+ if ((new_msgnum < 0L) || (new_location == NULL)) {
h->response_code = 502;
h->response_string = strdup("bad gateway");
add_response_header(h, strdup("Content-type"), strdup("text/plain"));
char *etag = malloc(20);
if (etag != NULL) {
sprintf(etag, "%ld", new_msgnum);
- add_response_header(h, strdup("ETag"), etag); // http_transaction now owns this memory
+ add_response_header(h, strdup("ETag"), etag); // http_transaction now owns this memory
}
char esc_room[1024];
urlesc(esc_room, sizeof esc_room, c->room);
urlesc(esc_euid, sizeof esc_euid, new_euid);
snprintf(new_location, 1024, "/ctdl/r/%s/%s", esc_room, esc_euid);
- add_response_header(h, strdup("Location"), new_location); // http_transaction now owns this memory
+ add_response_header(h, strdup("Location"), new_location); // http_transaction now owns this memory
if (old_msgnum <= 0) {
- h->response_code = 201; // We created this item for the first time.
+ h->response_code = 201; // We created this item for the first time.
h->response_string = strdup("created");
- }
- else {
- h->response_code = 204; // We modified an existing item.
+ } else {
+ h->response_code = 204; // We modified an existing item.
h->response_string = strdup("no content");
-
+
/* The item we replaced has probably already been deleted by
* the Citadel server, but we'll do this anyway, just in case.
*/
ctdl_printf(c, "DLAT %ld|%s", msgnum, partnum);
ctdl_readline(c, buf, sizeof buf);
if (buf[0] != '6') {
- do_404(h); // too bad, so sad, go away
+ do_404(h); // too bad, so sad, go away
}
-
// Server response is going to be: 6XX length|-1|filename|content-type|charset
h->response_body_length = extract_int(&buf[4], 0);
extract_token(content_type, buf, 3, '|', sizeof content_type);
do {
thisblock = read(c->sock, &h->response_body[bytes], (h->response_body_length - bytes));
bytes += thisblock;
- syslog(LOG_DEBUG, "Bytes read: %d of %d", (int)bytes, (int)h->response_body_length);
+ syslog(LOG_DEBUG, "Bytes read: %d of %d", (int) bytes, (int) h->response_body_length);
} while ((bytes < h->response_body_length) && (thisblock >= 0));
- h->response_body[h->response_body_length] = 0; // null terminate it just for good measure
+ h->response_body[h->response_body_length] = 0; // null terminate it just for good measure
syslog(LOG_DEBUG, "content type: %s", content_type);
add_response_header(h, strdup("Content-type"), strdup(content_type));
h->response_code = 502;
h->response_string = strdup("bad gateway");
add_response_header(h, strdup("Content-type"), strdup("text/plain"));
- h->response_body = strdup(_("This program was unable to connect or stay connected to the Citadel server. Please report this problem to your system administrator."));
+ h->response_body =
+ strdup(_
+ ("This program was unable to connect or stay connected to the Citadel server. Please report this problem to your system administrator."));
h->response_body_length = strlen(h->response_body);
}
// This is implemented as a series of strncasecmp() calls rather than a
// lookup table in order to make the code more readable.
- if (IsEmptyStr(h->uri))
- { // Sanity check
+ if (IsEmptyStr(h->uri)) { // Sanity check
do_404(h);
return;
}
-
// Right about here is where we should try to handle anything that doesn't start
// with the /ctdl/ prefix.
// Root (/) ...
- if ( (!strcmp(h->uri, "/")) && (!strcasecmp(h->method, "GET")) )
- {
+ if ((!strcmp(h->uri, "/")) && (!strcasecmp(h->method, "GET"))) {
http_redirect(h, "/ctdl/s/index.html");
return;
}
-
// Legacy URI patterns (/readnew?gotoroom=xxx&start_reading_at=yyy) ...
// Direct room name (/my%20blog) ...
// Everything below this line is strictly REST URI patterns.
- if (strncasecmp(h->uri, HKEY("/ctdl/")))
- { // Reject non-REST
+ if (strncasecmp(h->uri, HKEY("/ctdl/"))) { // Reject non-REST
do_404(h);
return;
}
- if (!strncasecmp(h->uri, HKEY("/ctdl/s/")))
- { // Static content
+ if (!strncasecmp(h->uri, HKEY("/ctdl/s/"))) { // Static content
output_static(h);
return;
}
- if (h->uri[7] != '/')
- {
+ if (h->uri[7] != '/') {
do_404(h);
return;
}
-
// Anything below this line:
- // 1. Is in the format of /ctdl/?/*
- // 2. Requires a connection to a Citadel server.
+ // 1. Is in the format of /ctdl/?/*
+ // 2. Requires a connection to a Citadel server.
c = connect_to_citadel(h);
- if (c == NULL)
- {
+ if (c == NULL) {
do_502(h);
return;
}
-
// WebDAV methods like OPTIONS and PROPFIND *require* a logged-in session,
// even if the Citadel server allows anonymous access.
- if (IsEmptyStr(c->auth))
- {
- if ( (!strcasecmp(h->method, "OPTIONS"))
- || (!strcasecmp(h->method, "PROPFIND"))
- || (!strcasecmp(h->method, "REPORT"))
- || (!strcasecmp(h->method, "DELETE"))
- ) {
+ if (IsEmptyStr(c->auth)) {
+ if ((!strcasecmp(h->method, "OPTIONS"))
+ || (!strcasecmp(h->method, "PROPFIND"))
+ || (!strcasecmp(h->method, "REPORT"))
+ || (!strcasecmp(h->method, "DELETE"))
+ ) {
request_http_authenticate(h);
disconnect_from_citadel(c);
return;
}
}
-
// Break down the URI by path and send the request to the appropriate part of the program.
//
- switch(h->uri[6])
- {
- case 'a': // /ctdl/a/ == RESTful path to admin functions
- ctdl_a(h, c);
- break;
- case 'c': // /ctdl/c/ == misc Citadel server commands
- ctdl_c(h, c);
- break;
- case 'r': // /ctdl/r/ == RESTful path to rooms
- ctdl_r(h, c);
- break;
- case 'u': // /ctdl/u/ == RESTful path to users
- do_404(h);
- break;
- default:
- do_404(h);
+ switch (h->uri[6]) {
+ case 'a': // /ctdl/a/ == RESTful path to admin functions
+ ctdl_a(h, c);
+ break;
+ case 'c': // /ctdl/c/ == misc Citadel server commands
+ ctdl_c(h, c);
+ break;
+ case 'r': // /ctdl/r/ == RESTful path to rooms
+ ctdl_r(h, c);
+ break;
+ case 'u': // /ctdl/u/ == RESTful path to users
+ do_404(h);
+ break;
+ default:
+ do_404(h);
}
// Are we in an authenticated session? If so, set a cookie so we stay logged in.
- if (!IsEmptyStr(c->auth))
- {
+ if (!IsEmptyStr(c->auth)) {
char koekje[AUTH_MAX];
char *exp = http_datestring(time(NULL) + (86400 * 30));
snprintf(koekje, AUTH_MAX, "wcauth=%s; path=/ctdl/; Expires=%s", c->auth, exp);
free(exp);
add_response_header(h, strdup("Set-Cookie"), strdup(koekje));
}
-
// During development we are foiling the browser cache completely. In production we'll be more selective.
add_response_header(h, strdup("Cache-Control"), strdup("no-store, must-revalidate"));
add_response_header(h, strdup("Pragma"), strdup("no-cache"));
ctdl_printf(c, "MSGS %s", which_msgs);
ctdl_readline(c, buf, sizeof(buf));
- if (buf[0] == '1') do
- {
- if (num_msgs >= num_alloc)
- {
- if (num_alloc == 0)
- {
- num_alloc = 1024;
- msglist = malloc(num_alloc * sizeof(long));
- }
- else
- {
- num_alloc *= 2;
- msglist = realloc(msglist, num_alloc * sizeof(long));
+ if (buf[0] == '1')
+ do {
+ if (num_msgs >= num_alloc) {
+ if (num_alloc == 0) {
+ num_alloc = 1024;
+ msglist = malloc(num_alloc * sizeof(long));
+ } else {
+ num_alloc *= 2;
+ msglist = realloc(msglist, num_alloc * sizeof(long));
+ }
}
- }
- ctdl_readline(c, buf, sizeof(buf));
- msglist[num_msgs++] = atol(buf);
- } while (strcmp(buf, "000")); // this makes the last element a "0" terminator
+ ctdl_readline(c, buf, sizeof(buf));
+ msglist[num_msgs++] = atol(buf);
+ } while (strcmp(buf, "000")); // this makes the last element a "0" terminator
return msglist;
}
int match_etags(char *taglist, long msgnum)
{
int num_tags = num_tokens(taglist, ',');
- int i=0;
+ int i = 0;
char tag[1024];
- if (msgnum <= 0) // no msgnum? no match.
+ if (msgnum <= 0) // no msgnum? no match.
{
- return(0);
+ return (0);
}
- for (i=0; i<num_tags; ++i)
- {
+ for (i = 0; i < num_tags; ++i) {
extract_token(tag, taglist, i, ',', sizeof tag);
striplt(tag);
char *lq = (strchr(tag, '"'));
char *rq = (strrchr(tag, '"'));
- if (lq < rq) // has two double quotes
+ if (lq < rq) // has two double quotes
{
strcpy(rq, "");
strcpy(tag, ++lq);
}
striplt(tag);
- if (!strcmp(tag, "*")) // wildcard match
+ if (!strcmp(tag, "*")) // wildcard match
{
- return(1);
+ return (1);
}
long tagmsgnum = atol(tag);
- if ( (tagmsgnum > 0) && (tagmsgnum == msgnum) ) // match
+ if ((tagmsgnum > 0) && (tagmsgnum == msgnum)) // match
{
- return(1);
+ return (1);
}
}
- return(0); // no match
+ return (0); // no match
}
long *msglist = get_msglist(c, which);
JsonValue *j = NewJsonArray(HKEY("msgs"));
- if (msglist != NULL)
- {
- for (i=0; msglist[i]>0 ; ++i)
- {
- JsonArrayAppend(j, NewJsonNumber( HKEY("m"), msglist[i]));
+ if (msglist != NULL) {
+ for (i = 0; msglist[i] > 0; ++i) {
+ JsonArrayAppend(j, NewJsonNumber(HKEY("m"), msglist[i]));
}
free(msglist);
}
StrBuf *sj = NewStrBuf();
- SerializeJson(sj, j, 1); // '1' == free the source array
+ SerializeJson(sj, j, 1); // '1' == free the source array
add_response_header(h, strdup("Content-type"), strdup("application/json"));
h->response_code = 200;
extract_token(buf, h->uri, 4, '/', sizeof buf);
- if (!strncasecmp(buf, "msgs.", 5)) // Client is requesting a list of message numbers
+ if (!strncasecmp(buf, "msgs.", 5)) // Client is requesting a list of message numbers
{
json_msglist(h, c, &buf[5]);
return;
}
-
#if 0
- if (!strncasecmp(buf, "threads", 5)) // Client is requesting a threaded view (still kind of fuzzy here)
+ if (!strncasecmp(buf, "threads", 5)) // Client is requesting a threaded view (still kind of fuzzy here)
{
threaded_view(h, c, &buf[5]);
return;
}
- if (!strncasecmp(buf, "flat", 5)) // Client is requesting a flat view (still kind of fuzzy here)
+ if (!strncasecmp(buf, "flat", 5)) // Client is requesting a flat view (still kind of fuzzy here)
{
flat_view(h, c, &buf[5]);
return;
}
#endif
- if ( (c->room_default_view == VIEW_CALENDAR) // room types where objects are referenced by EUID
- || (c->room_default_view == VIEW_TASKS)
- || (c->room_default_view == VIEW_ADDRESSBOOK)
- ) {
+ if ((c->room_default_view == VIEW_CALENDAR) // room types where objects are referenced by EUID
+ || (c->room_default_view == VIEW_TASKS)
+ || (c->room_default_view == VIEW_ADDRESSBOOK)
+ ) {
safestrncpy(unescaped_euid, buf, sizeof unescaped_euid);
unescape_input(unescaped_euid);
msgnum = locate_message_by_uid(c, unescaped_euid);
- }
- else
- {
+ } else {
msgnum = atol(buf);
}
/*
* All methods except PUT require the message to already exist
*/
- if ( (msgnum <= 0) && (strcasecmp(h->method, "PUT")) )
- {
+ if ((msgnum <= 0) && (strcasecmp(h->method, "PUT"))) {
do_404(h);
}
* (1) a MIME part specifier, in which case the client wants to download that component within the message
* (2) a content-type, in which ase the client wants us to try to render it a certain way
*/
- if (num_tokens(h->uri, '/') == 6)
- {
+ if (num_tokens(h->uri, '/') == 6) {
extract_token(buf, h->uri, 5, '/', sizeof buf);
if (!IsEmptyStr(buf)) {
- if (!strcasecmp(buf, "json"))
- {
+ if (!strcasecmp(buf, "json")) {
json_render_one_message(h, c, msgnum);
- }
- else
- {
+ } else {
download_mime_component(h, c, msgnum, buf);
}
return;
* Ok, we want a full message, but first let's check for the if[-none]-match headers.
*/
char *if_match = header_val(h, "If-Match");
- if ( (if_match != NULL) && (!match_etags(if_match, msgnum)) )
- {
+ if ((if_match != NULL) && (!match_etags(if_match, msgnum))) {
do_412(h);
return;
}
char *if_none_match = header_val(h, "If-None-Match");
- if ( (if_none_match != NULL) && (match_etags(if_none_match, msgnum)) )
- {
+ if ((if_none_match != NULL) && (match_etags(if_none_match, msgnum))) {
do_412(h);
return;
}
* DOOOOOO ITTTTT!!!
*/
- if (!strcasecmp(h->method, "DELETE"))
- {
+ if (!strcasecmp(h->method, "DELETE")) {
dav_delete_message(h, c, msgnum);
- }
- else if (!strcasecmp(h->method, "GET"))
- {
+ } else if (!strcasecmp(h->method, "GET")) {
dav_get_message(h, c, msgnum);
- }
- else if (!strcasecmp(h->method, "PUT"))
- {
+ } else if (!strcasecmp(h->method, "PUT")) {
dav_put_message(h, c, unescaped_euid, msgnum);
- }
- else
- {
- do_404(h); // Got this far but the method made no sense? Bummer.
+ } else {
+ do_404(h); // Got this far but the method made no sense? Bummer.
}
}
*/
void report_the_room_itself(struct http_transaction *h, struct ctdlsession *c)
{
- if (c->room_default_view == VIEW_CALENDAR)
- {
- caldav_report(h, c); // CalDAV REPORTs ... fmgwac
+ if (c->room_default_view == VIEW_CALENDAR) {
+ caldav_report(h, c); // CalDAV REPORTs ... fmgwac
return;
}
- do_404(h); // future implementations like CardDAV will require code paths here
+ do_404(h); // future implementations like CardDAV will require code paths here
}
{
h->response_code = 200;
h->response_string = strdup("OK");
- if (c->room_default_view == VIEW_CALENDAR)
- {
+ if (c->room_default_view == VIEW_CALENDAR) {
add_response_header(h, strdup("DAV"), strdup("1, calendar-access")); // offer CalDAV
- }
- else if (c->room_default_view == VIEW_ADDRESSBOOK)
- {
+ } else if (c->room_default_view == VIEW_ADDRESSBOOK) {
add_response_header(h, strdup("DAV"), strdup("1, addressbook")); // offer CardDAV
- }
- else
- {
- add_response_header(h, strdup("DAV"), strdup("1")); // ordinary WebDAV for all other room types
+ } else {
+ add_response_header(h, strdup("DAV"), strdup("1")); // ordinary WebDAV for all other room types
}
add_response_header(h, strdup("Allow"), strdup("OPTIONS, PROPFIND, GET, PUT, REPORT, DELETE"));
}
StrBuf *Buf = NewStrBuf();
StrBufAppendPrintf(Buf, "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
- "<D:multistatus "
- "xmlns:D=\"DAV:\" "
- "xmlns:C=\"urn:ietf:params:xml:ns:caldav\""
- ">"
- );
+ "<D:multistatus " "xmlns:D=\"DAV:\" " "xmlns:C=\"urn:ietf:params:xml:ns:caldav\"" ">");
/* Transmit the collection resource */
StrBufAppendPrintf(Buf, "<D:response>");
StrBufXMLEscAppend(Buf, NULL, c->room, strlen(c->room), 0);
StrBufAppendPrintf(Buf, "</D:displayname>");
- StrBufAppendPrintf(Buf, "<D:owner />"); // empty owner ought to be legal; see rfc3744 section 5.1
+ StrBufAppendPrintf(Buf, "<D:owner />"); // empty owner ought to be legal; see rfc3744 section 5.1
StrBufAppendPrintf(Buf, "<D:resourcetype><D:collection />");
- switch(c->room_default_view)
- {
- case VIEW_CALENDAR:
- StrBufAppendPrintf(Buf, "<C:calendar />"); // RFC4791 section 4.2
- break;
+ switch (c->room_default_view) {
+ case VIEW_CALENDAR:
+ StrBufAppendPrintf(Buf, "<C:calendar />"); // RFC4791 section 4.2
+ break;
}
StrBufAppendPrintf(Buf, "</D:resourcetype>");
- int enumerate_by_euid = 0; // nonzero if messages will be retrieved by euid instead of msgnum
- switch(c->room_default_view)
- {
- case VIEW_CALENDAR: // RFC4791 section 5.2
- StrBufAppendPrintf(Buf, "<C:supported-calendar-component-set><C:comp name=\"VEVENT\"/></C:supported-calendar-component-set>");
- StrBufAppendPrintf(Buf, "<C:supported-calendar-data>");
- StrBufAppendPrintf(Buf, "<C:calendar-data content-type=\"text/calendar\" version=\"2.0\"/>");
- StrBufAppendPrintf(Buf, "</C:supported-calendar-data>");
- enumerate_by_euid = 1;
- break;
- case VIEW_TASKS: // RFC4791 section 5.2
- StrBufAppendPrintf(Buf, "<C:supported-calendar-component-set><C:comp name=\"VTODO\"/></C:supported-calendar-component-set>");
- StrBufAppendPrintf(Buf, "<C:supported-calendar-data>");
- StrBufAppendPrintf(Buf, "<C:calendar-data content-type=\"text/calendar\" version=\"2.0\"/>");
- StrBufAppendPrintf(Buf, "</C:supported-calendar-data>");
- enumerate_by_euid = 1;
- break;
- case VIEW_ADDRESSBOOK: // FIXME put some sort of CardDAV crapola here when we implement it
- enumerate_by_euid = 1;
- break;
- case VIEW_WIKI: // FIXME invent "WikiDAV" ?
- enumerate_by_euid = 1;
- break;
+ int enumerate_by_euid = 0; // nonzero if messages will be retrieved by euid instead of msgnum
+ switch (c->room_default_view) {
+ case VIEW_CALENDAR: // RFC4791 section 5.2
+ StrBufAppendPrintf(Buf,
+ "<C:supported-calendar-component-set><C:comp name=\"VEVENT\"/></C:supported-calendar-component-set>");
+ StrBufAppendPrintf(Buf, "<C:supported-calendar-data>");
+ StrBufAppendPrintf(Buf, "<C:calendar-data content-type=\"text/calendar\" version=\"2.0\"/>");
+ StrBufAppendPrintf(Buf, "</C:supported-calendar-data>");
+ enumerate_by_euid = 1;
+ break;
+ case VIEW_TASKS: // RFC4791 section 5.2
+ StrBufAppendPrintf(Buf,
+ "<C:supported-calendar-component-set><C:comp name=\"VTODO\"/></C:supported-calendar-component-set>");
+ StrBufAppendPrintf(Buf, "<C:supported-calendar-data>");
+ StrBufAppendPrintf(Buf, "<C:calendar-data content-type=\"text/calendar\" version=\"2.0\"/>");
+ StrBufAppendPrintf(Buf, "</C:supported-calendar-data>");
+ enumerate_by_euid = 1;
+ break;
+ case VIEW_ADDRESSBOOK: // FIXME put some sort of CardDAV crapola here when we implement it
+ enumerate_by_euid = 1;
+ break;
+ case VIEW_WIKI: // FIXME invent "WikiDAV" ?
+ enumerate_by_euid = 1;
+ break;
}
/* FIXME get the mtime
- StrBufAppendPrintf(Buf, "<D:getlastmodified>");
- escputs(datestring);
- StrBufAppendPrintf(Buf, "</D:getlastmodified>");
- */
+ StrBufAppendPrintf(Buf, "<D:getlastmodified>");
+ escputs(datestring);
+ StrBufAppendPrintf(Buf, "</D:getlastmodified>");
+ */
StrBufAppendPrintf(Buf, "</D:prop>");
StrBufAppendPrintf(Buf, "</D:propstat>");
// If a depth greater than zero was specified, transmit the collection listing
// BEGIN COLLECTION
- if (dav_depth > 0)
- {
+ if (dav_depth > 0) {
long *msglist = get_msglist(c, "ALL");
- if (msglist)
- {
+ if (msglist) {
int i;
- for (i=0; (msglist[i] > 0); ++i)
- {
- if ((i%10) == 0) syslog(LOG_DEBUG, "PROPFIND enumerated %d messages", i);
+ for (i = 0; (msglist[i] > 0); ++i) {
+ if ((i % 10) == 0)
+ syslog(LOG_DEBUG, "PROPFIND enumerated %d messages", i);
e = NULL; // EUID gets stored here
timestamp = 0;
char cbuf[1024];
ctdl_printf(c, "MSG0 %ld|3", msglist[i]);
ctdl_readline(c, cbuf, sizeof(cbuf));
- if (cbuf[0] == '1') while (ctdl_readline(c, cbuf, sizeof(cbuf)), strcmp(cbuf, "000"))
- {
- if ( (enumerate_by_euid) && (!strncasecmp(cbuf, "exti=", 5)) )
- {
- // e = strdup(&cbuf[5]);
- int elen = (2 * strlen(&cbuf[5]));
- e = malloc(elen);
- urlesc(e, elen, &cbuf[5]);
- }
- if (!strncasecmp(cbuf, "time=", 5))
- {
- timestamp = atol(&cbuf[5]);
+ if (cbuf[0] == '1')
+ while (ctdl_readline(c, cbuf, sizeof(cbuf)), strcmp(cbuf, "000")) {
+ if ((enumerate_by_euid) && (!strncasecmp(cbuf, "exti=", 5))) {
+ // e = strdup(&cbuf[5]);
+ int elen = (2 * strlen(&cbuf[5]));
+ e = malloc(elen);
+ urlesc(e, elen, &cbuf[5]);
+ }
+ if (!strncasecmp(cbuf, "time=", 5)) {
+ timestamp = atol(&cbuf[5]);
+ }
}
- }
- if (e == NULL)
- {
+ if (e == NULL) {
e = malloc(20);
sprintf(e, "%ld", msglist[i]);
}
StrBufAppendPrintf(Buf, "<D:status>HTTP/1.1 200 OK</D:status>");
StrBufAppendPrintf(Buf, "<D:prop>");
- switch(c->room_default_view)
- {
- case VIEW_CALENDAR:
- StrBufAppendPrintf(Buf, "<D:getcontenttype>text/calendar; component=vevent</D:getcontenttype>");
- break;
- case VIEW_TASKS:
- StrBufAppendPrintf(Buf, "<D:getcontenttype>text/calendar; component=vtodo</D:getcontenttype>");
- break;
- case VIEW_ADDRESSBOOK:
- StrBufAppendPrintf(Buf, "<D:getcontenttype>text/x-vcard</D:getcontenttype>");
- break;
+ switch (c->room_default_view) {
+ case VIEW_CALENDAR:
+ StrBufAppendPrintf(Buf,
+ "<D:getcontenttype>text/calendar; component=vevent</D:getcontenttype>");
+ break;
+ case VIEW_TASKS:
+ StrBufAppendPrintf(Buf,
+ "<D:getcontenttype>text/calendar; component=vtodo</D:getcontenttype>");
+ break;
+ case VIEW_ADDRESSBOOK:
+ StrBufAppendPrintf(Buf, "<D:getcontenttype>text/x-vcard</D:getcontenttype>");
+ break;
}
- if (timestamp > 0)
- {
+ if (timestamp > 0) {
char *datestring = http_datestring(timestamp);
- if (datestring)
- {
+ if (datestring) {
StrBufAppendPrintf(Buf, "<D:getlastmodified>");
StrBufXMLEscAppend(Buf, NULL, datestring, strlen(datestring), 0);
StrBufAppendPrintf(Buf, "</D:getlastmodified>");
free(datestring);
}
- if (enumerate_by_euid) // FIXME ajc 2017oct30 should this be inside the timestamp conditional?
+ if (enumerate_by_euid) // FIXME ajc 2017oct30 should this be inside the timestamp conditional?
{
StrBufAppendPrintf(Buf, "<D:getetag>\"%ld\"</D:getetag>", msglist[i]);
}
{
JsonValue *j = NewJsonObject(HKEY("gotoroom"));
- JsonObjectAppend(j, NewJsonPlainString( HKEY("name"), c->room, -1));
- JsonObjectAppend(j, NewJsonNumber( HKEY("current_view"), c->room_current_view ));
- JsonObjectAppend(j, NewJsonNumber( HKEY("default_view"), c->room_default_view ));
- JsonObjectAppend(j, NewJsonNumber( HKEY("new_messages"), c->new_messages ));
- JsonObjectAppend(j, NewJsonNumber( HKEY("total_messages"), c->total_messages ));
- JsonObjectAppend(j, NewJsonNumber( HKEY("last_seen"), c->last_seen ));
+ JsonObjectAppend(j, NewJsonPlainString(HKEY("name"), c->room, -1));
+ JsonObjectAppend(j, NewJsonNumber(HKEY("current_view"), c->room_current_view));
+ JsonObjectAppend(j, NewJsonNumber(HKEY("default_view"), c->room_default_view));
+ JsonObjectAppend(j, NewJsonNumber(HKEY("new_messages"), c->new_messages));
+ JsonObjectAppend(j, NewJsonNumber(HKEY("total_messages"), c->total_messages));
+ JsonObjectAppend(j, NewJsonNumber(HKEY("last_seen"), c->last_seen));
StrBuf *sj = NewStrBuf();
- SerializeJson(sj, j, 1); // '1' == free the source array
+ SerializeJson(sj, j, 1); // '1' == free the source array
add_response_header(h, strdup("Content-type"), strdup("application/json"));
h->response_code = 200;
{
// OPTIONS method on the room itself usually is a DAV client assessing what's here.
- if (!strcasecmp(h->method, "OPTIONS"))
- {
+ if (!strcasecmp(h->method, "OPTIONS")) {
options_the_room_itself(h, c);
return;
}
-
// PROPFIND method on the room itself could be looking for a directory
- if (!strcasecmp(h->method, "PROPFIND"))
- {
+ if (!strcasecmp(h->method, "PROPFIND")) {
propfind_the_room_itself(h, c);
return;
}
-
// REPORT method on the room itself is probably the dreaded CalDAV tower-of-crapola
- if (!strcasecmp(h->method, "REPORT"))
- {
+ if (!strcasecmp(h->method, "REPORT")) {
report_the_room_itself(h, c);
return;
}
-
// GET method on the room itself is an API call, possibly from our JavaScript front end
- if (!strcasecmp(h->method, "get"))
- {
+ if (!strcasecmp(h->method, "get")) {
get_the_room_itself(h, c);
return;
}
-
// we probably want a "go to this room" for interactive access
do_404(h);
}
ctdl_printf(c, "LKRA");
ctdl_readline(c, buf, sizeof(buf));
- if (buf[0] != '1')
- {
+ if (buf[0] != '1') {
do_502(h);
return;
}
JsonValue *j = NewJsonArray(HKEY("lkra"));
- while (ctdl_readline(c, buf, sizeof(buf)) , strcmp(buf, "000"))
- {
+ while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) {
// name|QRflags|QRfloor|QRorder|QRflags2|ra|current_view|default_view|mtime
JsonValue *jr = NewJsonObject(HKEY("room"));
extract_token(roomname, buf, 0, '|', sizeof roomname);
- JsonObjectAppend(jr, NewJsonPlainString( HKEY("name"), roomname, -1));
+ JsonObjectAppend(jr, NewJsonPlainString(HKEY("name"), roomname, -1));
int ra = extract_int(buf, 5);
- JsonObjectAppend(jr, NewJsonBool( HKEY("known"), (ra && UA_KNOWN)));
- JsonObjectAppend(jr, NewJsonBool( HKEY("hasnewmsgs"), (ra && UA_HASNEWMSGS)));
+ JsonObjectAppend(jr, NewJsonBool(HKEY("known"), (ra && UA_KNOWN)));
+ JsonObjectAppend(jr, NewJsonBool(HKEY("hasnewmsgs"), (ra && UA_HASNEWMSGS)));
int floor = extract_int(buf, 2);
- JsonObjectAppend(jr, NewJsonNumber( HKEY("floor"), floor));
+ JsonObjectAppend(jr, NewJsonNumber(HKEY("floor"), floor));
int rorder = extract_int(buf, 3);
- JsonObjectAppend(jr, NewJsonNumber( HKEY("rorder"), rorder));
+ JsonObjectAppend(jr, NewJsonNumber(HKEY("rorder"), rorder));
- JsonArrayAppend(j, jr); // add the room to the array
+ JsonArrayAppend(j, jr); // add the room to the array
}
StrBuf *sj = NewStrBuf();
- SerializeJson(sj, j, 1); // '1' == free the source array
+ SerializeJson(sj, j, 1); // '1' == free the source array
add_response_header(h, strdup("Content-type"), strdup("application/json"));
h->response_code = 200;
extract_token(requested_roomname, h->uri, 3, '/', sizeof requested_roomname);
unescape_input(requested_roomname);
- if (IsEmptyStr(requested_roomname)) // /ctdl/r/
+ if (IsEmptyStr(requested_roomname)) // /ctdl/r/
{
room_list(h, c);
return;
}
-
// If not, try to go there.
- if (strcasecmp(requested_roomname, c->room))
- {
+ if (strcasecmp(requested_roomname, c->room)) {
ctdl_printf(c, "GOTO %s", requested_roomname);
ctdl_readline(c, buf, sizeof(buf));
- if (buf[0] == '2')
- {
+ if (buf[0] == '2') {
// buf[3] will indicate whether any instant messages are waiting
extract_token(c->room, &buf[4], 0, '|', sizeof c->room);
- c->new_messages = extract_int(&buf[4], 1);
- c->total_messages = extract_int(&buf[4], 2);
- // 3 (int)info Info flag: set to nonzero if the user needs to read this room's info file
- // 4 (int)CCC->room.QRflags Various flags associated with this room.
- // 5 (long)CCC->room.QRhighest The highest message number present in this room
- c->last_seen = extract_long(&buf[4], 6); // The highest message number the user has read in this room
- // 7 (int)rmailflag Boolean flag: 1 if this is a Mail> room, 0 otherwise.
- // 8 (int)raideflag Nonzero if user is either Aide or a Room Aide in this room
- // 9 (int)newmailcount The number of new Mail messages the user has
- // 10 (int)CCC->room.QRfloor The floor number this room resides on
+ c->new_messages = extract_int(&buf[4], 1);
+ c->total_messages = extract_int(&buf[4], 2);
+ // 3 (int)info Info flag: set to nonzero if the user needs to read this room's info file
+ // 4 (int)CCC->room.QRflags Various flags associated with this room.
+ // 5 (long)CCC->room.QRhighest The highest message number present in this room
+ c->last_seen = extract_long(&buf[4], 6); // The highest message number the user has read in this room
+ // 7 (int)rmailflag Boolean flag: 1 if this is a Mail> room, 0 otherwise.
+ // 8 (int)raideflag Nonzero if user is either Aide or a Room Aide in this room
+ // 9 (int)newmailcount The number of new Mail messages the user has
+ // 10 (int)CCC->room.QRfloor The floor number this room resides on
c->room_current_view = extract_int(&buf[4], 11);
c->room_default_view = extract_int(&buf[4], 12);
- // 13 (int)is_trash Boolean flag: 1 if this is the user's Trash folder, 0 otherwise.
- // 14 (int)CCC->room.QRflags2 More flags associated with this room
- // 15 (long)CCC->room.QRmtime Timestamp of the last write activity in this room
- }
- else
- {
+ // 13 (int)is_trash Boolean flag: 1 if this is the user's Trash folder, 0 otherwise.
+ // 14 (int)CCC->room.QRflags2 More flags associated with this room
+ // 15 (long)CCC->room.QRmtime Timestamp of the last write activity in this room
+ } else {
do_404(h);
return;
}
}
-
// At this point our Citadel client session is "in" the specified room.
- if (num_tokens(h->uri, '/') == 4) // /ctdl/r/roomname
+ if (num_tokens(h->uri, '/') == 4) // /ctdl/r/roomname
{
the_room_itself(h, c);
return;
}
extract_token(buf, h->uri, 4, '/', sizeof buf);
- if (num_tokens(h->uri, '/') == 5)
- {
- if (IsEmptyStr(buf))
- {
- the_room_itself(h, c); // /ctdl/r/roomname/ ( same as /ctdl/r/roomname )
- }
- else
- {
- object_in_room(h, c); // /ctdl/r/roomname/object
+ if (num_tokens(h->uri, '/') == 5) {
+ if (IsEmptyStr(buf)) {
+ the_room_itself(h, c); // /ctdl/r/roomname/ ( same as /ctdl/r/roomname )
+ } else {
+ object_in_room(h, c); // /ctdl/r/roomname/object
}
return;
}
- if (num_tokens(h->uri, '/') == 6)
- {
- object_in_room(h, c); // /ctdl/r/roomname/object/ or possibly /ctdl/r/roomname/object/component
+ if (num_tokens(h->uri, '/') == 6) {
+ object_in_room(h, c); // /ctdl/r/roomname/object/ or possibly /ctdl/r/roomname/object/component
return;
}
-
// If we get to this point, the client specified a valid room but requested an action we don't know how to perform.
do_404(h);
}
{
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(SSLCritters[n]);
- }
- else {
+ } else {
pthread_mutex_unlock(SSLCritters[n]);
}
}
unsigned long e = RSA_F4;
FILE *fp;
- if (access(keyfilename, R_OK) == 0)
- {
+ if (access(keyfilename, R_OK) == 0) {
return;
}
syslog(LOG_INFO, "crypto: generating RSA key pair");
-
+
// generate rsa key
bne = BN_new();
- ret = BN_set_word(bne,e);
- if (ret != 1)
- {
+ ret = BN_set_word(bne, e);
+ if (ret != 1) {
goto free_all;
}
-
+
rsa = RSA_new();
ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
- if (ret != 1)
- {
+ if (ret != 1) {
goto free_all;
}
-
// write the key file
fp = fopen(keyfilename, "w");
- if (fp != NULL)
- {
+ if (fp != NULL) {
chmod(keyfilename, 0600);
if (PEM_write_RSAPrivateKey(fp, /* the file */
- rsa, /* the key */
- NULL, /* no enc */
- NULL, /* no passphr */
- 0, /* no passphr */
- NULL, /* no callbk */
- NULL /* no callbk */
- ) != 1)
- {
+ rsa, /* the key */
+ NULL, /* no enc */
+ NULL, /* no passphr */
+ 0, /* no passphr */
+ NULL, /* no callbk */
+ NULL /* no callbk */
+ ) != 1) {
syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
unlink(keyfilename);
}
fclose(fp);
}
-
- // 4. free
-free_all:
- RSA_free(rsa);
- BN_free(bne);
+ // 4. free
+ free_all:
+ RSA_free(rsa);
+ BN_free(bne);
}
void init_ssl(void)
{
const SSL_METHOD *ssl_method;
- RSA *rsa=NULL;
+ RSA *rsa = NULL;
X509_REQ *req = NULL;
X509 *cer = NULL;
EVP_PKEY *pk = NULL;
int rv = 0;
SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
- if (!SSLCritters)
- {
+ if (!SSLCritters) {
syslog(LOG_ERR, "citserver: can't allocate memory!!");
exit(1);
- }
- else
- {
+ } else {
int a;
- for (a = 0; a < CRYPTO_num_locks(); a++)
- {
+ for (a = 0; a < CRYPTO_num_locks(); a++) {
SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
- if (!SSLCritters[a])
- {
+ if (!SSLCritters[a]) {
syslog(LOG_INFO, "citserver: can't allocate memory!!");
exit(1);
}
SSL_library_init();
SSL_load_error_strings();
ssl_method = SSLv23_server_method();
- if (!(ssl_ctx = SSL_CTX_new(ssl_method)))
- {
+ if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
syslog(LOG_WARNING, "SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
return;
}
syslog(LOG_INFO, "Requesting cipher list: %s", ssl_cipher_list);
- if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list)))
- {
+ if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s", ERR_reason_error_string(ERR_get_error()));
return;
}
* in the next step. Therefore, if we have neither a CSR nor a certificate, generate
* the CSR in this step so that the next step may commence.
*/
- if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) )
- {
+ if ((access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0)) {
syslog(LOG_INFO, "Generating a certificate signing request.");
/*
* and we didn't just generate it now.
*/
fp = fopen(CTDL_KEY_PATH, "r");
- if (fp)
- {
+ if (fp) {
rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
fclose(fp);
}
- if (rsa)
- {
+ if (rsa) {
/* Create a public key from the private key */
- if (pk=EVP_PKEY_new(), pk != NULL)
- {
+ if (pk = EVP_PKEY_new(), pk != NULL) {
EVP_PKEY_assign_RSA(pk, rsa);
- if (req = X509_REQ_new(), req != NULL)
- {
+ if (req = X509_REQ_new(), req != NULL) {
const char *env;
/* Set the public key */
X509_REQ_set_pubkey(req, pk);
X509_REQ_set_version(req, 0L);
name = X509_REQ_get_subject_name(req);
- X509_NAME_add_entry_by_txt(
- name, "O", MBSTRING_ASC,
- (unsigned char*)"Citadel Server",
- -1, -1, 0
- );
- X509_NAME_add_entry_by_txt(
- name, "OU", MBSTRING_ASC,
- (unsigned char*)"Default Certificate PLEASE CHANGE",
- -1, -1, 0
- );
- X509_NAME_add_entry_by_txt(
- name, "CN",
- MBSTRING_ASC,
- (unsigned char*)"*",
- -1, -1, 0
- );
-
+ X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
+ (unsigned char *) "Citadel Server", -1, -1, 0);
+ X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC,
+ (unsigned char *) "Default Certificate PLEASE CHANGE",
+ -1, -1, 0);
+ X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *) "*", -1, -1, 0);
+
X509_REQ_set_subject_name(req, name);
/* Sign the CSR */
- if (!X509_REQ_sign(req, pk, EVP_md5()))
- {
+ if (!X509_REQ_sign(req, pk, EVP_md5())) {
syslog(LOG_WARNING, "X509_REQ_sign(): error");
- }
- else
- {
- /* Write it to disk. */
+ } else {
+ /* Write it to disk. */
fp = fopen(CTDL_CSR_PATH, "w");
- if (fp != NULL)
- {
+ if (fp != NULL) {
chmod(CTDL_CSR_PATH, 0600);
PEM_write_X509_REQ(fp, req);
fclose(fp);
- }
- else
- {
+ } else {
syslog(LOG_WARNING, "Cannot write key: %s", CTDL_CSR_PATH);
exit(1);
}
}
}
RSA_free(rsa);
- }
- else
- {
+ } else {
syslog(LOG_WARNING, "Unable to read private key.");
}
}
/*
* Generate a self-signed certificate if we don't have one.
*/
- if (access(CTDL_CER_PATH, R_OK) != 0)
- {
+ if (access(CTDL_CER_PATH, R_OK) != 0) {
syslog(LOG_INFO, "Generating a self-signed certificate.");
/* Same deal as before: always read the key from disk because
* it may or may not have just been generated.
*/
fp = fopen(CTDL_KEY_PATH, "r");
- if (fp)
- {
+ if (fp) {
rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
fclose(fp);
}
req = NULL;
cer = NULL;
pk = NULL;
- if (rsa)
- {
- if (pk=EVP_PKEY_new(), pk != NULL)
- {
+ if (rsa) {
+ if (pk = EVP_PKEY_new(), pk != NULL) {
EVP_PKEY_assign_RSA(pk, rsa);
}
fp = fopen(CTDL_CSR_PATH, "r");
- if (fp)
- {
+ if (fp) {
req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
fclose(fp);
}
- if (req)
- {
- if (cer = X509_new(), cer != NULL)
- {
+ if (req) {
+ if (cer = X509_new(), cer != NULL) {
ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
X509_gmtime_adj(X509_get_notBefore(cer), 0);
- X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
+ X509_gmtime_adj(X509_get_notAfter(cer), (long) 60 * 60 * 24 * SIGN_DAYS);
req_pkey = X509_REQ_get_pubkey(req);
X509_set_pubkey(cer, req_pkey);
EVP_PKEY_free(req_pkey);
-
+
/* Sign the cert */
- if (!X509_sign(cer, pk, EVP_md5()))
- {
+ if (!X509_sign(cer, pk, EVP_md5())) {
syslog(LOG_WARNING, "X509_sign(): error");
- }
- else
- { /* Write it to disk. */
+ } else { /* Write it to disk. */
fp = fopen(CTDL_CER_PATH, "w");
- if (fp != NULL)
- {
+ if (fp != NULL) {
chmod(CTDL_CER_PATH, 0600);
PEM_write_X509(fp, cer);
fclose(fp);
- }
- else
- {
+ } else {
syslog(LOG_WARNING, "Cannot write key: %s", CTDL_CER_PATH);
exit(1);
}
*/
SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
- if ( !SSL_CTX_check_private_key(ssl_ctx) )
- {
+ if (!SSL_CTX_check_private_key(ssl_ctx)) {
syslog(LOG_WARNING, "Cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
}
-
+
}
{
int retval, bits, alg_bits;
- if (!ssl_ctx)
- {
+ if (!ssl_ctx) {
return;
}
- if (!(ch->ssl_handle = SSL_new(ssl_ctx)))
- {
+ if (!(ch->ssl_handle = SSL_new(ssl_ctx))) {
syslog(LOG_WARNING, "SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
return;
}
- if (!(SSL_set_fd(ch->ssl_handle, ch->sock)))
- {
+ if (!(SSL_set_fd(ch->ssl_handle, ch->sock))) {
syslog(LOG_WARNING, "SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
SSL_free(ch->ssl_handle);
return;
}
retval = SSL_accept(ch->ssl_handle);
- if (retval < 1)
- {
+ if (retval < 1) {
long errval;
const char *ssl_error_reason = NULL;
errval = SSL_get_error(ch->ssl_handle, retval);
ssl_error_reason = ERR_reason_error_string(ERR_get_error());
- if (ssl_error_reason == NULL)
- {
+ if (ssl_error_reason == NULL) {
syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d %s", errval, retval, strerror(errval));
- }
- else
- {
+ } else {
syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
}
sleep(1);
retval = SSL_accept(ch->ssl_handle);
}
- if (retval < 1)
- {
+ if (retval < 1) {
long errval;
const char *ssl_error_reason = NULL;
errval = SSL_get_error(ch->ssl_handle, retval);
ssl_error_reason = ERR_reason_error_string(ERR_get_error());
- if (ssl_error_reason == NULL)
- {
+ if (ssl_error_reason == NULL) {
syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d (%s)", errval, retval, strerror(errval));
- }
- else
- {
+ } else {
syslog(LOG_WARNING, "SSL_accept failed: %s", ssl_error_reason);
}
SSL_free(ch->ssl_handle);
ch->ssl_handle = NULL;
return;
- }
- else
- {
+ } else {
syslog(LOG_INFO, "SSL_accept success");
}
bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(ch->ssl_handle), &alg_bits);
syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)",
- SSL_CIPHER_get_name(SSL_get_current_cipher(ch->ssl_handle)),
- SSL_CIPHER_get_version(SSL_get_current_cipher(ch->ssl_handle)),
- bits, alg_bits);
+ SSL_CIPHER_get_name(SSL_get_current_cipher(ch->ssl_handle)),
+ SSL_CIPHER_get_version(SSL_get_current_cipher(ch->ssl_handle)), bits, alg_bits);
syslog(LOG_INFO, "SSL started");
}
void endtls(struct client_handle *ch)
{
syslog(LOG_INFO, "Ending SSL/TLS");
- if (ch->ssl_handle != NULL)
- {
+ if (ch->ssl_handle != NULL) {
SSL_shutdown(ch->ssl_handle);
SSL_get_SSL_CTX(ch->ssl_handle);
SSL_free(ch->ssl_handle);
int nremain;
char junk[1];
- if (ch->ssl_handle == NULL) return(-1);
+ if (ch->ssl_handle == NULL)
+ return (-1);
nremain = nbytes;
- while (nremain > 0)
- {
- if (SSL_want_write(ch->ssl_handle))
- {
- if ((SSL_read(ch->ssl_handle, junk, 0)) < 1)
- {
+ while (nremain > 0) {
+ if (SSL_want_write(ch->ssl_handle)) {
+ if ((SSL_read(ch->ssl_handle, junk, 0)) < 1) {
syslog(LOG_WARNING, "SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
}
}
retval = SSL_write(ch->ssl_handle, &buf[nbytes - nremain], nremain);
- if (retval < 1)
- {
+ if (retval < 1) {
long errval;
errval = SSL_get_error(ch->ssl_handle, retval);
- if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE)
- {
+ if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
sleep(1);
continue;
}
syslog(LOG_WARNING, "SSL_write got error %ld, ret %d", errval, retval);
- if (retval == -1)
- {
+ if (retval == -1) {
syslog(LOG_WARNING, "errno is %d", errno);
endtls(ch);
}
int rlen = 0;
char junk[1];
- if (ch->ssl_handle == NULL) return(-1);
+ if (ch->ssl_handle == NULL)
+ return (-1);
- while (bytes_read < nbytes)
- {
- if (SSL_want_read(ch->ssl_handle))
- {
- if ((SSL_write(ch->ssl_handle, junk, 0)) < 1)
- {
+ while (bytes_read < nbytes) {
+ if (SSL_want_read(ch->ssl_handle)) {
+ if ((SSL_write(ch->ssl_handle, junk, 0)) < 1) {
syslog(LOG_WARNING, "SSL_write in client_read");
}
}
- rlen = SSL_read(ch->ssl_handle, &buf[bytes_read], nbytes-bytes_read);
- if (rlen < 1)
- {
+ rlen = SSL_read(ch->ssl_handle, &buf[bytes_read], nbytes - bytes_read);
+ if (rlen < 1) {
long errval;
errval = SSL_get_error(ch->ssl_handle, rlen);
- if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE)
- {
+ if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
sleep(1);
continue;
}
}
bytes_read += rlen;
}
- return(bytes_read);
+ return (bytes_read);
}
snprintf(filename, sizeof filename, "static/%s", &h->uri[8]);
- if (strstr(filename, "../")) { // 100% guaranteed attacker.
- do_404(h); // Die in a car fire.
+ if (strstr(filename, "../")) { // 100% guaranteed attacker.
+ do_404(h); // Die in a car fire.
return;
}
- FILE *fp = fopen(filename, "r"); // Try to open the requested file.
+ FILE *fp = fopen(filename, "r"); // Try to open the requested file.
if (fp == NULL) {
do_404(h);
return;
h->response_body = malloc(h->response_body_length);
if (h->response_body != NULL) {
fread(h->response_body, h->response_body_length, 1, fp);
- }
- else {
+ } else {
h->response_body_length = 0;
}
- fclose(fp); // Content is now in memory.
+ fclose(fp); // Content is now in memory.
h->response_code = 200;
h->response_string = strdup("OK");
int s, i, b;
int ip_version = 6;
-retry:
+ retry:
memset(&sin6, 0, sizeof(sin6));
memset(&sin4, 0, sizeof(sin4));
sin6.sin6_family = AF_INET6;
sin4.sin_family = AF_INET;
- if ( (ip_addr == NULL) /* any IPv6 */
- || (IsEmptyStr(ip_addr))
- || (!strcmp(ip_addr, "*"))
- ) {
+ if ((ip_addr == NULL) /* any IPv6 */
+ ||(IsEmptyStr(ip_addr))
+ || (!strcmp(ip_addr, "*"))
+ ) {
IsDefault = 1;
ip_version = 6;
sin6.sin6_addr = in6addr_any;
- }
- else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
- {
+ } else if (!strcmp(ip_addr, "0.0.0.0")) { /* any IPv4 */
ip_version = 4;
sin4.sin_addr.s_addr = INADDR_ANY;
- }
- else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
- {
+ } else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) { /* specific IPv4 */
ip_version = 4;
if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
syslog(LOG_WARNING, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
- return(-1);
+ return (-1);
}
- }
- else /* specific IPv6 */
- {
+ } else { /* specific IPv6 */
+
ip_version = 6;
if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
syslog(LOG_WARNING, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
- return(-1);
+ return (-1);
}
}
if (port_number == 0) {
syslog(LOG_WARNING, "Cannot start: no port number specified.\n");
- return(-1);
+ return (-1);
}
sin6.sin6_port = htons((u_short) port_number);
sin4.sin_port = htons((u_short) port_number);
p = getprotobyname("tcp");
- s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
+ s = socket(((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
if (s < 0) {
- if (IsDefault && (errno == EAFNOSUPPORT))
- {
+ if (IsDefault && (errno == EAFNOSUPPORT)) {
s = 0;
ip_addr = ipv4broadcast;
goto retry;
}
syslog(LOG_WARNING, "Can't create a listening socket: %s\n", strerror(errno));
- return(-1);
+ return (-1);
}
/* Set some socket options that make sense. */
i = 1;
if (ip_version == 6) {
b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
- }
- else {
+ } else {
b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
}
if (b < 0) {
syslog(LOG_ERR, "Can't bind: %s\n", strerror(errno));
close(s);
- return(-1);
+ return (-1);
}
if (listen(s, queue_len) < 0) {
syslog(LOG_ERR, "Can't listen: %s\n", strerror(errno));
close(s);
- return(-1);
+ return (-1);
}
return (s);
}
int actual_queue_len;
actual_queue_len = queue_len;
- if (actual_queue_len < 5) actual_queue_len = 5;
+ if (actual_queue_len < 5)
+ actual_queue_len = 5;
i = unlink(sockpath);
if ((i != 0) && (errno != ENOENT)) {
syslog(LOG_WARNING, "webcit: can't unlink %s: %s", sockpath, strerror(errno));
- return(-1);
+ return (-1);
}
memset(&addr, 0, sizeof(addr));
s = socket(AF_UNIX, SOCK_STREAM, 0);
if (s < 0) {
syslog(LOG_WARNING, "webcit: Can't create a unix domain socket: %s", strerror(errno));
- return(-1);
+ return (-1);
}
- if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
+ if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
syslog(LOG_WARNING, "webcit: Can't bind: %s", strerror(errno));
close(s);
- return(-1);
+ return (-1);
}
if (listen(s, actual_queue_len) < 0) {
syslog(LOG_WARNING, "webcit: Can't listen: %s", strerror(errno));
close(s);
- return(-1);
+ return (-1);
}
chmod(sockpath, 0777);
- return(s);
+ return (s);
}
/*
* Convert a text/plain message to text/html
*/
-StrBuf *text2html(const char *supplied_charset, int treat_as_wiki, char *roomname, long msgnum, StrBuf *Source)
+StrBuf *text2html(const char *supplied_charset, int treat_as_wiki, char *roomname, long msgnum, StrBuf * Source)
{
StrBuf *sj = NULL;
sj = NewStrBuf();
if (!sj) {
- return(sj);
+ return (sj);
}
StrBufAppendPrintf(sj, "<pre>");
- StrEscAppend(sj, Source, NULL, 0, 0); // FIXME - add code here to activate links
+ StrEscAppend(sj, Source, NULL, 0, 0); // FIXME - add code here to activate links
StrBufAppendPrintf(sj, "</pre>\n");
- return(sj);
+ return (sj);
}
/*
* Convert a text/x-citadel-variformat message to text/html
*/
-StrBuf *variformat2html(StrBuf *Source)
+StrBuf *variformat2html(StrBuf * Source)
{
StrBuf *Target = NULL;
Target = NewStrBuf();
if (!Target) {
- return(Target);
+ return (Target);
}
const char *ptr, *pte;
long len;
int intext = 0;
- if (StrLength(Source) > 0)
- do
- {
+ if (StrLength(Source) > 0)
+ do {
StrBufSipLine(Line, Source, &BufPtr);
bq = 0;
i = 0;
if (*ptr == '>') {
bq++;
}
- ptr ++;
+ ptr++;
i++;
}
}
* different colour. This code understands Citadel-style
* " >" quotes and will convert to <BLOCKQUOTE> tags.
*/
- if (i > 0) StrBufCutLeft(Line, i);
+ if (i > 0)
+ StrBufCutLeft(Line, i);
- for (i = bn; i < bq; i++)
+ for (i = bn; i < bq; i++)
StrBufAppendBufPlain(Target, HKEY("<blockquote>"), 0);
- for (i = bq; i < bn; i++)
+ for (i = bq; i < bn; i++)
StrBufAppendBufPlain(Target, HKEY("</blockquote>"), 0);
bn = bq;
StrBufAppendBufPlain(Target, HKEY("\n"), 0);
}
- while ((BufPtr != StrBufNOTNULL) &&
- (BufPtr != NULL));
+ while ((BufPtr != StrBufNOTNULL) && (BufPtr != NULL));
for (i = 0; i < bn; i++) {
StrBufAppendBufPlain(Target, HKEY("</blockquote>"), 0);
FreeStrBuf(&Line);
FreeStrBuf(&Line1);
FreeStrBuf(&Line2);
- return(Target);
+ return (Target);
}
-
-
buflen = strlen(buf);
- while ((buflen > 0) && (isspace(buf[buflen - 1]))){
+ while ((buflen > 0) && (isspace(buf[buflen - 1]))) {
buf[buflen - 1] = 0;
- buflen --;
+ buflen--;
}
- a = 0;
+ a = 0;
while (a < buflen) {
if (buf[a] == '+')
buf[a] = ' ';
if (a + 2 > buflen) {
buf[a] = '\0';
buflen = a;
- }
- else {
+ } else {
hex[0] = buf[a + 1];
hex[1] = buf[a + 2];
hex[2] = 0;
len = buflen - a - 2;
if (len > 0)
memmove(&buf[a + 1], &buf[a + 3], len);
-
- buflen -=2;
+
+ buflen -= 2;
}
}
a++;
* Supplied with a unix timestamp, generate a textual time/date stamp.
* Caller owns the returned memory.
*/
-char *http_datestring(time_t xtime) {
+char *http_datestring(time_t xtime)
+{
/* HTTP Months - do not translate - these are not for human consumption */
static char *httpdate_months[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
-
+
/* HTTP Weekdays - do not translate - these are not for human consumption */
static char *httpdate_weekdays[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
char offsign;
int n = 40;
char *buf = malloc(n);
- if (!buf) return(NULL);
+ if (!buf)
+ return (NULL);
localtime_r(&xtime, &t);
offset = t.tm_gmtoff;
if (offset > 0) {
offsign = '+';
- }
- else {
+ } else {
offset = 0L - offset;
offsign = '-';
}
- offset = ( (offset / 3600) * 100 ) + ( offset % 60 );
+ offset = ((offset / 3600) * 100) + (offset % 60);
snprintf(buf, n, "%s, %02d %s %04d %02d:%02d:%02d %c%04ld",
- httpdate_weekdays[t.tm_wday],
- t.tm_mday,
- httpdate_months[t.tm_mon],
- t.tm_year + 1900,
- t.tm_hour,
- t.tm_min,
- t.tm_sec,
- offsign, offset
- );
- return(buf);
+ httpdate_weekdays[t.tm_wday],
+ t.tm_mday, httpdate_months[t.tm_mon], t.tm_year + 1900, t.tm_hour, t.tm_min, t.tm_sec, offsign, offset);
+ return (buf);
}
*/
void spawn_another_worker_thread(int *pointer_to_master_socket)
{
- pthread_t th; // Thread descriptor
- pthread_attr_t attr; // Thread attributes
+ pthread_t th; // Thread descriptor
+ pthread_attr_t attr; // Thread attributes
/* set attributes for the new thread */
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 1048576); // Large stacks to prevent MIME parser crash on FreeBSD
/* now create the thread */
- if (pthread_create(&th, &attr, (void *(*)(void *)) worker_entry, (void *)pointer_to_master_socket) != 0) {
+ if (pthread_create(&th, &attr, (void *(*)(void *)) worker_entry, (void *) pointer_to_master_socket) != 0) {
syslog(LOG_WARNING, "Can't create thread: %s", strerror(errno));
- }
- else {
+ } else {
++num_threads_existing;
++num_threads_executing;
}
int fail_this_transaction = 0;
struct client_handle ch;
- while(1) {
+ while (1) {
/* Each worker thread blocks on accept() while waiting for something to do. */
memset(&ch, 0, sizeof ch);
- ch.sock = -1;
+ ch.sock = -1;
errno = EAGAIN;
do {
--num_threads_executing;
- syslog(LOG_DEBUG, "Additional memory allocated since startup: %d bytes", (int)(sbrk(0)-original_brk));
- syslog(LOG_DEBUG, "Thread 0x%x calling accept() on master socket %d", (unsigned int)pthread_self(), master_socket);
+ syslog(LOG_DEBUG, "Additional memory allocated since startup: %d bytes", (int) (sbrk(0) - original_brk));
+ syslog(LOG_DEBUG, "Thread 0x%x calling accept() on master socket %d", (unsigned int) pthread_self(),
+ master_socket);
ch.sock = accept(master_socket, NULL, 0);
if (ch.sock < 0) {
syslog(LOG_DEBUG, "accept() : %s", strerror(errno));
}
++num_threads_executing;
- syslog(LOG_DEBUG, "socket %d is awake , threads executing: %d , threads total: %d", ch.sock, num_threads_executing, num_threads_existing);
+ syslog(LOG_DEBUG, "socket %d is awake , threads executing: %d , threads total: %d", ch.sock,
+ num_threads_executing, num_threads_existing);
} while ((master_socket > 0) && (ch.sock < 0));
/* If all threads are executing, spawn more, up to the maximum */
- if ( (num_threads_executing >= num_threads_existing) && (num_threads_existing <= MAX_WORKER_THREADS) ) {
+ if ((num_threads_executing >= num_threads_existing) && (num_threads_existing <= MAX_WORKER_THREADS)) {
spawn_another_worker_thread(pointer_to_master_socket);
}
if (ch.ssl_handle == NULL) {
fail_this_transaction = 1;
}
- }
- else
- {
- int fdflags;
+ } else {
+ int fdflags;
fdflags = fcntl(ch.sock, F_GETFL);
if (fdflags < 0) {
syslog(LOG_WARNING, "unable to get server socket flags! %s", strerror(errno));
*/
int webserver(char *webserver_interface, int webserver_port, int webserver_protocol)
{
- int master_socket = (-1) ;
+ int master_socket = (-1);
original_brk = sbrk(0);
- switch(webserver_protocol) {
- case WEBSERVER_HTTP:
- syslog(LOG_DEBUG, "Starting HTTP server on %s:%d", webserver_interface, webserver_port);
- master_socket = webcit_tcp_server(webserver_interface, webserver_port, 10);
- break;
- case WEBSERVER_HTTPS:
- syslog(LOG_DEBUG, "Starting HTTPS server on %s:%d", webserver_interface, webserver_port);
- master_socket = webcit_tcp_server(webserver_interface, webserver_port, 10);
- init_ssl();
- is_https = 1;
- break;
- default:
- syslog(LOG_ERR, "unknown protocol");
- ;;
+ switch (webserver_protocol) {
+ case WEBSERVER_HTTP:
+ syslog(LOG_DEBUG, "Starting HTTP server on %s:%d", webserver_interface, webserver_port);
+ master_socket = webcit_tcp_server(webserver_interface, webserver_port, 10);
+ break;
+ case WEBSERVER_HTTPS:
+ syslog(LOG_DEBUG, "Starting HTTPS server on %s:%d", webserver_interface, webserver_port);
+ master_socket = webcit_tcp_server(webserver_interface, webserver_port, 10);
+ init_ssl();
+ is_https = 1;
+ break;
+ default:
+ syslog(LOG_ERR, "unknown protocol");
+ ;;
}
if (master_socket < 1) {
syslog(LOG_ERR, "Unable to bind the web server listening socket");
- return(1);
+ return (1);
}
syslog(LOG_INFO, "Listening on socket %d", master_socket);
signal(SIGPIPE, SIG_IGN);
- worker_entry(&master_socket); // this thread becomes a worker
- return(0);
+ worker_entry(&master_socket); // this thread becomes a worker
+ return (0);
}