]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/gateway/osrf_http_translator.c
f6d492b48a93b8f3f7f519c163ddf1eda90d0bd3
[OpenSRF.git] / src / gateway / osrf_http_translator.c
1 #include <sys/time.h>
2 #include <sys/resource.h>
3 #include <unistd.h>
4 #include <strings.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>
12
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"
17
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"
22
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"
28
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"
36
37
38 char* configFile = DEFAULT_TRANSLATOR_CONFIG_FILE;
39 char* configCtx = DEFAULT_TRANSLATOR_CONFIG_CTX;
40 char* cacheServers = DEFAULT_TRANSLATOR_CACHE_SERVERS;
41
42 char* routerName = NULL;
43 char* domainName = NULL;
44 int osrfConnected = 0;
45 char recipientBuf[128];
46 char contentTypeBuf[80];
47
48 #if 0
49 // Commented out to avoid compiler warning
50 // for development only, writes to apache error log
51 static void _dbg(char* s, ...) {
52     VA_LIST_TO_STRING(s);
53     fprintf(stderr, "%s\n", VA_BUF);
54     fflush(stderr);
55 }
56 #endif
57
58 // Translator struct
59 typedef struct {
60     request_rec* apreq;
61     transport_client* handle;
62     osrfList* messages;
63     char* body;
64     char* delim;
65     const char* recipient;
66     const char* service;
67     const char* thread;
68     const char* remoteHost;
69     int complete;
70     int timeout;
71     int multipart;
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
76     int localXid;
77 } osrfHttpTranslator;
78
79
80 static const char* osrfHttpTranslatorGetConfigFile(cmd_parms *parms, void *config, const char *arg) {
81     configFile = (char*) arg;
82         return NULL;
83 }
84 static const char* osrfHttpTranslatorGetConfigFileCtx(cmd_parms *parms, void *config, const char *arg) {
85     configCtx = (char*) arg;
86         return NULL;
87 }
88 static const char* osrfHttpTranslatorGetCacheServer(cmd_parms *parms, void *config, const char *arg) {
89     cacheServers = (char*) arg;
90         return NULL;
91 }
92
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"),
101     {NULL}
102 };
103
104
105 // there can only be one, so use a global static one
106 static osrfHttpTranslator globalTranslator;
107
108 /*
109  * Constructs a new translator object based on the current apache 
110  * request_rec.  Reads the request body and headers.
111  */
112 static osrfHttpTranslator* osrfNewHttpTranslator(request_rec* apreq) {
113     osrfHttpTranslator* trans = &globalTranslator;
114     trans->apreq = apreq;
115     trans->complete = 0;
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;
122
123     /* load the message body */
124     osrfStringArray* params     = apacheParseParms(apreq);
125     trans->body = apacheGetFirstParamValue(params, "osrf-msg");
126     osrfStringArrayFree(params);
127
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)));
132
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);
136
137     const char* timeout = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TIMEOUT);
138     if(timeout) 
139         trans->timeout = atoi(timeout);
140     else 
141         trans->timeout = DEFAULT_TRANSLATOR_TIMEOUT;
142
143     const char* multipart = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_MULTIPART);
144     if(multipart && !strcasecmp(multipart, "true"))
145         trans->multipart = 1;
146     else
147         trans->multipart = 0;
148
149     char buf[32];
150     snprintf(buf, sizeof(buf), "%d%ld", getpid(), time(NULL));
151     trans->delim = md5sum(buf);
152
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;
157
158     return trans;
159 }
160
161 static void osrfHttpTranslatorFree(osrfHttpTranslator* trans) {
162     if(!trans) return;
163     if(trans->body)
164         free(trans->body);
165     if(trans->delim)
166         free(trans->delim);
167     osrfListFree(trans->messages);
168 }
169
170 #if 0
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);
179 }
180 #endif
181
182 /**
183  * Determines the correct recipient address based on the requested 
184  * service or recipient address.  
185  */
186 static int osrfHttpTranslatorSetTo(osrfHttpTranslator* trans) {
187     int stat = 0;
188     jsonObject* sessionCache = NULL;
189
190     if(trans->service) {
191         if(trans->recipient) {
192             osrfLogError(OSRF_LOG_MARK, "Specifying both SERVICE and TO are not allowed");
193
194         } else {
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;
202             stat = 1;
203         }
204
205     } else {
206
207         if(trans->recipient) {
208             sessionCache = osrfCacheGetObject(trans->thread);
209
210             if(sessionCache) {
211                 const char* ipAddr = jsonObjectGetString(
212                     jsonObjectGetKeyConst( sessionCache, "ip" ));
213                 const char* recipient = jsonObjectGetString(
214                     jsonObjectGetKeyConst( sessionCache, "jid" ));
215
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);
222                     stat = 1;
223                     trans->service = apr_pstrdup(
224                         trans->apreq->pool, jsonObjectGetString(
225                             jsonObjectGetKeyConst( sessionCache, "service" )));
226
227                 } else {
228                     osrfLogError(OSRF_LOG_MARK, 
229                         "Session cache for thread %s does not match request", trans->thread);
230                 }
231             }  else {
232                 osrfLogError(OSRF_LOG_MARK, 
233                     "attempt to send directly to %s without a session", trans->recipient);
234             }
235         } else {
236             osrfLogError(OSRF_LOG_MARK, "No SERVICE or RECIPIENT defined");
237         } 
238     }
239
240     jsonObjectFree(sessionCache);
241     return stat;
242 }
243
244 /**
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.
248  */
249 static char* osrfHttpTranslatorParseRequest(osrfHttpTranslator* trans) {
250     osrfMessage* msg;
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);
254
255     if(numMsgs == 0)
256         return NULL;
257
258     // log request messages to the activity log
259     int i;
260     for(i = 0; i < numMsgs; i++) {
261         msg = msgList[i];
262         osrfMessageSetIngress(msg, TRANSLATOR_INGRESS);
263
264         switch(msg->m_type) {
265
266             case REQUEST: {
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);
272
273                 const jsonObject* obj = NULL;
274                 int i = 0;
275                 const char* str;
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))) {
280                         redactParams = 1;
281                         break;
282                     }
283                 }
284                 if(redactParams) {
285                     OSRF_BUFFER_ADD(act, " **PARAMS REDACTED**");
286                 } else {
287                     i = 0;
288                     while((obj = jsonObjectGetIndex(params, i++))) {
289                         str = jsonObjectToJSON(obj);
290                         if( i == 1 )
291                             OSRF_BUFFER_ADD(act, " ");
292                         else
293                             OSRF_BUFFER_ADD(act, ", ");
294                         OSRF_BUFFER_ADD(act, str);
295                         free(str);
296                     }
297                 }
298                 osrfLogActivity(OSRF_LOG_MARK, "%s", act->buf);
299                 buffer_free(act);
300                 break;
301             }
302
303             case CONNECT:
304                 trans->connecting = 1;
305                 if (numMsgs == 1) 
306                     trans->connectOnly = 1;
307                 break;
308
309             case DISCONNECT:
310                 trans->disconnecting = 1;
311                 if (numMsgs == 1) 
312                     trans->disconnectOnly = 1;
313                 break;
314
315             case RESULT:
316                 osrfLogWarning( OSRF_LOG_MARK, "Unexpected RESULT message received" );
317                 break;
318
319             case STATUS:
320                 osrfLogWarning( OSRF_LOG_MARK, "Unexpected STATUS message received" );
321                 break;
322
323             default:
324                 osrfLogWarning( OSRF_LOG_MARK, "Invalid message type %d received",
325                     msg->m_type );
326                 break;
327         }
328     }
329
330     return osrfMessageSerializeBatch(msgList, numMsgs);
331 }
332
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;
338
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);
344             return 0;
345         }
346         // XXX hm, check for explicit status=COMPLETE message instead??
347         if(last->status_code != OSRF_STATUS_CONTINUE)
348             trans->complete = 1;
349     }
350
351     return 1;
352 }
353
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);
364     } else {
365         ap_set_content_type(trans->apreq, JSON_CONTENT_TYPE);
366     }
367 }
368
369 /**
370  * Cache the transaction with the JID of the backend process we are talking to
371  */
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);
378 }
379
380
381 /**
382  * Writes a single chunk of multipart/x-mixed-replace content
383  */
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);
393     } else {
394         ap_rprintf(trans->apreq, "--%s\n", trans->delim);
395         //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s\n", trans->delim);
396     }
397     ap_rflush(trans->apreq);
398 }
399
400 static int osrfHttpTranslatorProcess(osrfHttpTranslator* trans) {
401     if(trans->body == NULL)
402         return HTTP_BAD_REQUEST;
403
404     if(!osrfHttpTranslatorSetTo(trans))
405         return HTTP_BAD_REQUEST;
406
407     char* jsonBody = osrfHttpTranslatorParseRequest(trans);
408     if (NULL == jsonBody)
409         return HTTP_BAD_REQUEST;
410
411     while(client_recv(trans->handle, 0))
412         continue; // discard any old status messages in the recv queue
413
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);
419     message_free(tmsg); 
420     free(jsonBody);
421
422     if(trans->disconnectOnly) {
423         osrfLogDebug(OSRF_LOG_MARK, "exiting early on disconnect");
424         osrfCacheRemove(trans->thread);
425         return OK;
426     }
427
428     // process the response from the opensrf service
429     int firstWrite = 1;
430     while(!trans->complete) {
431         transport_message* msg = client_recv(trans->handle, trans->timeout);
432
433         if(trans->handle->error) {
434             osrfLogError(OSRF_LOG_MARK, "Transport error");
435             osrfCacheRemove(trans->thread);
436             return HTTP_INTERNAL_SERVER_ERROR;
437         }
438
439         if(msg == NULL)
440             return HTTP_GATEWAY_TIME_OUT;
441
442         if(msg->is_error) {
443             osrfLogError(OSRF_LOG_MARK, "XMPP message resulted in error code %d", msg->error_code);
444             osrfCacheRemove(trans->thread);
445             return HTTP_NOT_FOUND;
446         }
447
448         if(!osrfHttpTranslatorCheckStatus(trans, msg))
449             continue;
450
451         if(firstWrite) {
452             osrfHttpTranslatorInitHeaders(trans, msg);
453             if(trans->connecting)
454                 osrfHttpTranslatorCacheSession(trans, msg->sender);
455             firstWrite = 0;
456         }
457
458         if(trans->multipart) {
459             osrfHttpTranslatorWriteChunk(trans, msg);
460             if(trans->connectOnly)
461                 break;
462         } else {
463             if(!trans->messages)
464                 trans->messages = osrfNewList();
465             osrfListPush(trans->messages, msg->body);
466
467             if(trans->complete || trans->connectOnly) {
468                 growing_buffer* buf = buffer_init(128);
469                 unsigned int i;
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);
478                 }
479
480                 ap_rputs(buf->buf, trans->apreq);
481                 buffer_free(buf);
482             }
483         }
484     }
485
486     if(trans->disconnecting) // DISCONNECT within a multi-message batch
487         osrfCacheRemove(trans->thread);
488
489     return OK;
490 }
491
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
497                 exit(1);
498         }
499 }
500
501 #if 0
502 // Commented out to avoid compiler warning
503 // it's dead, Jim
504 static apr_status_t childExit(void* data) {
505     osrf_system_shutdown();
506     return OK;
507 }
508 #endif
509
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);
514                 return;
515         }
516
517     routerName = osrfConfigGetValue(NULL, "/router_name");
518     domainName = osrfConfigGetValue(NULL, "/domain");
519     const char* servers[] = {cacheServers};
520     osrfCacheInit(servers, 1, 86400);
521         osrfConnected = 1;
522
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);
526 }
527
528 static int handler(request_rec *r) {
529     int stat = OK;
530         if(strcmp(r->handler, MODULE_NAME)) return DECLINED;
531     if(r->header_only) return stat;
532
533         r->allowed |= (AP_METHOD_BIT << M_GET);
534         r->allowed |= (AP_METHOD_BIT << M_POST);
535
536         osrfLogSetAppname("osrf_http_translator");
537         osrfAppSessionSetIngress(TRANSLATOR_INGRESS);
538     testConnection(r);
539
540         osrfLogMkXid();
541     osrfHttpTranslator* trans = osrfNewHttpTranslator(r);
542     if(trans->body) {
543         stat = osrfHttpTranslatorProcess(trans);
544         //osrfHttpTranslatorDebug(trans);
545         osrfLogInfo(OSRF_LOG_MARK, "translator resulted in status %d", stat);
546     } else {
547         osrfLogWarning(OSRF_LOG_MARK, "no message body to process");
548     }
549     osrfHttpTranslatorFree(trans);
550         return stat;
551 }
552
553
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);
557 }
558
559
560 module AP_MODULE_DECLARE_DATA osrf_http_translator_module = {
561         STANDARD20_MODULE_STUFF,
562     NULL,
563         NULL,
564     NULL,
565         NULL,
566     osrfHttpTranslatorCmds,
567         registerHooks,
568 };