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;
120 trans->remoteHost = apreq->connection->remote_ip;
121 trans->messages = NULL;
123 /* load the message body */
124 osrfStringArray* params = apacheParseParms(apreq);
125 trans->body = apacheGetFirstParamValue(params, "osrf-msg");
126 osrfStringArrayFree(params);
128 /* load the request headers */
129 if (apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID))
130 // force our log xid to match the caller
131 osrfLogForceXid(strdup(apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)));
133 trans->handle = osrfSystemGetTransportClient();
134 trans->recipient = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TO);
135 trans->service = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_SERVICE);
137 const char* timeout = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TIMEOUT);
139 trans->timeout = atoi(timeout);
141 trans->timeout = DEFAULT_TRANSLATOR_TIMEOUT;
143 const char* multipart = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_MULTIPART);
144 if(multipart && !strcasecmp(multipart, "true"))
145 trans->multipart = 1;
147 trans->multipart = 0;
150 snprintf(buf, sizeof(buf), "%d%ld", getpid(), time(NULL));
151 trans->delim = md5sum(buf);
153 /* Use thread if it has been passed in; otherwise, just use the delimiter */
154 trans->thread = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
155 ? apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
156 : (const char*)trans->delim;
161 static void osrfHttpTranslatorFree(osrfHttpTranslator* trans) {
167 osrfListFree(trans->messages);
171 // Commented out to avoid compiler warning
172 static void osrfHttpTranslatorDebug(osrfHttpTranslator* trans) {
173 _dbg("-----------------------------------");
174 _dbg("body = %s", trans->body);
175 _dbg("service = %s", trans->service);
176 _dbg("thread = %s", trans->thread);
177 _dbg("multipart = %d", trans->multipart);
178 _dbg("recipient = %s", trans->recipient);
183 * Determines the correct recipient address based on the requested
184 * service or recipient address.
186 static int osrfHttpTranslatorSetTo(osrfHttpTranslator* trans) {
188 jsonObject* sessionCache = NULL;
191 if(trans->recipient) {
192 osrfLogError(OSRF_LOG_MARK, "Specifying both SERVICE and TO are not allowed");
195 // service is specified, build a recipient address
196 // from the router, domain, and service
197 int size = snprintf(recipientBuf, 128, "%s@%s/%s", routerName,
198 domainName, trans->service);
199 recipientBuf[size] = '\0';
200 osrfLogDebug(OSRF_LOG_MARK, "Set recipient to %s", recipientBuf);
201 trans->recipient = recipientBuf;
207 if(trans->recipient) {
208 sessionCache = osrfCacheGetObject(trans->thread);
211 const char* ipAddr = jsonObjectGetString(
212 jsonObjectGetKeyConst( sessionCache, "ip" ));
213 const char* recipient = jsonObjectGetString(
214 jsonObjectGetKeyConst( sessionCache, "jid" ));
216 // choosing a specific recipient address requires that the recipient and
217 // thread be cached on the server (so drone processes cannot be hijacked)
218 if(!strcmp(ipAddr, trans->remoteHost) && !strcmp(recipient, trans->recipient)) {
219 osrfLogDebug( OSRF_LOG_MARK,
220 "Found cached session from host %s and recipient %s",
221 trans->remoteHost, trans->recipient);
223 trans->service = apr_pstrdup(
224 trans->apreq->pool, jsonObjectGetString(
225 jsonObjectGetKeyConst( sessionCache, "service" )));
228 osrfLogError(OSRF_LOG_MARK,
229 "Session cache for thread %s does not match request", trans->thread);
232 osrfLogError(OSRF_LOG_MARK,
233 "attempt to send directly to %s without a session", trans->recipient);
236 osrfLogError(OSRF_LOG_MARK, "No SERVICE or RECIPIENT defined");
240 jsonObjectFree(sessionCache);
245 * Parses the request body, logs any REQUEST messages to the activity log,
246 * stamps the translator ingress on each message, and returns the updated
247 * messages as a JSON string.
249 static char* osrfHttpTranslatorParseRequest(osrfHttpTranslator* trans) {
251 osrfMessage* msgList[MAX_MSGS_PER_PACKET];
252 int numMsgs = osrf_message_deserialize(trans->body, msgList, MAX_MSGS_PER_PACKET);
253 osrfLogDebug(OSRF_LOG_MARK, "parsed %d opensrf messages in this packet", numMsgs);
258 // log request messages to the activity log
260 for(i = 0; i < numMsgs; i++) {
262 osrfMessageSetIngress(msg, TRANSLATOR_INGRESS);
264 switch(msg->m_type) {
267 const jsonObject* params = msg->_params;
268 growing_buffer* act = buffer_init(128);
269 char* method = msg->method_name;
270 buffer_fadd(act, "[%s] [%s] %s %s", trans->remoteHost, "",
271 trans->service, method);
273 const jsonObject* obj = NULL;
276 int redactParams = 0;
277 while( (str = osrfStringArrayGetString(log_protect_arr, i++)) ) {
278 //osrfLogInternal(OSRF_LOG_MARK, "Checking for log protection [%s]", str);
279 if(!strncmp(method, str, strlen(str))) {
285 OSRF_BUFFER_ADD(act, " **PARAMS REDACTED**");
288 while((obj = jsonObjectGetIndex(params, i++))) {
289 str = jsonObjectToJSON(obj);
291 OSRF_BUFFER_ADD(act, " ");
293 OSRF_BUFFER_ADD(act, ", ");
294 OSRF_BUFFER_ADD(act, str);
298 osrfLogActivity(OSRF_LOG_MARK, "%s", act->buf);
304 trans->connecting = 1;
306 trans->connectOnly = 1;
310 trans->disconnecting = 1;
312 trans->disconnectOnly = 1;
316 osrfLogWarning( OSRF_LOG_MARK, "Unexpected RESULT message received" );
320 osrfLogWarning( OSRF_LOG_MARK, "Unexpected STATUS message received" );
324 osrfLogWarning( OSRF_LOG_MARK, "Invalid message type %d received",
330 return osrfMessageSerializeBatch(msgList, numMsgs);
333 static int osrfHttpTranslatorCheckStatus(osrfHttpTranslator* trans, transport_message* msg) {
334 osrfMessage* omsgList[MAX_MSGS_PER_PACKET];
335 int numMsgs = osrf_message_deserialize(msg->body, omsgList, MAX_MSGS_PER_PACKET);
336 osrfLogDebug(OSRF_LOG_MARK, "parsed %d response messages", numMsgs);
337 if(numMsgs == 0) return 0;
339 osrfMessage* last = omsgList[numMsgs-1];
340 if(last->m_type == STATUS) {
341 if(last->status_code == OSRF_STATUS_TIMEOUT) {
342 osrfLogDebug(OSRF_LOG_MARK, "removing cached session on request timeout");
343 osrfCacheRemove(trans->thread);
346 // XXX hm, check for explicit status=COMPLETE message instead??
347 if(last->status_code != OSRF_STATUS_CONTINUE)
354 static void osrfHttpTranslatorInitHeaders(osrfHttpTranslator* trans, transport_message* msg) {
355 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_FROM, msg->sender);
356 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_THREAD, trans->thread);
357 if(trans->multipart) {
358 sprintf(contentTypeBuf, MULTIPART_CONTENT_TYPE, trans->delim);
359 contentTypeBuf[79] = '\0';
360 osrfLogDebug(OSRF_LOG_MARK, "content type %s : %s : %s", MULTIPART_CONTENT_TYPE,
361 trans->delim, contentTypeBuf);
362 ap_set_content_type(trans->apreq, contentTypeBuf);
363 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
365 ap_set_content_type(trans->apreq, JSON_CONTENT_TYPE);
370 * Cache the transaction with the JID of the backend process we are talking to
372 static void osrfHttpTranslatorCacheSession(osrfHttpTranslator* trans, const char* jid) {
373 jsonObject* cacheObj = jsonNewObject(NULL);
374 jsonObjectSetKey(cacheObj, "ip", jsonNewObject(trans->remoteHost));
375 jsonObjectSetKey(cacheObj, "jid", jsonNewObject(jid));
376 jsonObjectSetKey(cacheObj, "service", jsonNewObject(trans->service));
377 osrfCachePutObject((char*) trans->thread, cacheObj, CACHE_TIME);
382 * Writes a single chunk of multipart/x-mixed-replace content
384 static void osrfHttpTranslatorWriteChunk(osrfHttpTranslator* trans, transport_message* msg) {
385 osrfLogInternal(OSRF_LOG_MARK, "sending multipart chunk %s", msg->body);
386 ap_rprintf(trans->apreq,
387 "Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
388 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: Content-type: %s\n\n%s\n\n",
389 //JSON_CONTENT_TYPE, msg->body);
390 if(trans->complete) {
391 ap_rprintf(trans->apreq, "--%s--\n", trans->delim);
392 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s--\n", trans->delim);
394 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
395 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s\n", trans->delim);
397 ap_rflush(trans->apreq);
400 static int osrfHttpTranslatorProcess(osrfHttpTranslator* trans) {
401 if(trans->body == NULL)
402 return HTTP_BAD_REQUEST;
404 if(!osrfHttpTranslatorSetTo(trans))
405 return HTTP_BAD_REQUEST;
407 char* jsonBody = osrfHttpTranslatorParseRequest(trans);
408 if (NULL == jsonBody)
409 return HTTP_BAD_REQUEST;
411 while(client_recv(trans->handle, 0))
412 continue; // discard any old status messages in the recv queue
414 // send the message to the recipient
415 transport_message* tmsg = message_init(
416 jsonBody, NULL, trans->thread, trans->recipient, NULL);
417 message_set_osrf_xid(tmsg, osrfLogGetXid());
418 client_send_message(trans->handle, tmsg);
422 if(trans->disconnectOnly) {
423 osrfLogDebug(OSRF_LOG_MARK, "exiting early on disconnect");
424 osrfCacheRemove(trans->thread);
428 // process the response from the opensrf service
430 while(!trans->complete) {
431 transport_message* msg = client_recv(trans->handle, trans->timeout);
433 if(trans->handle->error) {
434 osrfLogError(OSRF_LOG_MARK, "Transport error");
435 osrfCacheRemove(trans->thread);
436 return HTTP_INTERNAL_SERVER_ERROR;
440 return HTTP_GATEWAY_TIME_OUT;
443 osrfLogError(OSRF_LOG_MARK, "XMPP message resulted in error code %d", msg->error_code);
444 osrfCacheRemove(trans->thread);
445 return HTTP_NOT_FOUND;
448 if(!osrfHttpTranslatorCheckStatus(trans, msg))
452 osrfHttpTranslatorInitHeaders(trans, msg);
453 if(trans->connecting)
454 osrfHttpTranslatorCacheSession(trans, msg->sender);
458 if(trans->multipart) {
459 osrfHttpTranslatorWriteChunk(trans, msg);
460 if(trans->connectOnly)
464 trans->messages = osrfNewList();
465 osrfListPush(trans->messages, msg->body);
467 if(trans->complete || trans->connectOnly) {
468 growing_buffer* buf = buffer_init(128);
470 OSRF_BUFFER_ADD(buf, osrfListGetIndex(trans->messages, 0));
471 for(i = 1; i < trans->messages->size; i++) {
472 buffer_chomp(buf); // chomp off the closing array bracket
473 char* body = osrfListGetIndex(trans->messages, i);
474 char newbuf[strlen(body)];
475 sprintf(newbuf, body+1); // chomp off the opening array bracket
476 OSRF_BUFFER_ADD_CHAR(buf, ',');
477 OSRF_BUFFER_ADD(buf, newbuf);
480 ap_rputs(buf->buf, trans->apreq);
486 if(trans->disconnecting) // DISCONNECT within a multi-message batch
487 osrfCacheRemove(trans->thread);
492 static void testConnection(request_rec* r) {
493 if(!osrfConnected || !osrfSystemGetTransportClient()) {
494 osrfLogError(OSRF_LOG_MARK, "We're not connected to OpenSRF");
495 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "We're not connected to OpenSRF");
496 usleep(100000); // .1 second to prevent process die/start overload
502 // Commented out to avoid compiler warning
504 static apr_status_t childExit(void* data) {
505 osrf_system_shutdown();
510 static void childInit(apr_pool_t *p, server_rec *s) {
511 if(!osrfSystemBootstrapClientResc(configFile, configCtx, "translator")) {
512 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s,
513 "Unable to Bootstrap OpenSRF Client with config %s..", configFile);
517 routerName = osrfConfigGetValue(NULL, "/router_name");
518 domainName = osrfConfigGetValue(NULL, "/domain");
519 const char* servers[] = {cacheServers};
520 osrfCacheInit(servers, 1, 86400);
523 // at pool destroy time (= child exit time), cleanup
524 // XXX causes us to disconnect even for clone()'d process cleanup (as in mod_cgi)
525 //apr_pool_cleanup_register(p, NULL, childExit, apr_pool_cleanup_null);
528 static int handler(request_rec *r) {
530 if(strcmp(r->handler, MODULE_NAME)) return DECLINED;
531 if(r->header_only) return stat;
533 r->allowed |= (AP_METHOD_BIT << M_GET);
534 r->allowed |= (AP_METHOD_BIT << M_POST);
536 osrfLogSetAppname("osrf_http_translator");
537 osrfAppSessionSetIngress(TRANSLATOR_INGRESS);
541 osrfHttpTranslator* trans = osrfNewHttpTranslator(r);
543 stat = osrfHttpTranslatorProcess(trans);
544 //osrfHttpTranslatorDebug(trans);
545 osrfLogInfo(OSRF_LOG_MARK, "translator resulted in status %d", stat);
547 osrfLogWarning(OSRF_LOG_MARK, "no message body to process");
549 osrfHttpTranslatorFree(trans);
554 static void registerHooks (apr_pool_t *p) {
555 ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE);
556 ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE);
560 module AP_MODULE_DECLARE_DATA osrf_http_translator_module = {
561 STANDARD20_MODULE_STUFF,
566 osrfHttpTranslatorCmds,