1c184df52bad7051423a1a31d1534eb49f690fb4
[Evergreen.git] / Open-ILS / src / apachemods / mod_rest_gateway.c
1 #include "mod_rest_gateway.h"
2
3 char* ils_rest_gateway_config_file;
4
5 static const char* ils_gateway_set_config(cmd_parms *parms, void *config, const char *arg) {
6         ils_gateway_config  *cfg;
7
8         cfg = ap_get_module_config(parms->server->module_config, &ils_rest_gateway_module);
9
10         cfg->configfile = (char*) arg;
11         ils_rest_gateway_config_file = (char*) arg;
12
13         return NULL;
14 }
15
16 /* tell apache about our commands */
17 static const command_rec ils_gateway_cmds[] = {
18         AP_INIT_TAKE1( GATEWAY_CONFIG, ils_gateway_set_config, NULL, RSRC_CONF, "gateway config file"),
19         {NULL}
20 };
21
22 /* build the config object */
23 static void* ils_gateway_create_config( apr_pool_t* p, server_rec* s) {
24         ils_gateway_config* cfg = (ils_gateway_config*) apr_palloc(p, sizeof(ils_gateway_config));
25         cfg->configfile = GATEWAY_DEFAULT_CONFIG;
26         return (void*) cfg;
27 }
28
29
30 static void mod_ils_gateway_child_init(apr_pool_t *p, server_rec *s) {
31
32         char* cfg = ils_rest_gateway_config_file;
33
34         if( ! osrf_system_bootstrap_client( cfg, CONFIG_CONTEXT) ) {
35                 //osrfLogError("Unable to load gateway config file...");
36                 return;
37         }
38         fprintf(stderr, "Bootstrapping %d\n", getpid() );
39         fflush(stderr);
40 }
41
42 static int mod_ils_gateway_method_handler (request_rec *r) {
43
44         /* make sure we're needed first thing*/
45         if (strcmp(r->handler, MODULE_NAME )) 
46                 return DECLINED;
47
48         apr_pool_t *p = r->pool;        /* memory pool */
49         char* arg = r->args;                    /* url query string */
50
51         char* service                                   = NULL; /* service to connect to */
52         char* method                                    = NULL; /* method to perform */
53
54         //json* exception                               = NULL; /* returned in error conditions */
55         //jsonObject* exception                         = NULL; /* returned in error conditions */
56         string_array* sarray                    = init_string_array(12); /* method parameters */
57
58         growing_buffer* buffer          = NULL; /* POST data */
59         growing_buffer* tmp_buf         = NULL; /* temp buffer */
60
61         char* key                                               = NULL; /* query item name */
62         char* val                                               = NULL; /* query item value */
63
64         jsonObject* response                    = jsonParseString("{\"status\":0,\"debug\":\"\"}");
65         jsonObject* payload                     = jsonParseString("[]");
66         jsonObjectSetKey(response, "payload", payload );
67
68         /* verify we are connected */
69         if(!osrf_system_get_transport_client()) {
70                 //osrfLogError("Bootstrap Failed, no transport client");
71                 return HTTP_INTERNAL_SERVER_ERROR;
72         }
73
74
75
76         /* gather the post args and append them to the url query string */
77         if( !strcmp(r->method,"POST") ) {
78
79                 ap_setup_client_block(r,REQUEST_CHUNKED_DECHUNK);
80
81                 if(! ap_should_client_block(r)) {
82                         //osrfLogWarning("No Post Body");
83                 }
84
85                 char body[1025];
86                 memset(body,0,1025);
87                 buffer = buffer_init(1025);
88
89                 while(ap_get_client_block(r, body, 1024)) {
90                         //osrfLogDebug("Apache read POST block data: %s\n", body);
91                         buffer_add( buffer, body );
92                         memset(body,0,1025);
93                 }
94
95                 if(arg && arg[0]) {
96                         tmp_buf = buffer_init(1024);
97                         buffer_add(tmp_buf,arg);
98                         buffer_add(tmp_buf,buffer->buf);
99                         arg = (char*) apr_pstrdup(p, tmp_buf->buf);
100                         buffer_free(tmp_buf);
101                 } else {
102                         arg = (char*) apr_pstrdup(p, buffer->buf);
103                 }
104                 buffer_free(buffer);
105
106         } 
107
108         //osrfLogDebug("params args are %s", arg);
109
110
111         if( ! arg || !arg[0] ) { /* we received no request */
112                 //osrfLogWarning("No Args");
113                 return OK;
114         }
115
116         r->allowed |= (AP_METHOD_BIT << M_GET);
117         r->allowed |= (AP_METHOD_BIT << M_POST);
118
119         
120         while( arg && (val = ap_getword(p, (const char**) &arg, '&'))) {
121
122                 key = ap_getword(r->pool, (const char**) &val, '=');
123                 if(!key || !key[0])
124                         break;
125
126                 ap_unescape_url((char*)key);
127                 ap_unescape_url((char*)val);
128
129                 if(!strcmp(key,"service")) 
130                         service = val;
131
132                 if(!strcmp(key,"method"))
133                         method = val;
134
135                 if(!strcmp(key,"param"))
136                         string_array_add(sarray, val);
137
138         }
139
140         //osrfLogInfo("Performing(%d):  service %s | method %s | \n",
141         //              getpid(), service, method );
142
143         int k;
144         for( k = 0; k!= sarray->size; k++ ) {
145                 //osrfLogInfo( "param %s", string_array_get_string(sarray,k));
146         }
147
148         osrf_app_session* session = osrf_app_client_session_init(service);
149
150         //osrfLogDebug("MOD session service: %s", session->remote_service );
151
152         int req_id = osrf_app_session_make_req( session, NULL, method, 1, sarray );
153         string_array_destroy(sarray);
154
155         osrf_message* omsg = NULL;
156
157         //growing_buffer* result_data = buffer_init(256);
158         //buffer_add(result_data, "[");
159
160         /* gather result data */
161         /*
162         while((omsg = osrf_app_session_request_recv( session, req_id, 60 ))) {
163
164                 if( omsg->_result_content ) {
165                         char* content = jsonObjectToJSON(omsg->_result_content);
166                         buffer_add(result_data, content);
167                         buffer_add( result_data, ",");
168                         free(content);
169
170                 } else {
171
172
173                         growing_buffer* exc_buffer = buffer_init(256);
174                         buffer_add( exc_buffer, "\nReceived Exception:\nName: " );
175                         buffer_add( exc_buffer, omsg->status_name );
176                         buffer_add( exc_buffer, "\nStatus: " );
177                         buffer_add( exc_buffer, omsg->status_text );
178                         buffer_add( exc_buffer, "\nStatus: " );
179
180                         char code[16];
181                         memset(code, 0, 16);
182                         sprintf( code, "%d", omsg->status_code );
183                         buffer_add( exc_buffer, code );
184
185                         exception = json_parse_string("{}");
186                         jsonObjectSetKey(exception, "is_err", json_parse_string("1"));
187                         jsonObjectSetKey(exception, "err_msg", jsonNewObject(exc_buffer->buf) );
188
189                         //osrfLogWarning("*** Looks like we got a "
190                         //              "server exception\n%s", exc_buffer->buf );
191
192                         buffer_free(exc_buffer);
193                         osrf_message_free(omsg);
194                         break;
195                 }
196
197                 osrf_message_free(omsg);
198                 omsg = NULL;
199         }
200         */
201
202         while((omsg = osrf_app_session_request_recv( session, req_id, 60 ))) {
203
204                 jsonObjectSetKey(response, "status", jsonNewNumberObject(omsg->status_code));
205
206                 if( omsg->_result_content ) {
207                         jsonObjectPush( payload, jsonObjectClone(omsg->_result_content));
208
209                 } else {
210
211                         char* s = omsg->status_name ? omsg->status_name : "Unknown Error";
212                         char* t = omsg->status_text ? omsg->status_text : "No Error Message";
213                         jsonObjectSetKey(response, "debug", jsonNewObject("\n\n%s:\n%s\n", s, t));
214                         //osrfLogError( "Gateway received error: %s",
215                         //                jsonObjectGetString(jsonObjectGetKey(response, "debug")));
216                         break;
217                 }
218
219                 osrf_message_free(omsg);
220                 omsg = NULL;
221         }
222
223         char* content = jsonObjectToJSON(response);
224         char* xml = json_string_to_xml( content );
225
226         free(content);
227
228         
229         /* set content type to text/xml for passing around XML objects */
230         ap_set_content_type(r, "text/xml");
231         ap_rputs(xml,r);
232         free(xml);
233
234         osrf_app_session_request_finish( session, req_id );
235         //osrfLogDebug("gateway process message successfully");
236
237
238         osrf_app_session_destroy(session);
239
240         jsonObjectFree(response);
241
242         return OK;
243
244 }
245
246 static void mod_ils_gateway_register_hooks (apr_pool_t *p) {
247         ap_hook_handler(mod_ils_gateway_method_handler, NULL, NULL, APR_HOOK_MIDDLE);
248         ap_hook_child_init(mod_ils_gateway_child_init,NULL,NULL,APR_HOOK_MIDDLE);
249 }
250
251
252 module AP_MODULE_DECLARE_DATA ils_rest_gateway_module = {
253         STANDARD20_MODULE_STUFF,
254         NULL,
255         NULL,
256         ils_gateway_create_config,
257         NULL,
258         ils_gateway_cmds,
259         mod_ils_gateway_register_hooks,
260 };
261