The networker and RSS client each start up their own threads
[citadel.git] / citadel / modules / rssclient / serv_rssclient.c
1 /*
2  * $Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $
3  *
4  * Bring external RSS feeds into rooms.
5  *
6  */
7
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <stdio.h>
11
12 #if TIME_WITH_SYS_TIME
13 # include <sys/time.h>
14 # include <time.h>
15 #else
16 # if HAVE_SYS_TIME_H
17 #  include <sys/time.h>
18 # else
19 #  include <time.h>
20 # endif
21 #endif
22
23 #include <ctype.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <libcitadel.h>
29 #include "citadel.h"
30 #include "server.h"
31 #include "citserver.h"
32 #include "support.h"
33 #include "config.h"
34 #include "threads.h"
35 #include "room_ops.h"
36 #include "ctdl_module.h"
37 #include "clientsocket.h"
38 #include "msgbase.h"
39 #include "parsedate.h"
40 #include "database.h"
41 #include "citadel_dirs.h"
42 #include "md5.h"
43
44 #ifdef HAVE_EXPAT
45 #include <expat.h>
46
47
48 struct rssnetcfg {
49         struct rssnetcfg *next;
50         char url[256];
51         char *rooms;
52 };
53
54 struct rss_item {
55         char *chardata;
56         int chardata_len;
57         char *roomlist;
58         int done_parsing;
59         char *guid;
60         char *title;
61         char *link;
62         char *description;
63         time_t pubdate;
64         char channel_title[256];
65         int item_tag_nesting;
66 };
67
68 struct rssnetcfg *rnclist = NULL;
69
70
71 /*
72  * Commit a fetched and parsed RSS item to disk
73  */
74 void rss_save_item(struct rss_item *ri) {
75
76         struct MD5Context md5context;
77         u_char rawdigest[MD5_DIGEST_LEN];
78         int i;
79         char utmsgid[SIZ];
80         struct cdbdata *cdbut;
81         struct UseTable ut;
82         struct CtdlMessage *msg;
83         struct recptypes *recp = NULL;
84         int msglen = 0;
85
86         recp = (struct recptypes *) malloc(sizeof(struct recptypes));
87         if (recp == NULL) return;
88         memset(recp, 0, sizeof(struct recptypes));
89         recp->recp_room = strdup(ri->roomlist);
90         recp->num_room = num_tokens(ri->roomlist, '|');
91         recp->recptypes_magic = RECPTYPES_MAGIC;
92    
93         /* Construct a GUID to use in the S_USETABLE table.
94          * If one is not present in the item itself, make one up.
95          */
96         if (ri->guid != NULL) {
97                 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
98         }
99         else {
100                 MD5Init(&md5context);
101                 if (ri->title != NULL) {
102                         MD5Update(&md5context, ri->title, strlen(ri->title));
103                 }
104                 if (ri->link != NULL) {
105                         MD5Update(&md5context, ri->link, strlen(ri->link));
106                 }
107                 MD5Final(rawdigest, &md5context);
108                 for (i=0; i<MD5_DIGEST_LEN; i++) {
109                         sprintf(&utmsgid[i*2], "%02X", (unsigned char) (rawdigest[i] & 0xff));
110                         utmsgid[i*2] = tolower(utmsgid[i*2]);
111                         utmsgid[(i*2)+1] = tolower(utmsgid[(i*2)+1]);
112                 }
113                 strcat(utmsgid, "_rss2ctdl");
114         }
115
116         /* Find out if we've already seen this item */
117         cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
118         if (cdbut != NULL) {
119                 /* Item has already been seen */
120                 lprintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
121                 cdb_free(cdbut);
122
123                 /* rewrite the record anyway, to update the timestamp */
124                 strcpy(ut.ut_msgid, utmsgid);
125                 ut.ut_timestamp = time(NULL);
126                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
127         }
128         else {
129                 /* Item has not been seen, so save it. */
130
131                 if (ri->description == NULL) ri->description = strdup("");
132                 for (i=strlen(ri->description); i>=0; --i) {
133                         if (isspace(ri->description[i])) {
134                                 ri->description[i] = ' ';
135                         }
136                 }
137
138                 msg = malloc(sizeof(struct CtdlMessage));
139                 memset(msg, 0, sizeof(struct CtdlMessage));
140                 msg->cm_magic = CTDLMESSAGE_MAGIC;
141                 msg->cm_anon_type = MES_NORMAL;
142                 msg->cm_format_type = FMT_RFC822;
143                 msg->cm_fields['A'] = strdup("rss");
144                 msg->cm_fields['N'] = strdup(NODENAME);
145                 msg->cm_fields['U'] = strdup(ri->title);
146                 msg->cm_fields['T'] = malloc(64);
147                 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
148                 if (!IsEmptyStr(ri->channel_title)) {
149                         msg->cm_fields['O'] = strdup(ri->channel_title);
150                 }
151
152                 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
153                 msg->cm_fields['M'] = malloc(msglen);
154                 snprintf(msg->cm_fields['M'], msglen,
155                         "Content-type: text/html\r\n\r\n"
156                         "<html><body>\n"
157                         "%s<br><br>\n"
158                         "<a href=\"%s\">%s</a>\n"
159                         "</body></html>\n"
160                         ,
161                         ri->description,
162                         ri->link, ri->link
163                 );
164
165                 CtdlSubmitMsg(msg, recp, NULL);
166                 CtdlFreeMessage(msg);
167
168                 /* write the uidl to the use table so we don't store this item again */
169                 strcpy(ut.ut_msgid, utmsgid);
170                 ut.ut_timestamp = time(NULL);
171                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
172         }
173         free_recipients(recp);
174 }
175
176
177
178 /*
179  * Convert an RDF/RSS datestamp into a time_t
180  */
181 time_t rdf_parsedate(char *p)
182 {
183         struct tm tm;
184         time_t t = 0;
185
186         if (!p) return 0L;
187         if (strlen(p) < 10) return 0L;
188
189         memset(&tm, 0, sizeof tm);
190
191         /* YYYY-MM-DDTHH:MM format...
192          */
193         if ( (p[4] == '-') && (p[7] == '-') ) {
194                 tm.tm_year = atoi(&p[0]) - 1900;
195                 tm.tm_mon = atoi(&p[5]) - 1;
196                 tm.tm_mday = atoi(&p[8]);
197                 if ( (p[10] == 'T') && (p[13] == ':') ) {
198                         tm.tm_hour = atoi(&p[11]);
199                         tm.tm_min = atoi(&p[14]);
200                 }
201                 return mktime(&tm);
202         }
203
204         /* hmm... try RFC822 date stamp format */
205
206         t = parsedate(p);
207         if (t > 0) return(t);
208
209         /* yeesh.  ok, just return the current date and time. */
210         return(time(NULL));
211 }
212
213
214
215 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
216         struct rss_item *ri = (struct rss_item *) data;
217         char el[256];
218         char *sep = NULL;
219
220         /* Axe the namespace, we don't care about it */
221         safestrncpy(el, supplied_el, sizeof el);
222         while (sep = strchr(el, ':'), sep) {
223                 strcpy(el, ++sep);
224         }
225
226         if (!strcasecmp(el, "item")) {
227                 ++ri->item_tag_nesting;
228
229                 /* Initialize the feed item data structure */
230                 if (ri->guid != NULL) free(ri->guid);
231                 ri->guid = NULL;
232                 if (ri->title != NULL) free(ri->title);
233                 ri->title = NULL;
234                 if (ri->link != NULL) free(ri->link);
235                 ri->link = NULL;
236                 if (ri->description != NULL) free(ri->description);
237                 ri->description = NULL;
238
239                 /* Throw away any existing character data */
240                 if (ri->chardata_len > 0) {
241                         free(ri->chardata);
242                         ri->chardata = 0;
243                         ri->chardata_len = 0;
244                 }
245         }
246
247
248
249 }
250
251 void rss_xml_end(void *data, const char *supplied_el) {
252         struct rss_item *ri = (struct rss_item *) data;
253         char el[256];
254         char *sep = NULL;
255
256         /* Axe the namespace, we don't care about it */
257         safestrncpy(el, supplied_el, sizeof el);
258         while (sep = strchr(el, ':'), sep) {
259                 strcpy(el, ++sep);
260         }
261
262         if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
263                 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
264                 striplt(ri->channel_title);
265         }
266
267         if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
268                 if (ri->guid != NULL) free(ri->guid);
269                 striplt(ri->chardata);
270                 ri->guid = strdup(ri->chardata);
271         }
272
273         if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
274                 if (ri->title != NULL) free(ri->title);
275                 striplt(ri->chardata);
276                 ri->title = strdup(ri->chardata);
277         }
278
279         if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
280                 if (ri->link != NULL) free(ri->link);
281                 striplt(ri->chardata);
282                 ri->link = strdup(ri->chardata);
283         }
284
285         if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
286                 if (ri->description != NULL) free(ri->description);
287                 ri->description = strdup(ri->chardata);
288         }
289
290         if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
291                 striplt(ri->chardata);
292                 ri->pubdate = rdf_parsedate(ri->chardata);
293         }
294
295         if (!strcasecmp(el, "item")) {
296                 --ri->item_tag_nesting;
297                 rss_save_item(ri);
298         }
299
300         if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
301                 lprintf(CTDL_DEBUG, "End of feed detected.  Closing parser.\n");
302                 ri->done_parsing = 1;
303         }
304
305         if (ri->chardata_len > 0) {
306                 free(ri->chardata);
307                 ri->chardata = 0;
308                 ri->chardata_len = 0;
309         }
310
311 }
312
313
314 /*
315  * This callback stores up the data which appears in between tags.
316  */
317 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
318         struct rss_item *ri = (struct rss_item *) data;
319         int old_len;
320         int new_len;
321         char *new_buffer;
322
323         old_len = ri->chardata_len;
324         new_len = old_len + len;
325         new_buffer = realloc(ri->chardata, new_len + 1);
326         if (new_buffer != NULL) {
327                 memcpy(&new_buffer[old_len], s, len);
328                 new_buffer[new_len] = 0;
329                 ri->chardata = new_buffer;
330                 ri->chardata_len = new_len;
331         }
332 }
333
334
335
336 /* 
337  * Parse a URL into host, port number, and resource identifier.
338  */
339 int parse_url(char *url, char *hostname, int *port, char *identifier)
340 {
341         char protocol[1024];
342         char scratch[1024];
343         char *ptr = NULL;
344         char *nptr = NULL;
345         
346         strcpy(scratch, url);
347         ptr = (char *)strchr(scratch, ':');
348         if (!ptr) {
349                 return(1);      /* no protocol specified */
350         }
351
352         strcpy(ptr, "");
353         strcpy(protocol, scratch);
354         if (strcmp(protocol, "http")) {
355                 return(2);      /* not HTTP */
356         }
357
358         strcpy(scratch, url);
359         ptr = (char *) strstr(scratch, "//");
360         if (!ptr) {
361                 return(3);      /* no server specified */
362         }
363         ptr += 2;
364
365         strcpy(hostname, ptr);
366         nptr = (char *)strchr(ptr, ':');
367         if (!nptr) {
368                 *port = 80;     /* default */
369                 nptr = (char *)strchr(hostname, '/');
370         }
371         else {
372                 sscanf(nptr, ":%d", port);
373                 nptr = (char *)strchr(hostname, ':');
374         }
375
376         if (nptr) {
377                 *nptr = '\0';
378         }
379
380         nptr = (char *)strchr(ptr, '/');
381         
382         if (!nptr) {
383                 return(4);      /* no url specified */
384         }
385         
386         strcpy(identifier, nptr);
387         return(0);
388 }
389
390
391 /*
392  * Begin a feed parse
393  */
394 void rss_do_fetching(char *url, char *rooms) {
395         char buf[1024];
396         char rsshost[1024];
397         int rssport = 80;
398         char rssurl[1024];
399         struct rss_item ri;
400         XML_Parser xp;
401         int sock = (-1);
402         int got_bytes = (-1);
403         int redirect_count = 0;
404
405         /* Parse the URL */
406         if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
407                 lprintf(CTDL_ALERT, "Invalid URL: %s\n", url);
408         }
409
410         xp = XML_ParserCreateNS("UTF-8", ':');
411         if (!xp) {
412                 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
413                 return;
414         }
415
416         memset(&ri, 0, sizeof(struct rss_item));
417         ri.roomlist = rooms;
418         XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
419         XML_SetCharacterDataHandler(xp, rss_xml_chardata);
420         XML_SetUserData(xp, &ri);
421
422 retry:  lprintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
423         sprintf(buf, "%d", rssport);
424         sock = sock_connect(rsshost, buf, "tcp");
425         if (sock >= 0) {
426                 lprintf(CTDL_DEBUG, "Connected!\n");
427
428                 snprintf(buf, sizeof buf, "GET %s HTTP/1.0", rssurl);
429                 lprintf(CTDL_DEBUG, "<%s\n", buf);
430                 sock_puts(sock, buf);
431
432                 snprintf(buf, sizeof buf, "Host: %s", rsshost);
433                 lprintf(CTDL_DEBUG, "<%s\n", buf);
434                 sock_puts(sock, buf);
435
436                 snprintf(buf, sizeof buf, "User-Agent: %s", CITADEL);
437                 lprintf(CTDL_DEBUG, "<%s\n", buf);
438                 sock_puts(sock, buf);
439
440                 snprintf(buf, sizeof buf, "Accept: */*");
441                 lprintf(CTDL_DEBUG, "<%s\n", buf);
442                 sock_puts(sock, buf);
443
444                 sock_puts(sock, "");
445
446                 if (sock_getln(sock, buf, sizeof buf) >= 0) {
447                 lprintf(CTDL_DEBUG, ">%s\n", buf);
448                         remove_token(buf, 0, ' ');
449
450                         /* 200 OK */
451                         if (buf[0] == '2') {
452
453                                 while (got_bytes = sock_getln(sock, buf, sizeof buf),
454                                       (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
455                                         /* discard headers */
456                                 }
457
458                                 while (got_bytes = sock_read(sock, buf, sizeof buf, 0),
459                                       ((got_bytes>=0) && (ri.done_parsing == 0)) ) {
460                                         XML_Parse(xp, buf, got_bytes, 0);
461                                 }
462                                 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
463                         }
464
465                         /* 30X redirect */
466                         else if ( (!strncmp(buf, "30", 2)) && (redirect_count < 16) ) {
467                                 while (got_bytes = sock_getln(sock, buf, sizeof buf),
468                                       (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
469                                         if (!strncasecmp(buf, "Location:", 9)) {
470                                                 ++redirect_count;
471                                                 strcpy(buf, &buf[9]);
472                                                 striplt(buf);
473                                                 if (parse_url(buf, rsshost, &rssport, rssurl) == 0) {
474                                                         sock_close(sock);
475                                                         goto retry;
476                                                 }
477                                                 else {
478                                                         lprintf(CTDL_ALERT, "Invalid URL: %s\n", buf);
479                                                 }
480                                         }
481                                 }
482                         }
483
484                 }
485                 sock_close(sock);
486         }
487         else {
488                 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
489         }
490
491         XML_ParserFree(xp);
492
493         /* Free the feed item data structure */
494         if (ri.guid != NULL) free(ri.guid);
495         ri.guid = NULL;
496         if (ri.title != NULL) free(ri.title);
497         ri.title = NULL;
498         if (ri.link != NULL) free(ri.link);
499         ri.link = NULL;
500         if (ri.description != NULL) free(ri.description);
501         ri.description = NULL;
502         if (ri.chardata_len > 0) {
503                 free(ri.chardata);
504                 ri.chardata = 0;
505                 ri.chardata_len = 0;
506         }
507 }
508
509
510 /*
511  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
512  */
513 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
514 {
515         char filename[PATH_MAX];
516         char buf[1024];
517         char instr[32];
518         FILE *fp;
519         char feedurl[256];
520         struct rssnetcfg *rncptr = NULL;
521         struct rssnetcfg *use_this_rncptr = NULL;
522         int len = 0;
523         char *ptr = NULL;
524
525         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
526
527         /* Only do net processing for rooms that have netconfigs */
528         fp = fopen(filename, "r");
529         if (fp == NULL) {
530                 return;
531         }
532
533         while (fgets(buf, sizeof buf, fp) != NULL) {
534                 buf[strlen(buf)-1] = 0;
535
536                 extract_token(instr, buf, 0, '|', sizeof instr);
537                 if (!strcasecmp(instr, "rssclient")) {
538
539                         use_this_rncptr = NULL;
540
541                         extract_token(feedurl, buf, 1, '|', sizeof feedurl);
542
543                         /* If any other rooms have requested the same feed, then we will just add this
544                          * room to the target list for that client request.
545                          */
546                         for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
547                                 if (!strcmp(rncptr->url, feedurl)) {
548                                         use_this_rncptr = rncptr;
549                                 }
550                         }
551
552                         /* Otherwise create a new client request */
553                         if (use_this_rncptr == NULL) {
554                                 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
555                                 if (rncptr != NULL) {
556                                         rncptr->next = rnclist;
557                                         safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
558                                         rncptr->rooms = NULL;
559                                         rnclist = rncptr;
560                                         use_this_rncptr = rncptr;
561                                 }
562                         }
563
564                         /* Add the room name to the request */
565                         if (use_this_rncptr != NULL) {
566                                 if (use_this_rncptr->rooms == NULL) {
567                                         rncptr->rooms = strdup(qrbuf->QRname);
568                                 }
569                                 else {
570                                         len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
571                                         ptr = realloc(use_this_rncptr->rooms, len);
572                                         if (ptr != NULL) {
573                                                 strcat(ptr, "|");
574                                                 strcat(ptr, qrbuf->QRname);
575                                                 use_this_rncptr->rooms = ptr;
576                                         }
577                                 }
578                         }
579                 }
580
581         }
582
583         fclose(fp);
584
585 }
586
587 /*
588  * Scan for rooms that have RSS client requests configured
589  */
590 void *rssclient_scan(void *args) {
591         static time_t last_run = 0L;
592         static int doing_rssclient = 0;
593         struct rssnetcfg *rptr = NULL;
594         struct CitContext rssclientCC;
595
596         /* Give this thread its own private CitContext */
597         memset(&rssclientCC, 0, sizeof(struct CitContext));
598         rssclientCC.internal_pgm = 1;
599         rssclientCC.cs_pid = 0;
600         pthread_setspecific(MyConKey, (void *)&rssclientCC );
601
602         CtdlThreadAllocTSD();
603
604         /*
605          * This is a simple concurrency check to make sure only one rssclient run
606          * is done at a time.  We could do this with a mutex, but since we
607          * don't really require extremely fine granularity here, we'll do it
608          * with a static variable instead.
609          */
610         if (doing_rssclient) return NULL;
611         doing_rssclient = 1;
612
613         lprintf(CTDL_DEBUG, "rssclient started\n");
614         ForEachRoom(rssclient_scan_room, NULL);
615
616         while (rnclist != NULL) {
617                 rss_do_fetching(rnclist->url, rnclist->rooms);
618                 rptr = rnclist;
619                 rnclist = rnclist->next;
620                 if (rptr->rooms != NULL) free(rptr->rooms);
621                 free(rptr);
622         }
623
624         lprintf(CTDL_DEBUG, "rssclient ended\n");
625         last_run = time(NULL);
626         doing_rssclient = 0;
627         CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
628         return NULL;
629 }
630
631
632 #endif  /* HAVE_EXPAT */
633
634 CTDL_MODULE_INIT(rssclient)
635 {
636         if (threading)
637         {
638 #ifdef HAVE_EXPAT
639                 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
640 #else
641                 lprintf(CTDL_INFO, "This server is missing the Expat XML parser.  RSS client will be disabled.\n");
642 #endif
643         }
644         
645         /* return our Subversion id for the Log */
646         return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";
647 }