File: extnotify_main.c

package info (click to toggle)
citadel 7.83-2squeeze2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 4,572 kB
  • ctags: 3,756
  • sloc: ansic: 54,870; sh: 4,298; yacc: 660; makefile: 450; xml: 40
file content (418 lines) | stat: -rw-r--r-- 11,323 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*
 * extnotify_main.c
 * Mathew McBride
 *
 * This module implements an external pager hook for when notifcation
 * of a new email is wanted.
 *
 * Based on bits of serv_funambol
 * Contact: <matt@mcbridematt.dhs.org> / <matt@comalies>
 *
 * Copyright (c) 2008-2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "sysdep.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <pwd.h>
#include <errno.h>
#include <sys/types.h>

#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
#  include <sys/time.h>
# else
#  include <time.h>
# endif
#endif

#include <sys/wait.h>
#include <string.h>
#include <limits.h>
#include <sys/socket.h>
#include <libcitadel.h>
#include "citadel.h"
#include "server.h"
#include "citserver.h"
#include "support.h"
#include "config.h"
#include "control.h"
#include "user_ops.h"
#include "database.h"
#include "msgbase.h"
#include "internet_addressing.h"
#include "domain.h"
#include "clientsocket.h"
#include "extnotify.h"

#include "ctdl_module.h"



void ExtNotify_PutErrorMessage(NotifyContext *Ctx, StrBuf *ErrMsg)
{
	int nNext;
	if (Ctx->NotifyErrors == NULL)
		Ctx->NotifyErrors = NewHash(1, Flathash);

	nNext = GetCount(Ctx->NotifyErrors) + 1;
	Put(Ctx->NotifyErrors, 
	    (char*)&nNext, 
	    sizeof(int), 
	    ErrMsg, 
	    HFreeStrBuf);
}




StrBuf* GetNHBuf(int i, int allocit, StrBuf **NotifyHostList)
{
	if ((NotifyHostList[i] == NULL) && (allocit != 0))
		NotifyHostList[i] = NewStrBuf();
	return NotifyHostList[i];
}


StrBuf** GetNotifyHosts(void)
{
	char NotifyHostsBuf[SIZ];
	StrBuf *Host;
	StrBuf *File;
	StrBuf *NotifyBuf;
	int notify;
	const char *pchs, *pche;
	const char *NextHost = NULL;
	StrBuf **NotifyHostList;
	int num_notify;

	/* See if we have any Notification Hosts configured */
	num_notify = get_hosts(NotifyHostsBuf, "notify");
	if (num_notify < 1)
		return(NULL);

	NotifyHostList = malloc(sizeof(StrBuf*) * 2 * (num_notify + 1));
	memset(NotifyHostList, 0, sizeof(StrBuf*) * 2 * (num_notify + 1));
	
	NotifyBuf = NewStrBufPlain(NotifyHostsBuf, -1);
	/* get all configured notifiers's */
        for (notify=0; notify<num_notify; notify++) {
		
		Host = GetNHBuf(notify * 2, 1, NotifyHostList);
		StrBufExtract_NextToken(Host, NotifyBuf, &NextHost, '|');
		pchs = ChrPtr(Host);
		pche = strchr(pchs, ':');
		if (pche == NULL) {
			CtdlLogPrintf(CTDL_ERR, 
				      __FILE__": filename not found in %s.\n", 
				      pchs);
			continue;
		}
		File = GetNHBuf(notify * 2 + 1, 1, NotifyHostList);
		StrBufPlain(File, pchs, pche - pchs);
		StrBufCutLeft(Host, pche - pchs + 1);
	}
	return NotifyHostList;
}


/*! \brief Create the notify message queue. We use the exact same room
 *			as the Funambol module.
 *
 *	Run at server startup, creates FNBL_QUEUE_ROOM if it doesn't exist
 *	and sets as system room.
 */
void create_extnotify_queue(void) {
	struct ctdlroom qrbuf;
    
	CtdlCreateRoom(FNBL_QUEUE_ROOM, 3, "", 0, 1, 0, VIEW_MAILBOX);
    
	/*
	 * Make sure it's set to be a "system room" so it doesn't show up
	 * in the <K>nown rooms list for Aides.
	 */
	if (CtdlGetRoomLock(&qrbuf, FNBL_QUEUE_ROOM) == 0) {
		qrbuf.QRflags2 |= QR2_SYSTEM;
		CtdlPutRoomLock(&qrbuf);
	}
}
/*!
 * \brief Run through the pager room queue
 */
void do_extnotify_queue(void) 
{

	NotifyContext Ctx;
	static int doing_queue = 0;
	int i = 0;
	CitContext extnotifyCC;
    
	/*
	 * This is a simple concurrency check to make sure only one queue run
	 * is done at a time.  We could do this with a mutex, but since we
	 * don't really require extremely fine granularity here, we'll do it
	 * with a static variable instead.
	 */
	if (doing_queue) return;
	doing_queue = 1;

	/* Give this thread its own private CitContext */
	CtdlFillSystemContext(&extnotifyCC, "extnotify");
	citthread_setspecific(MyConKey, (void *)&extnotifyCC );
    
	/*
	 * Go ahead and run the queue
	 */
	CtdlLogPrintf(CTDL_DEBUG, "serv_extnotify: processing notify queue\n");
    
	memset(&Ctx, 0, sizeof(NotifyContext));
	Ctx.NotifyHostList = GetNotifyHosts();
	if (CtdlGetRoom(&CC->room, FNBL_QUEUE_ROOM) != 0) {
		CtdlLogPrintf(CTDL_ERR, "Cannot find room <%s>\n", FNBL_QUEUE_ROOM);
		CtdlClearSystemContext();
		return;
	}
	CtdlForEachMessage(MSGS_ALL, 0L, NULL,
			   SPOOLMIME, NULL, process_notify, &Ctx);

	while ((Ctx.NotifyHostList != NULL) && (Ctx.NotifyHostList[i] != NULL))
		FreeStrBuf(&Ctx.NotifyHostList[i]);

	if (Ctx.NotifyErrors != NULL)
	{
		long len;
		const char *Key;
		HashPos *It;
		void *vErr;
		StrBuf *ErrMsg;

		It = GetNewHashPos(Ctx.NotifyErrors, 0);
		while (GetNextHashPos(Ctx.NotifyErrors, It, &len, &Key, &vErr) && 
		       (vErr != NULL)) {
			ErrMsg = (StrBuf*) vErr;
			quickie_message("Citadel", NULL, NULL, AIDEROOM, ChrPtr(ErrMsg), FMT_FIXED, 
					"Failed to notify external service about inbound mail");
		}

		DeleteHashPos(&It);
		DeleteHash(&Ctx.NotifyErrors);
	}

	CtdlLogPrintf(CTDL_DEBUG, "serv_extnotify: queue run completed\n");
	doing_queue = 0;
	CtdlClearSystemContext();
}
/*!
 * \brief Process messages in the external notification queue
 */
void process_notify(long NotifyMsgnum, void *usrdata) 
{
	NotifyContext *Ctx;
	long msgnum = 0;
	long todelete[1];
	int fnblAllowed;
	int extPagerAllowedHttp;
	int extPagerAllowedSystem;
	char *pch;
	long configMsgNum;
	char configMsg[SIZ];
	struct CtdlMessage *msg;

	Ctx = (NotifyContext*) usrdata;

	msg = CtdlFetchMessage(NotifyMsgnum, 1);
	if ( msg->cm_fields['W'] == NULL) {
		goto nuke;
	}
    
	configMsgNum = extNotify_getConfigMessage(msg->cm_fields['W']);
    
	extNotify_getPrefs(configMsgNum, &configMsg[0]);
	
	/* Check to see if:
	 * 1. The user has configured paging / They have and disabled it
	 * AND 2. There is an external pager program
	 * 3. A Funambol server has been entered
	 *
	 */
	if ((configMsgNum == -1) || 
	    ((strncasecmp(configMsg, "none", 4) == 0) &&
	     IsEmptyStr(config.c_pager_program) && 
	     IsEmptyStr(config.c_funambol_host))) {
		CtdlLogPrintf(CTDL_DEBUG, "No external notifiers configured on system/user");
		goto nuke;
	}

	// Can Funambol take the message?
	pch = strchr(configMsg, '\n');
	if (*pch == '\n')
	    *pch = '\0';
	fnblAllowed = strncasecmp(configMsg, HKEY(FUNAMBOL_CONFIG_TEXT));
	extPagerAllowedHttp = strncasecmp(configMsg, HKEY(PAGER_CONFIG_HTTP)); 
	extPagerAllowedSystem = strncasecmp(configMsg, HKEY(PAGER_CONFIG_SYSTEM));
	pch = strstr(msg->cm_fields['M'], "msgid|");
	if (pch != NULL) 
		msgnum = atol(pch + sizeof("msgid"));
	if (fnblAllowed == 0) {
		char remoteurl[SIZ];
		snprintf(remoteurl, SIZ, "http://%s@%s:%d/%s",
			 config.c_funambol_auth,
			 config.c_funambol_host,
			 config.c_funambol_port,
			 FUNAMBOL_WS);
		notify_http_server(remoteurl, 
				   file_funambol_msg,
				   strlen(file_funambol_msg),/*GNA*/
				   msg->cm_fields['W'], 
				   msg->cm_fields['I'],
				   msgnum, 
				   Ctx);
	} else if (extPagerAllowedHttp == 0) {
		int i = 0;
		StrBuf *URL;
		char URLBuf[SIZ];
		StrBuf *File;
		StrBuf *FileBuf = NewStrBuf();
		
		while(1)
		{

			URL = GetNHBuf(i*2, 0, Ctx->NotifyHostList);
			if (URL==NULL) break;
			File = GetNHBuf(i*2 + 1, 0, Ctx->NotifyHostList);
			if (File==NULL) break;

			if (StrLength(File)>0)
				StrBufPrintf(FileBuf, "%s/%s", 
					     ctdl_shared_dir, 
					     ChrPtr(File));
			else
				FlushStrBuf(FileBuf);
			memcpy(URLBuf, ChrPtr(URL), StrLength(URL) + 1);

			notify_http_server(URLBuf, 
					   ChrPtr(FileBuf),
					   StrLength(FileBuf),
					   msg->cm_fields['W'], 
					   msg->cm_fields['I'],
					   msgnum, 
					   Ctx);
			i++;
		}
		FreeStrBuf(&FileBuf);
	} 
	else if (extPagerAllowedSystem == 0) {
		char *number;
		int commandSiz;
		char *command;

		number = strtok(configMsg, "textmessage\n");
		commandSiz = sizeof(config.c_pager_program) + strlen(number) + strlen(msg->cm_fields['W']) + 5;
		command = malloc(commandSiz);
		snprintf(command, commandSiz, "%s %s -u %s", config.c_pager_program, number, msg->cm_fields['W']);
		system(command);
		free(command);
	}
nuke:
	CtdlFreeMessage(msg);
	memset(configMsg, 0, sizeof(configMsg));
	todelete[0] = NotifyMsgnum;
	CtdlDeleteMessages(FNBL_QUEUE_ROOM, todelete, 1, "");
}

/*! \brief Checks to see what notification option the user has set
 *
 */
void extNotify_getPrefs(long configMsgNum, char *configMsg) 
{
	struct CtdlMessage *prefMsg;
	// Do a simple string search to see if 'funambol' is selected as the
	// type. This string would be at the very top of the message contents.
	if (configMsgNum == -1) {
		CtdlLogPrintf(CTDL_ERR, "extNotify_isAllowedByPrefs was passed a non-existant config message id\n");
		return;
	}
	prefMsg = CtdlFetchMessage(configMsgNum, 1);
	strncpy(configMsg, prefMsg->cm_fields['M'], strlen(prefMsg->cm_fields['M']));
	CtdlFreeMessage(prefMsg);
}

/*! \brief Get configuration message for pager/funambol system from the
 *			users "My Citadel Config" room
 */
long extNotify_getConfigMessage(char *username) {
	struct ctdlroom qrbuf; // scratch for room
	struct ctdluser user; // ctdl user instance
	char configRoomName[ROOMNAMELEN];
	struct CtdlMessage *msg;
	struct cdbdata *cdbfr;
	long *msglist = NULL;
	int num_msgs = 0;
	long confMsgNum = -1;
	int a;

	// Get the user
	CtdlGetUser(&user, username);
    
	CtdlMailboxName(configRoomName, sizeof configRoomName, &user, USERCONFIGROOM);
	// Fill qrbuf
	CtdlGetRoom(&qrbuf, configRoomName);
	/* Do something really, really stoopid here. Raid the room on ourselves,
	 * loop through the messages manually and find it. I don't want
	 * to use a CtdlForEachMessage callback here, as we would be
	 * already in one */
	cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
	if (cdbfr != NULL) {
		msglist = (long *) cdbfr->ptr;
		cdbfr->ptr = NULL;	/* CtdlForEachMessage() now owns this memory */
		num_msgs = cdbfr->len / sizeof(long);
		cdb_free(cdbfr);
	} else {
		CtdlLogPrintf(CTDL_DEBUG, "extNotify_getConfigMessage: No config messages found\n");
		return -1;	/* No messages at all?  No further action. */
	}
	for (a = 0; a < num_msgs; ++a) {
		msg = CtdlFetchMessage(msglist[a], 1);
		if (msg != NULL) {
			if ((msg->cm_fields['U'] != NULL) && 
			    (strncasecmp(msg->cm_fields['U'], PAGER_CONFIG_MESSAGE,
					 strlen(PAGER_CONFIG_MESSAGE)) == 0)) {
				confMsgNum = msglist[a];
			}
			CtdlFreeMessage(msg);
		}
	}
	return confMsgNum;
    
}

CTDL_MODULE_INIT(extnotify)
{
	if (!threading)
	{
		create_extnotify_queue();
		CtdlRegisterSessionHook(do_extnotify_queue, EVT_TIMER);
	}
	/* return our Subversion id for the Log */
        return "$Id: extnotify_main.c 8617 2010-06-09 22:37:37Z dothebart $";
}