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>
11 #include <opensrf/string_array.h>
13 #define MODULE_NAME "osrf_http_translator_module"
14 #define OSRF_TRANSLATOR_CONFIG_FILE "OSRFTranslatorConfig"
15 #define OSRF_TRANSLATOR_CONFIG_CTX "OSRFTranslatorConfigContext"
16 #define OSRF_TRANSLATOR_CACHE_SERVER "OSRFTranslatorCacheServer"
18 #define DEFAULT_TRANSLATOR_CONFIG_CTX "gateway"
19 #define DEFAULT_TRANSLATOR_CONFIG_FILE "/openils/conf/opensrf_core.xml"
20 #define DEFAULT_TRANSLATOR_TIMEOUT 1200
21 #define DEFAULT_TRANSLATOR_CACHE_SERVERS "127.0.0.1:11211"
23 #define MULTIPART_CONTENT_TYPE "multipart/x-mixed-replace;boundary=\"%s\""
24 #define JSON_CONTENT_TYPE "text/plain"
25 #define MAX_MSGS_PER_PACKET 256
26 #define CACHE_TIME 300
27 #define TRANSLATOR_INGRESS "translator-v1"
29 #define OSRF_HTTP_HEADER_TO "X-OpenSRF-to"
30 #define OSRF_HTTP_HEADER_XID "X-OpenSRF-xid"
31 #define OSRF_HTTP_HEADER_FROM "X-OpenSRF-from"
32 #define OSRF_HTTP_HEADER_THREAD "X-OpenSRF-thread"
33 #define OSRF_HTTP_HEADER_TIMEOUT "X-OpenSRF-timeout"
34 #define OSRF_HTTP_HEADER_SERVICE "X-OpenSRF-service"
35 #define OSRF_HTTP_HEADER_MULTIPART "X-OpenSRF-multipart"
38 char* configFile = DEFAULT_TRANSLATOR_CONFIG_FILE;
39 char* configCtx = DEFAULT_TRANSLATOR_CONFIG_CTX;
40 char* cacheServers = DEFAULT_TRANSLATOR_CACHE_SERVERS;
42 char* routerName = NULL;
43 char* domainName = NULL;
44 int osrfConnected = 0;
45 char recipientBuf[128];
46 char contentTypeBuf[80];
49 // Commented out to avoid compiler warning
50 // for development only, writes to apache error log
51 static void _dbg(char* s, ...) {
53 fprintf(stderr, "%s\n", VA_BUF);
61 transport_client* handle;
65 const char* recipient;
68 const char* remoteHost;
72 int connectOnly; // there is only 1 message, a CONNECT
73 int disconnectOnly; // there is only 1 message, a DISCONNECT
74 int connecting; // there is a connect message in this batch
75 int disconnecting; // there is a connect message in this batch
80 static const char* osrfHttpTranslatorGetConfigFile(cmd_parms *parms, void *config, const char *arg) {
81 configFile = (char*) arg;
84 static const char* osrfHttpTranslatorGetConfigFileCtx(cmd_parms *parms, void *config, const char *arg) {
85 configCtx = (char*) arg;
88 static const char* osrfHttpTranslatorGetCacheServer(cmd_parms *parms, void *config, const char *arg) {
89 cacheServers = (char*) arg;
93 /** set up the configuration handlers */
94 static const command_rec osrfHttpTranslatorCmds[] = {
95 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_FILE, osrfHttpTranslatorGetConfigFile,
96 NULL, RSRC_CONF, "osrf translator config file"),
97 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_CTX, osrfHttpTranslatorGetConfigFileCtx,
98 NULL, RSRC_CONF, "osrf translator config file context"),
99 AP_INIT_TAKE1( OSRF_TRANSLATOR_CACHE_SERVER, osrfHttpTranslatorGetCacheServer,
100 NULL, RSRC_CONF, "osrf translator cache server"),
105 // there can only be one, so use a global static one
106 static osrfHttpTranslator globalTranslator;
109 * Constructs a new translator object based on the current apache
110 * request_rec. Reads the request body and headers.
112 static osrfHttpTranslator* osrfNewHttpTranslator(request_rec* apreq) {
113 osrfHttpTranslator* trans = &globalTranslator;
114 trans->apreq = apreq;
116 trans->connectOnly = 0;
117 trans->disconnectOnly = 0;
118 trans->connecting = 0;
119 trans->disconnecting = 0;
121 trans->remoteHost = apreq->connection->client_ip;
123 trans->remoteHost = apreq->connection->remote_ip;
125 trans->messages = NULL;
127 /* load the message body */
128 osrfStringArray* params = apacheParseParms(apreq);
129 trans->body = apacheGetFirstParamValue(params, "osrf-msg");
130 osrfStringArrayFree(params);
132 /* load the request headers */
133 if (apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID))
134 // force our log xid to match the caller
135 osrfLogForceXid(strdup(apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)));
137 trans->handle = osrfSystemGetTransportClient();
138 trans->recipient = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TO);
139 trans->service = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_SERVICE);
141 const char* timeout = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TIMEOUT);
143 trans->timeout = atoi(timeout);
145 trans->timeout = DEFAULT_TRANSLATOR_TIMEOUT;
147 const char* multipart = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_MULTIPART);
148 if(multipart && !strcasecmp(multipart, "true"))
149 trans->multipart = 1;
151 trans->multipart = 0;
154 snprintf(buf, sizeof(buf), "%d%ld", getpid(), time(NULL));
155 trans->delim = md5sum(buf);
157 /* Use thread if it has been passed in; otherwise, just use the delimiter */
158 trans->thread = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
159 ? apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
160 : (const char*)trans->delim;
165 static void osrfHttpTranslatorFree(osrfHttpTranslator* trans) {
171 osrfListFree(trans->messages);
175 // Commented out to avoid compiler warning
176 static void osrfHttpTranslatorDebug(osrfHttpTranslator* trans) {
177 _dbg("-----------------------------------");
178 _dbg("body = %s", trans->body);
179 _dbg("service = %s", trans->service);
180 _dbg("thread = %s", trans->thread);
181 _dbg("multipart = %d", trans->multipart);
182 _dbg("recipient = %s", trans->recipient);
187 * Determines the correct recipient address based on the requested
188 * service or recipient address.
190 static int osrfHttpTranslatorSetTo(osrfHttpTranslator* trans) {
192 jsonObject* sessionCache = NULL;
195 if(trans->recipient) {
196 osrfLogError(OSRF_LOG_MARK, "Specifying both SERVICE and TO are not allowed");
199 // service is specified, build a recipient address
200 // from the router, domain, and service
201 int size = snprintf(recipientBuf, 128, "%s@%s/%s", routerName,
202 domainName, trans->service);
203 recipientBuf[size] = '\0';
204 osrfLogDebug(OSRF_LOG_MARK, "Set recipient to %s", recipientBuf);
205 trans->recipient = recipientBuf;
211 if(trans->recipient) {
212 sessionCache = osrfCacheGetObject(trans->thread);
215 const char* ipAddr = jsonObjectGetString(
216 jsonObjectGetKeyConst( sessionCache, "ip" ));
217 const char* recipient = jsonObjectGetString(
218 jsonObjectGetKeyConst( sessionCache, "jid" ));
220 // choosing a specific recipient address requires that the recipient and
221 // thread be cached on the server (so drone processes cannot be hijacked)
222 if(!strcmp(ipAddr, trans->remoteHost) && !strcmp(recipient, trans->recipient)) {
223 osrfLogDebug( OSRF_LOG_MARK,
224 "Found cached session from host %s and recipient %s",
225 trans->remoteHost, trans->recipient);
227 trans->service = apr_pstrdup(
228 trans->apreq->pool, jsonObjectGetString(
229 jsonObjectGetKeyConst( sessionCache, "service" )));
232 osrfLogError(OSRF_LOG_MARK,
233 "Session cache for thread %s does not match request", trans->thread);
236 osrfLogError(OSRF_LOG_MARK,
237 "attempt to send directly to %s without a session", trans->recipient);
240 osrfLogError(OSRF_LOG_MARK, "No SERVICE or RECIPIENT defined");
244 jsonObjectFree(sessionCache);
249 * Parses the request body, logs any REQUEST messages to the activity log,
250 * stamps the translator ingress on each message, and returns the updated
251 * messages as a JSON string.
253 static char* osrfHttpTranslatorParseRequest(osrfHttpTranslator* trans) {
255 osrfMessage* msgList[MAX_MSGS_PER_PACKET];
256 int numMsgs = osrf_message_deserialize(trans->body, msgList, MAX_MSGS_PER_PACKET);
257 osrfLogDebug(OSRF_LOG_MARK, "parsed %d opensrf messages in this packet", numMsgs);
262 // log request messages to the activity log
264 for(i = 0; i < numMsgs; i++) {
266 osrfMessageSetIngress(msg, TRANSLATOR_INGRESS);
268 switch(msg->m_type) {
271 const jsonObject* params = msg->_params;
272 growing_buffer* act = buffer_init(128);
273 char* method = msg->method_name;
274 buffer_fadd(act, "[%s] [%s] %s %s", trans->remoteHost, "",
275 trans->service, method);
277 const jsonObject* obj = NULL;
280 int redactParams = 0;
281 while( (str = osrfStringArrayGetString(log_protect_arr, i++)) ) {
282 //osrfLogInternal(OSRF_LOG_MARK, "Checking for log protection [%s]", str);
283 if(!strncmp(method, str, strlen(str))) {
289 OSRF_BUFFER_ADD(act, " **PARAMS REDACTED**");
292 while((obj = jsonObjectGetIndex(params, i++))) {
293 str = jsonObjectToJSON(obj);
295 OSRF_BUFFER_ADD(act, " ");
297 OSRF_BUFFER_ADD(act, ", ");
298 OSRF_BUFFER_ADD(act, str);
302 osrfLogActivity(OSRF_LOG_MARK, "%s", act->buf);
308 trans->connecting = 1;
310 trans->connectOnly = 1;
314 trans->disconnecting = 1;
316 trans->disconnectOnly = 1;
320 osrfLogWarning( OSRF_LOG_MARK, "Unexpected RESULT message received" );
324 osrfLogWarning( OSRF_LOG_MARK, "Unexpected STATUS message received" );
328 osrfLogWarning( OSRF_LOG_MARK, "Invalid message type %d received",
334 char* jsonString = osrfMessageSerializeBatch(msgList, numMsgs);
335 for(i = 0; i < numMsgs; i++) {
336 osrfMessageFree(msgList[i]);
341 static int osrfHttpTranslatorCheckStatus(osrfHttpTranslator* trans, transport_message* msg) {
342 osrfMessage* omsgList[MAX_MSGS_PER_PACKET];
343 int numMsgs = osrf_message_deserialize(msg->body, omsgList, MAX_MSGS_PER_PACKET);
344 osrfLogDebug(OSRF_LOG_MARK, "parsed %d response messages", numMsgs);
345 if(numMsgs == 0) return 0;
347 osrfMessage* last = omsgList[numMsgs-1];
348 if(last->m_type == STATUS) {
349 if(last->status_code == OSRF_STATUS_TIMEOUT) {
350 osrfLogDebug(OSRF_LOG_MARK, "removing cached session on request timeout");
351 osrfCacheRemove(trans->thread);
354 // XXX hm, check for explicit status=COMPLETE message instead??
355 if(last->status_code != OSRF_STATUS_CONTINUE)
362 static void osrfHttpTranslatorInitHeaders(osrfHttpTranslator* trans, transport_message* msg) {
363 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_FROM, msg->sender);
364 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_THREAD, trans->thread);
365 if(trans->multipart) {
366 sprintf(contentTypeBuf, MULTIPART_CONTENT_TYPE, trans->delim);
367 contentTypeBuf[79] = '\0';
368 osrfLogDebug(OSRF_LOG_MARK, "content type %s : %s : %s", MULTIPART_CONTENT_TYPE,
369 trans->delim, contentTypeBuf);
370 ap_set_content_type(trans->apreq, contentTypeBuf);
371 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
373 ap_set_content_type(trans->apreq, JSON_CONTENT_TYPE);
378 * Cache the transaction with the JID of the backend process we are talking to
380 static void osrfHttpTranslatorCacheSession(osrfHttpTranslator* trans, const char* jid) {
381 jsonObject* cacheObj = jsonNewObject(NULL);
382 jsonObjectSetKey(cacheObj, "ip", jsonNewObject(trans->remoteHost));
383 jsonObjectSetKey(cacheObj, "jid", jsonNewObject(jid));
384 jsonObjectSetKey(cacheObj, "service", jsonNewObject(trans->service));
385 osrfCachePutObject((char*) trans->thread, cacheObj, CACHE_TIME);
390 * Writes a single chunk of multipart/x-mixed-replace content
392 static void osrfHttpTranslatorWriteChunk(osrfHttpTranslator* trans, transport_message* msg) {
393 osrfLogInternal(OSRF_LOG_MARK, "sending multipart chunk %s", msg->body);
394 ap_rprintf(trans->apreq,
395 "Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
396 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: Content-type: %s\n\n%s\n\n",
397 //JSON_CONTENT_TYPE, msg->body);
398 if(trans->complete) {
399 ap_rprintf(trans->apreq, "--%s--\n", trans->delim);
400 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s--\n", trans->delim);
402 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
403 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s\n", trans->delim);
405 ap_rflush(trans->apreq);
408 static int osrfHttpTranslatorProcess(osrfHttpTranslator* trans) {
409 if(trans->body == NULL)
410 return HTTP_BAD_REQUEST;
412 if(!osrfHttpTranslatorSetTo(trans))
413 return HTTP_BAD_REQUEST;
415 char* jsonBody = osrfHttpTranslatorParseRequest(trans);
416 if (NULL == jsonBody)
417 return HTTP_BAD_REQUEST;
419 while(client_recv(trans->handle, 0))
420 continue; // discard any old status messages in the recv queue
422 // send the message to the recipient
423 transport_message* tmsg = message_init(
424 jsonBody, NULL, trans->thread, trans->recipient, NULL);
425 message_set_osrf_xid(tmsg, osrfLogGetXid());
426 client_send_message(trans->handle, tmsg);
430 if(trans->disconnectOnly) {
431 osrfLogDebug(OSRF_LOG_MARK, "exiting early on disconnect");
432 osrfCacheRemove(trans->thread);
436 // process the response from the opensrf service
438 while(!trans->complete) {
439 transport_message* msg = client_recv(trans->handle, trans->timeout);
441 if(trans->handle->error) {
442 osrfLogError(OSRF_LOG_MARK, "Transport error");
443 osrfCacheRemove(trans->thread);
444 return HTTP_INTERNAL_SERVER_ERROR;
448 return HTTP_GATEWAY_TIME_OUT;
451 osrfLogError(OSRF_LOG_MARK, "XMPP message resulted in error code %d", msg->error_code);
452 osrfCacheRemove(trans->thread);
453 return HTTP_NOT_FOUND;
456 if(!osrfHttpTranslatorCheckStatus(trans, msg))
460 osrfHttpTranslatorInitHeaders(trans, msg);
461 if(trans->connecting)
462 osrfHttpTranslatorCacheSession(trans, msg->sender);
466 if(trans->multipart) {
467 osrfHttpTranslatorWriteChunk(trans, msg);
468 if(trans->connectOnly)
472 trans->messages = osrfNewList();
473 osrfListPush(trans->messages, msg->body);
475 if(trans->complete || trans->connectOnly) {
476 growing_buffer* buf = buffer_init(128);
478 OSRF_BUFFER_ADD(buf, osrfListGetIndex(trans->messages, 0));
479 for(i = 1; i < trans->messages->size; i++) {
480 buffer_chomp(buf); // chomp off the closing array bracket
481 char* body = osrfListGetIndex(trans->messages, i);
482 char newbuf[strlen(body)];
483 sprintf(newbuf, "%s", body+1); // chomp off the opening array bracket
484 OSRF_BUFFER_ADD_CHAR(buf, ',');
485 OSRF_BUFFER_ADD(buf, newbuf);
488 ap_rputs(buf->buf, trans->apreq);
494 if(trans->disconnecting) // DISCONNECT within a multi-message batch
495 osrfCacheRemove(trans->thread);
500 static void testConnection(request_rec* r) {
501 if(!osrfConnected || !osrfSystemGetTransportClient()) {
502 osrfLogError(OSRF_LOG_MARK, "We're not connected to OpenSRF");
503 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "We're not connected to OpenSRF");
504 usleep(100000); // .1 second to prevent process die/start overload
510 // Commented out to avoid compiler warning
512 static apr_status_t childExit(void* data) {
513 osrf_system_shutdown();
518 static void childInit(apr_pool_t *p, server_rec *s) {
519 if(!osrfSystemBootstrapClientResc(configFile, configCtx, "translator")) {
520 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s,
521 "Unable to Bootstrap OpenSRF Client with config %s..", configFile);
525 routerName = osrfConfigGetValue(NULL, "/router_name");
526 domainName = osrfConfigGetValue(NULL, "/domain");
527 const char* servers[] = {cacheServers};
528 osrfCacheInit(servers, 1, 86400);
531 // at pool destroy time (= child exit time), cleanup
532 // XXX causes us to disconnect even for clone()'d process cleanup (as in mod_cgi)
533 //apr_pool_cleanup_register(p, NULL, childExit, apr_pool_cleanup_null);
536 static int handler(request_rec *r) {
538 if(strcmp(r->handler, MODULE_NAME)) return DECLINED;
539 if(r->header_only) return stat;
541 r->allowed |= (AP_METHOD_BIT << M_GET);
542 r->allowed |= (AP_METHOD_BIT << M_POST);
544 osrfLogSetAppname("osrf_http_translator");
545 osrfAppSessionSetIngress(TRANSLATOR_INGRESS);
549 osrfHttpTranslator* trans = osrfNewHttpTranslator(r);
551 stat = osrfHttpTranslatorProcess(trans);
552 //osrfHttpTranslatorDebug(trans);
553 osrfLogInfo(OSRF_LOG_MARK, "translator resulted in status %d", stat);
555 osrfLogWarning(OSRF_LOG_MARK, "no message body to process");
557 osrfHttpTranslatorFree(trans);
562 static void registerHooks (apr_pool_t *p) {
563 ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE);
564 ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE);
568 module AP_MODULE_DECLARE_DATA osrf_http_translator_module = {
569 STANDARD20_MODULE_STUFF,
574 osrfHttpTranslatorCmds,