2 #include <sys/resource.h>
5 #include "apachetools.h"
6 #include <opensrf/osrf_app_session.h>
7 #include <opensrf/osrf_system.h>
8 #include <opensrf/osrfConfig.h>
9 #include <opensrf/osrf_json.h>
10 #include <opensrf/osrf_cache.h>
12 #define MODULE_NAME "osrf_http_translator_module"
13 #define OSRF_TRANSLATOR_CONFIG_FILE "OSRFTranslatorConfig"
14 #define OSRF_TRANSLATOR_CONFIG_CTX "OSRFTranslatorConfigContext"
15 #define OSRF_TRANSLATOR_CACHE_SERVER "OSRFTranslatorCacheServer"
17 #define DEFAULT_TRANSLATOR_CONFIG_CTX "gateway"
18 #define DEFAULT_TRANSLATOR_CONFIG_FILE "/openils/conf/opensrf_core.xml"
19 #define DEFAULT_TRANSLATOR_TIMEOUT 1200
20 #define DEFAULT_TRANSLATOR_CACHE_SERVERS "127.0.0.1:11211"
22 #define MULTIPART_CONTENT_TYPE "multipart/x-mixed-replace;boundary=\"%s\""
23 #define JSON_CONTENT_TYPE "text/plain"
24 #define MAX_MSGS_PER_PACKET 256
25 #define CACHE_TIME 300
27 #define OSRF_HTTP_HEADER_TO "X-OpenSRF-to"
28 #define OSRF_HTTP_HEADER_XID "X-OpenSRF-xid"
29 #define OSRF_HTTP_HEADER_FROM "X-OpenSRF-from"
30 #define OSRF_HTTP_HEADER_THREAD "X-OpenSRF-thread"
31 #define OSRF_HTTP_HEADER_TIMEOUT "X-OpenSRF-timeout"
32 #define OSRF_HTTP_HEADER_SERVICE "X-OpenSRF-service"
33 #define OSRF_HTTP_HEADER_MULTIPART "X-OpenSRF-multipart"
36 char* configFile = DEFAULT_TRANSLATOR_CONFIG_FILE;
37 char* configCtx = DEFAULT_TRANSLATOR_CONFIG_CTX;
38 char* cacheServers = DEFAULT_TRANSLATOR_CACHE_SERVERS;
40 char* routerName = NULL;
41 char* domainName = NULL;
42 int osrfConnected = 0;
43 char recipientBuf[128];
44 char contentTypeBuf[80];
46 // for development only, writes to apache error log
47 static void _dbg(char* s, ...) {
49 fprintf(stderr, "%s\n", VA_BUF);
56 transport_client* handle;
60 const char* recipient;
63 const char* remoteHost;
67 int connectOnly; // there is only 1 message, a CONNECT
68 int disconnectOnly; // there is only 1 message, a DISCONNECT
69 int connecting; // there is a connect message in this batch
70 int disconnecting; // there is a connect message in this batch
75 static const char* osrfHttpTranslatorGetConfigFile(cmd_parms *parms, void *config, const char *arg) {
76 configFile = (char*) arg;
79 static const char* osrfHttpTranslatorGetConfigFileCtx(cmd_parms *parms, void *config, const char *arg) {
80 configCtx = (char*) arg;
83 static const char* osrfHttpTranslatorGetCacheServer(cmd_parms *parms, void *config, const char *arg) {
84 cacheServers = (char*) arg;
88 /** set up the configuration handlers */
89 static const command_rec osrfHttpTranslatorCmds[] = {
90 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_FILE, osrfHttpTranslatorGetConfigFile,
91 NULL, RSRC_CONF, "osrf translator config file"),
92 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_CTX, osrfHttpTranslatorGetConfigFileCtx,
93 NULL, RSRC_CONF, "osrf translator config file context"),
94 AP_INIT_TAKE1( OSRF_TRANSLATOR_CACHE_SERVER, osrfHttpTranslatorGetCacheServer,
95 NULL, RSRC_CONF, "osrf translator cache server"),
100 // there can only be one, so use a global static one
101 static osrfHttpTranslator globalTranslator;
104 * Constructs a new translator object based on the current apache
105 * request_rec. Reads the request body and headers.
107 static osrfHttpTranslator* osrfNewHttpTranslator(request_rec* apreq) {
108 osrfHttpTranslator* trans = &globalTranslator;
109 trans->apreq = apreq;
111 trans->connectOnly = 0;
112 trans->disconnectOnly = 0;
113 trans->connecting = 0;
114 trans->disconnecting = 0;
115 trans->remoteHost = apreq->connection->remote_ip;
116 trans->messages = NULL;
118 /* load the message body */
119 osrfStringArray* params = apacheParseParms(apreq);
120 trans->body = apacheGetFirstParamValue(params, "osrf-msg");
121 osrfStringArrayFree(params);
123 /* load the request headers */
124 if (apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)) // force our log xid to match the caller
125 osrfLogForceXid(strdup(apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)));
127 trans->handle = osrfSystemGetTransportClient();
128 trans->recipient = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TO);
129 trans->service = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_SERVICE);
130 trans->thread = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD); /* XXX create thread if necessary */
132 const char* timeout = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TIMEOUT);
134 trans->timeout = atoi(timeout);
136 trans->timeout = DEFAULT_TRANSLATOR_TIMEOUT;
138 const char* multipart = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_MULTIPART);
139 if(multipart && !strcasecmp(multipart, "true"))
140 trans->multipart = 1;
142 trans->multipart = 0;
145 snprintf(buf, sizeof(buf), "%d%ld", getpid(), time(NULL));
146 trans->delim = md5sum(buf);
151 static void osrfHttpTranslatorFree(osrfHttpTranslator* trans) {
157 osrfListFree(trans->messages);
160 static void osrfHttpTranslatorDebug(osrfHttpTranslator* trans) {
161 _dbg("-----------------------------------");
162 _dbg("body = %s", trans->body);
163 _dbg("service = %s", trans->service);
164 _dbg("thread = %s", trans->thread);
165 _dbg("multipart = %d", trans->multipart);
166 _dbg("recipient = %s", trans->recipient);
170 * Determines the correct recipient address based on the requested
171 * service or recipient address.
173 static int osrfHttpTranslatorSetTo(osrfHttpTranslator* trans) {
175 jsonObject* sessionCache = NULL;
178 if(trans->recipient) {
179 osrfLogError(OSRF_LOG_MARK, "Specifying both SERVICE and TO are not allowed");
182 // service is specified, build a recipient address
183 // from the router, domain, and service
184 int size = snprintf(recipientBuf, 128, "%s@%s/%s", routerName, domainName, trans->service);
185 recipientBuf[size] = '\0';
186 osrfLogDebug(OSRF_LOG_MARK, "Set recipient to %s", recipientBuf);
187 trans->recipient = recipientBuf;
193 if(trans->recipient) {
194 sessionCache = osrfCacheGetObject(trans->thread);
197 char* ipAddr = jsonObjectGetString(jsonObjectGetKey(sessionCache, "ip"));
198 char* recipient = jsonObjectGetString(jsonObjectGetKey(sessionCache, "jid"));
200 // choosing a specific recipient address requires that the recipient and
201 // thread be cached on the server (so drone processes cannot be hijacked)
202 if(!strcmp(ipAddr, trans->remoteHost) && !strcmp(recipient, trans->recipient)) {
203 osrfLogDebug(OSRF_LOG_MARK, "Found cached session from host %s and recipient %s",
204 trans->remoteHost, trans->recipient);
206 trans->service = apr_pstrdup(
207 trans->apreq->pool, jsonObjectGetString(jsonObjectGetKey(sessionCache, "service")));
210 osrfLogError(OSRF_LOG_MARK,
211 "Session cache for thread %s does not match request", trans->thread);
214 osrfLogError(OSRF_LOG_MARK,
215 "attempt to send directly to %s without a session", trans->recipient);
218 osrfLogError(OSRF_LOG_MARK, "No SERVICE or RECIPIENT defined");
222 jsonObjectFree(sessionCache);
227 * Parses the request body and logs any REQUEST messages to the activity log
229 static int osrfHttpTranslatorParseRequest(osrfHttpTranslator* trans) {
231 osrfMessage* msgList[MAX_MSGS_PER_PACKET];
232 int numMsgs = osrf_message_deserialize(trans->body, msgList, MAX_MSGS_PER_PACKET);
233 osrfLogDebug(OSRF_LOG_MARK, "parsed %d opensrf messages in this packet", numMsgs);
240 if(msg->m_type == CONNECT) {
241 trans->connectOnly = 1;
242 trans->connecting = 1;
245 if(msg->m_type == DISCONNECT) {
246 trans->disconnectOnly = 1;
247 trans->disconnecting = 1;
252 // log request messages to the activity log
254 for(i = 0; i < numMsgs; i++) {
257 switch(msg->m_type) {
260 jsonObject* params = msg->_params;
261 growing_buffer* act = buffer_init(128);
262 buffer_fadd(act, "[%s] [%s] %s %s", trans->remoteHost, "", trans->service, msg->method_name);
264 jsonObject* obj = NULL;
267 while((obj = jsonObjectGetIndex(params, i++))) {
268 str = jsonObjectToJSON(obj);
270 OSRF_BUFFER_ADD(act, " ");
272 OSRF_BUFFER_ADD(act, ", ");
273 OSRF_BUFFER_ADD(act, str);
276 osrfLogActivity(OSRF_LOG_MARK, "%s", act->buf);
282 trans->connecting = 1;
286 trans->disconnecting = 1;
294 static int osrfHttpTranslatorCheckStatus(osrfHttpTranslator* trans, transport_message* msg) {
295 osrfMessage* omsgList[MAX_MSGS_PER_PACKET];
296 int numMsgs = osrf_message_deserialize(msg->body, omsgList, MAX_MSGS_PER_PACKET);
297 osrfLogDebug(OSRF_LOG_MARK, "parsed %d response messages", numMsgs);
298 if(numMsgs == 0) return 0;
300 osrfMessage* last = omsgList[numMsgs-1];
301 if(last->m_type == STATUS) {
302 if(last->status_code == OSRF_STATUS_TIMEOUT) {
303 osrfLogDebug(OSRF_LOG_MARK, "removing cached session on request timeout");
304 osrfCacheRemove(trans->thread);
307 // XXX hm, check for explicit status=COMPLETE message instead??
308 if(last->status_code != OSRF_STATUS_CONTINUE)
315 static void osrfHttpTranslatorInitHeaders(osrfHttpTranslator* trans, transport_message* msg) {
316 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_FROM, msg->sender);
317 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_THREAD, trans->thread);
318 if(trans->multipart) {
319 sprintf(contentTypeBuf, MULTIPART_CONTENT_TYPE, trans->delim);
320 contentTypeBuf[79] = '\0';
321 osrfLogDebug(OSRF_LOG_MARK, "content type %s : %s : %s", MULTIPART_CONTENT_TYPE, trans->delim, contentTypeBuf);
322 ap_set_content_type(trans->apreq, contentTypeBuf);
323 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
325 ap_set_content_type(trans->apreq, JSON_CONTENT_TYPE);
330 * Cache the transaction with the JID of the backend process we are talking to
332 static void osrfHttpTranslatorCacheSession(osrfHttpTranslator* trans, const char* jid) {
333 jsonObject* cacheObj = jsonNewObject(NULL);
334 jsonObjectSetKey(cacheObj, "ip", jsonNewObject(trans->remoteHost));
335 jsonObjectSetKey(cacheObj, "jid", jsonNewObject(jid));
336 jsonObjectSetKey(cacheObj, "service", jsonNewObject(trans->service));
337 osrfCachePutObject((char*) trans->thread, cacheObj, CACHE_TIME);
342 * Writes a single chunk of multipart/x-mixed-replace content
344 static void osrfHttpTranslatorWriteChunk(osrfHttpTranslator* trans, transport_message* msg) {
345 osrfLogInternal(OSRF_LOG_MARK, "sending multipart chunk %s", msg->body);
346 ap_rprintf(trans->apreq,
347 "Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
348 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
349 if(trans->complete) {
350 ap_rprintf(trans->apreq, "--%s--\n", trans->delim);
351 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s--\n", trans->delim);
353 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
354 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s\n", trans->delim);
356 ap_rflush(trans->apreq);
359 static int osrfHttpTranslatorProcess(osrfHttpTranslator* trans) {
360 if(trans->body == NULL)
361 return HTTP_BAD_REQUEST;
363 if(!osrfHttpTranslatorSetTo(trans))
364 return HTTP_BAD_REQUEST;
366 if(!osrfHttpTranslatorParseRequest(trans))
367 return HTTP_BAD_REQUEST;
369 while(client_recv(trans->handle, 0))
370 continue; // discard any old status messages in the recv queue
372 // send the message to the recipient
373 transport_message* tmsg = message_init(
374 trans->body, NULL, trans->thread, trans->recipient, NULL);
375 message_set_osrf_xid(tmsg, osrfLogGetXid());
376 client_send_message(trans->handle, tmsg);
379 if(trans->disconnectOnly) {
380 osrfLogDebug(OSRF_LOG_MARK, "exiting early on disconnect");
381 osrfCacheRemove(trans->thread);
385 // process the response from the opensrf service
387 while(!trans->complete) {
388 transport_message* msg = client_recv(trans->handle, trans->timeout);
390 if(trans->handle->error) {
391 osrfLogError(OSRF_LOG_MARK, "Transport error");
392 osrfCacheRemove(trans->thread);
393 return HTTP_INTERNAL_SERVER_ERROR;
397 return HTTP_GATEWAY_TIME_OUT;
400 osrfLogError(OSRF_LOG_MARK, "XMPP message resulted in error code %d", msg->error_code);
401 osrfCacheRemove(trans->thread);
402 return HTTP_NOT_FOUND;
405 if(!osrfHttpTranslatorCheckStatus(trans, msg))
409 osrfHttpTranslatorInitHeaders(trans, msg);
410 if(trans->connecting)
411 osrfHttpTranslatorCacheSession(trans, msg->sender);
415 if(trans->multipart) {
416 osrfHttpTranslatorWriteChunk(trans, msg);
417 if(trans->connectOnly)
421 trans->messages = osrfNewList();
422 osrfListPush(trans->messages, msg->body);
424 if(trans->complete || trans->connectOnly) {
425 growing_buffer* buf = buffer_init(128);
427 OSRF_BUFFER_ADD(buf, osrfListGetIndex(trans->messages, 0));
428 for(i = 1; i < trans->messages->size; i++) {
429 buffer_chomp(buf); // chomp off the closing array bracket
430 char* body = osrfListGetIndex(trans->messages, i);
431 char newbuf[strlen(body)];
432 sprintf(newbuf, body+1); // chomp off the opening array bracket
433 OSRF_BUFFER_ADD_CHAR(buf, ',');
434 OSRF_BUFFER_ADD(buf, newbuf);
437 ap_rputs(buf->buf, trans->apreq);
443 if(trans->disconnecting) // DISCONNECT within a multi-message batch
444 osrfCacheRemove(trans->thread);
449 static void testConnection(request_rec* r) {
450 if(!osrfConnected || !osrfSystemGetTransportClient()) {
451 osrfLogError(OSRF_LOG_MARK, "We're not connected to OpenSRF");
452 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "We're not connected to OpenSRF");
453 usleep(100000); // .1 second to prevent process die/start overload
459 static apr_status_t childExit(void* data) {
460 osrf_system_shutdown();
464 static void childInit(apr_pool_t *p, server_rec *s) {
465 if(!osrfSystemBootstrapClientResc(configFile, configCtx, "translator")) {
466 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s,
467 "Unable to Bootstrap OpenSRF Client with config %s..", configFile);
471 routerName = osrfConfigGetValue(NULL, "/router_name");
472 domainName = osrfConfigGetValue(NULL, "/domain");
473 const char* servers[] = {cacheServers};
474 osrfCacheInit(servers, 1, 86400);
477 // at pool destroy time (= child exit time), cleanup
478 // XXX causes us to disconnect even for clone()'d process cleanup (as in mod_cgi)
479 //apr_pool_cleanup_register(p, NULL, childExit, apr_pool_cleanup_null);
482 static int handler(request_rec *r) {
484 if(strcmp(r->handler, MODULE_NAME)) return DECLINED;
485 if(r->header_only) return stat;
487 r->allowed |= (AP_METHOD_BIT << M_GET);
488 r->allowed |= (AP_METHOD_BIT << M_POST);
490 osrfLogSetAppname("osrf_http_translator");
494 osrfHttpTranslator* trans = osrfNewHttpTranslator(r);
496 stat = osrfHttpTranslatorProcess(trans);
497 //osrfHttpTranslatorDebug(trans);
498 osrfLogInfo(OSRF_LOG_MARK, "translator resulted in status %d", stat);
500 osrfLogWarning(OSRF_LOG_MARK, "no message body to process");
502 osrfHttpTranslatorFree(trans);
507 static void registerHooks (apr_pool_t *p) {
508 ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE);
509 ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE);
513 module AP_MODULE_DECLARE_DATA osrf_http_translator_module = {
514 STANDARD20_MODULE_STUFF,
519 osrfHttpTranslatorCmds,