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];
47 // Commented out to avoid compiler warning
48 // for development only, writes to apache error log
49 static void _dbg(char* s, ...) {
51 fprintf(stderr, "%s\n", VA_BUF);
59 transport_client* handle;
63 const char* recipient;
66 const char* remoteHost;
70 int connectOnly; // there is only 1 message, a CONNECT
71 int disconnectOnly; // there is only 1 message, a DISCONNECT
72 int connecting; // there is a connect message in this batch
73 int disconnecting; // there is a connect message in this batch
78 static const char* osrfHttpTranslatorGetConfigFile(cmd_parms *parms, void *config, const char *arg) {
79 configFile = (char*) arg;
82 static const char* osrfHttpTranslatorGetConfigFileCtx(cmd_parms *parms, void *config, const char *arg) {
83 configCtx = (char*) arg;
86 static const char* osrfHttpTranslatorGetCacheServer(cmd_parms *parms, void *config, const char *arg) {
87 cacheServers = (char*) arg;
91 /** set up the configuration handlers */
92 static const command_rec osrfHttpTranslatorCmds[] = {
93 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_FILE, osrfHttpTranslatorGetConfigFile,
94 NULL, RSRC_CONF, "osrf translator config file"),
95 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_CTX, osrfHttpTranslatorGetConfigFileCtx,
96 NULL, RSRC_CONF, "osrf translator config file context"),
97 AP_INIT_TAKE1( OSRF_TRANSLATOR_CACHE_SERVER, osrfHttpTranslatorGetCacheServer,
98 NULL, RSRC_CONF, "osrf translator cache server"),
103 // there can only be one, so use a global static one
104 static osrfHttpTranslator globalTranslator;
107 * Constructs a new translator object based on the current apache
108 * request_rec. Reads the request body and headers.
110 static osrfHttpTranslator* osrfNewHttpTranslator(request_rec* apreq) {
111 osrfHttpTranslator* trans = &globalTranslator;
112 trans->apreq = apreq;
114 trans->connectOnly = 0;
115 trans->disconnectOnly = 0;
116 trans->connecting = 0;
117 trans->disconnecting = 0;
118 trans->remoteHost = apreq->connection->remote_ip;
119 trans->messages = NULL;
121 /* load the message body */
122 osrfStringArray* params = apacheParseParms(apreq);
123 trans->body = apacheGetFirstParamValue(params, "osrf-msg");
124 osrfStringArrayFree(params);
126 /* load the request headers */
127 if (apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID))
128 // force our log xid to match the caller
129 osrfLogForceXid(strdup(apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)));
131 trans->handle = osrfSystemGetTransportClient();
132 trans->recipient = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TO);
133 trans->service = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_SERVICE);
135 const char* timeout = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TIMEOUT);
137 trans->timeout = atoi(timeout);
139 trans->timeout = DEFAULT_TRANSLATOR_TIMEOUT;
141 const char* multipart = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_MULTIPART);
142 if(multipart && !strcasecmp(multipart, "true"))
143 trans->multipart = 1;
145 trans->multipart = 0;
148 snprintf(buf, sizeof(buf), "%d%ld", getpid(), time(NULL));
149 trans->delim = md5sum(buf);
151 /* Use thread if it has been passed in; otherwise, just use the delimiter */
152 trans->thread = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
153 ? apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
154 : (const char*)trans->delim;
159 static void osrfHttpTranslatorFree(osrfHttpTranslator* trans) {
165 osrfListFree(trans->messages);
169 // Commented out to avoid compiler warning
170 static void osrfHttpTranslatorDebug(osrfHttpTranslator* trans) {
171 _dbg("-----------------------------------");
172 _dbg("body = %s", trans->body);
173 _dbg("service = %s", trans->service);
174 _dbg("thread = %s", trans->thread);
175 _dbg("multipart = %d", trans->multipart);
176 _dbg("recipient = %s", trans->recipient);
181 * Determines the correct recipient address based on the requested
182 * service or recipient address.
184 static int osrfHttpTranslatorSetTo(osrfHttpTranslator* trans) {
186 jsonObject* sessionCache = NULL;
189 if(trans->recipient) {
190 osrfLogError(OSRF_LOG_MARK, "Specifying both SERVICE and TO are not allowed");
193 // service is specified, build a recipient address
194 // from the router, domain, and service
195 int size = snprintf(recipientBuf, 128, "%s@%s/%s", routerName,
196 domainName, trans->service);
197 recipientBuf[size] = '\0';
198 osrfLogDebug(OSRF_LOG_MARK, "Set recipient to %s", recipientBuf);
199 trans->recipient = recipientBuf;
205 if(trans->recipient) {
206 sessionCache = osrfCacheGetObject(trans->thread);
209 const char* ipAddr = jsonObjectGetString(
210 jsonObjectGetKeyConst( sessionCache, "ip" ));
211 const char* recipient = jsonObjectGetString(
212 jsonObjectGetKeyConst( sessionCache, "jid" ));
214 // choosing a specific recipient address requires that the recipient and
215 // thread be cached on the server (so drone processes cannot be hijacked)
216 if(!strcmp(ipAddr, trans->remoteHost) && !strcmp(recipient, trans->recipient)) {
217 osrfLogDebug( OSRF_LOG_MARK,
218 "Found cached session from host %s and recipient %s",
219 trans->remoteHost, trans->recipient);
221 trans->service = apr_pstrdup(
222 trans->apreq->pool, jsonObjectGetString(
223 jsonObjectGetKeyConst( sessionCache, "service" )));
226 osrfLogError(OSRF_LOG_MARK,
227 "Session cache for thread %s does not match request", trans->thread);
230 osrfLogError(OSRF_LOG_MARK,
231 "attempt to send directly to %s without a session", trans->recipient);
234 osrfLogError(OSRF_LOG_MARK, "No SERVICE or RECIPIENT defined");
238 jsonObjectFree(sessionCache);
243 * Parses the request body and logs any REQUEST messages to the activity log
245 static int osrfHttpTranslatorParseRequest(osrfHttpTranslator* trans) {
246 const osrfMessage* msg;
247 osrfMessage* msgList[MAX_MSGS_PER_PACKET];
248 int numMsgs = osrf_message_deserialize(trans->body, msgList, MAX_MSGS_PER_PACKET);
249 osrfLogDebug(OSRF_LOG_MARK, "parsed %d opensrf messages in this packet", numMsgs);
256 if(msg->m_type == CONNECT) {
257 trans->connectOnly = 1;
258 trans->connecting = 1;
261 if(msg->m_type == DISCONNECT) {
262 trans->disconnectOnly = 1;
263 trans->disconnecting = 1;
268 // log request messages to the activity log
270 for(i = 0; i < numMsgs; i++) {
273 switch(msg->m_type) {
276 const jsonObject* params = msg->_params;
277 growing_buffer* act = buffer_init(128);
278 buffer_fadd(act, "[%s] [%s] %s %s", trans->remoteHost, "",
279 trans->service, msg->method_name);
281 const jsonObject* obj = NULL;
284 while((obj = jsonObjectGetIndex(params, i++))) {
285 str = jsonObjectToJSON(obj);
287 OSRF_BUFFER_ADD(act, " ");
289 OSRF_BUFFER_ADD(act, ", ");
290 OSRF_BUFFER_ADD(act, str);
293 osrfLogActivity(OSRF_LOG_MARK, "%s", act->buf);
299 trans->connecting = 1;
303 trans->disconnecting = 1;
307 osrfLogWarning( OSRF_LOG_MARK, "Unexpected RESULT message received" );
311 osrfLogWarning( OSRF_LOG_MARK, "Unexpected STATUS message received" );
315 osrfLogWarning( OSRF_LOG_MARK, "Invalid message type %d received",
324 static int osrfHttpTranslatorCheckStatus(osrfHttpTranslator* trans, transport_message* msg) {
325 osrfMessage* omsgList[MAX_MSGS_PER_PACKET];
326 int numMsgs = osrf_message_deserialize(msg->body, omsgList, MAX_MSGS_PER_PACKET);
327 osrfLogDebug(OSRF_LOG_MARK, "parsed %d response messages", numMsgs);
328 if(numMsgs == 0) return 0;
330 osrfMessage* last = omsgList[numMsgs-1];
331 if(last->m_type == STATUS) {
332 if(last->status_code == OSRF_STATUS_TIMEOUT) {
333 osrfLogDebug(OSRF_LOG_MARK, "removing cached session on request timeout");
334 osrfCacheRemove(trans->thread);
337 // XXX hm, check for explicit status=COMPLETE message instead??
338 if(last->status_code != OSRF_STATUS_CONTINUE)
345 static void osrfHttpTranslatorInitHeaders(osrfHttpTranslator* trans, transport_message* msg) {
346 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_FROM, msg->sender);
347 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_THREAD, trans->thread);
348 if(trans->multipart) {
349 sprintf(contentTypeBuf, MULTIPART_CONTENT_TYPE, trans->delim);
350 contentTypeBuf[79] = '\0';
351 osrfLogDebug(OSRF_LOG_MARK, "content type %s : %s : %s", MULTIPART_CONTENT_TYPE,
352 trans->delim, contentTypeBuf);
353 ap_set_content_type(trans->apreq, contentTypeBuf);
354 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
356 ap_set_content_type(trans->apreq, JSON_CONTENT_TYPE);
361 * Cache the transaction with the JID of the backend process we are talking to
363 static void osrfHttpTranslatorCacheSession(osrfHttpTranslator* trans, const char* jid) {
364 jsonObject* cacheObj = jsonNewObject(NULL);
365 jsonObjectSetKey(cacheObj, "ip", jsonNewObject(trans->remoteHost));
366 jsonObjectSetKey(cacheObj, "jid", jsonNewObject(jid));
367 jsonObjectSetKey(cacheObj, "service", jsonNewObject(trans->service));
368 osrfCachePutObject((char*) trans->thread, cacheObj, CACHE_TIME);
373 * Writes a single chunk of multipart/x-mixed-replace content
375 static void osrfHttpTranslatorWriteChunk(osrfHttpTranslator* trans, transport_message* msg) {
376 osrfLogInternal(OSRF_LOG_MARK, "sending multipart chunk %s", msg->body);
377 ap_rprintf(trans->apreq,
378 "Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
379 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: Content-type: %s\n\n%s\n\n",
380 //JSON_CONTENT_TYPE, msg->body);
381 if(trans->complete) {
382 ap_rprintf(trans->apreq, "--%s--\n", trans->delim);
383 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s--\n", trans->delim);
385 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
386 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s\n", trans->delim);
388 ap_rflush(trans->apreq);
391 static int osrfHttpTranslatorProcess(osrfHttpTranslator* trans) {
392 if(trans->body == NULL)
393 return HTTP_BAD_REQUEST;
395 if(!osrfHttpTranslatorSetTo(trans))
396 return HTTP_BAD_REQUEST;
398 if(!osrfHttpTranslatorParseRequest(trans))
399 return HTTP_BAD_REQUEST;
401 while(client_recv(trans->handle, 0))
402 continue; // discard any old status messages in the recv queue
404 // send the message to the recipient
405 transport_message* tmsg = message_init(
406 trans->body, NULL, trans->thread, trans->recipient, NULL);
407 message_set_osrf_xid(tmsg, osrfLogGetXid());
408 client_send_message(trans->handle, tmsg);
411 if(trans->disconnectOnly) {
412 osrfLogDebug(OSRF_LOG_MARK, "exiting early on disconnect");
413 osrfCacheRemove(trans->thread);
417 // process the response from the opensrf service
419 while(!trans->complete) {
420 transport_message* msg = client_recv(trans->handle, trans->timeout);
422 if(trans->handle->error) {
423 osrfLogError(OSRF_LOG_MARK, "Transport error");
424 osrfCacheRemove(trans->thread);
425 return HTTP_INTERNAL_SERVER_ERROR;
429 return HTTP_GATEWAY_TIME_OUT;
432 osrfLogError(OSRF_LOG_MARK, "XMPP message resulted in error code %d", msg->error_code);
433 osrfCacheRemove(trans->thread);
434 return HTTP_NOT_FOUND;
437 if(!osrfHttpTranslatorCheckStatus(trans, msg))
441 osrfHttpTranslatorInitHeaders(trans, msg);
442 if(trans->connecting)
443 osrfHttpTranslatorCacheSession(trans, msg->sender);
447 if(trans->multipart) {
448 osrfHttpTranslatorWriteChunk(trans, msg);
449 if(trans->connectOnly)
453 trans->messages = osrfNewList();
454 osrfListPush(trans->messages, msg->body);
456 if(trans->complete || trans->connectOnly) {
457 growing_buffer* buf = buffer_init(128);
459 OSRF_BUFFER_ADD(buf, osrfListGetIndex(trans->messages, 0));
460 for(i = 1; i < trans->messages->size; i++) {
461 buffer_chomp(buf); // chomp off the closing array bracket
462 char* body = osrfListGetIndex(trans->messages, i);
463 char newbuf[strlen(body)];
464 sprintf(newbuf, body+1); // chomp off the opening array bracket
465 OSRF_BUFFER_ADD_CHAR(buf, ',');
466 OSRF_BUFFER_ADD(buf, newbuf);
469 ap_rputs(buf->buf, trans->apreq);
475 if(trans->disconnecting) // DISCONNECT within a multi-message batch
476 osrfCacheRemove(trans->thread);
481 static void testConnection(request_rec* r) {
482 if(!osrfConnected || !osrfSystemGetTransportClient()) {
483 osrfLogError(OSRF_LOG_MARK, "We're not connected to OpenSRF");
484 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "We're not connected to OpenSRF");
485 usleep(100000); // .1 second to prevent process die/start overload
491 // Commented out to avoid compiler warning
493 static apr_status_t childExit(void* data) {
494 osrf_system_shutdown();
499 static void childInit(apr_pool_t *p, server_rec *s) {
500 if(!osrfSystemBootstrapClientResc(configFile, configCtx, "translator")) {
501 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s,
502 "Unable to Bootstrap OpenSRF Client with config %s..", configFile);
506 routerName = osrfConfigGetValue(NULL, "/router_name");
507 domainName = osrfConfigGetValue(NULL, "/domain");
508 const char* servers[] = {cacheServers};
509 osrfCacheInit(servers, 1, 86400);
512 // at pool destroy time (= child exit time), cleanup
513 // XXX causes us to disconnect even for clone()'d process cleanup (as in mod_cgi)
514 //apr_pool_cleanup_register(p, NULL, childExit, apr_pool_cleanup_null);
517 static int handler(request_rec *r) {
519 if(strcmp(r->handler, MODULE_NAME)) return DECLINED;
520 if(r->header_only) return stat;
522 r->allowed |= (AP_METHOD_BIT << M_GET);
523 r->allowed |= (AP_METHOD_BIT << M_POST);
525 osrfLogSetAppname("osrf_http_translator");
529 osrfHttpTranslator* trans = osrfNewHttpTranslator(r);
531 stat = osrfHttpTranslatorProcess(trans);
532 //osrfHttpTranslatorDebug(trans);
533 osrfLogInfo(OSRF_LOG_MARK, "translator resulted in status %d", stat);
535 osrfLogWarning(OSRF_LOG_MARK, "no message body to process");
537 osrfHttpTranslatorFree(trans);
542 static void registerHooks (apr_pool_t *p) {
543 ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE);
544 ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE);
548 module AP_MODULE_DECLARE_DATA osrf_http_translator_module = {
549 STANDARD20_MODULE_STUFF,
554 osrfHttpTranslatorCmds,