]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/libopensrf/osrf_app_session.c
ca5d14e3c1905073408508ddf82984110429a772
[OpenSRF.git] / src / libopensrf / osrf_app_session.c
1 /**
2         @file osrf_app_session.c
3         @brief Implementation of osrfAppSession.
4 */
5
6 #include <time.h>
7 #include "opensrf/osrf_app_session.h"
8 #include "opensrf/osrf_stack.h"
9
10 struct osrf_app_request_struct {
11         /** The controlling session. */
12         struct osrf_app_session_struct* session;
13
14         /** Request id.  It is the same as the thread_trace of the REQUEST message
15                 for which it was created.
16         */
17         int request_id;
18         /** True if we have received a 'request complete' message from our request. */
19         int complete;
20         /** The original REQUEST message payload. */
21         osrfMessage* payload;
22         /** Linked list of responses to the request. */
23         osrfMessage* result;
24
25         /** Boolean; if true, then a call that is waiting on a response will reset the
26         timeout and set this variable back to false. */
27         int reset_timeout;
28         /** Linkage pointers for a linked list.  We maintain a hash table of pending requests,
29             and each slot of the hash table is a doubly linked list. */
30         osrfAppRequest* next;
31         osrfAppRequest* prev;
32 };
33
34 static inline unsigned int request_id_hash( int req_id );
35 static osrfAppRequest* find_app_request( const osrfAppSession* session, int req_id );
36 static void add_app_request( osrfAppSession* session, osrfAppRequest* req );
37
38 /* Send the given message */
39 static int _osrf_app_session_send( osrfAppSession*, osrfMessage* msg );
40
41 static int osrfAppSessionMakeLocaleRequest(
42                 osrfAppSession* session, const jsonObject* params, const char* method_name,
43                 int protocol, osrfStringArray* param_strings, char* locale );
44
45 /** @brief The global session cache.
46
47         Key: session_id.  Data: osrfAppSession.
48 */
49 static osrfHash* osrfAppSessionCache = NULL;
50
51 // --------------------------------------------------------------------------
52 // Request API
53 // --------------------------------------------------------------------------
54
55 /**
56         @brief Create a new osrfAppRequest.
57         @param session Pointer to the osrfAppSession that will own the new osrfAppRequest.
58         @param msg Pointer to the osrfMessage representing the request.
59         @return Pointer to the new osrfAppRequest.
60
61         The calling code is responsible for freeing the osrfAppRequest by calling
62         _osrf_app_request_free().
63 */
64 static osrfAppRequest* _osrf_app_request_init(
65                 osrfAppSession* session, osrfMessage* msg ) {
66
67         osrfAppRequest* req = safe_malloc(sizeof(osrfAppRequest));
68
69         req->session        = session;
70         req->request_id     = msg->thread_trace;
71         req->complete       = 0;
72         req->payload        = msg;
73         req->result         = NULL;
74         req->reset_timeout  = 0;
75         req->next           = NULL;
76         req->prev           = NULL;
77
78         return req;
79 }
80
81
82 /**
83         @brief Free an osrfAppRequest and everything it owns.
84         @param req Pointer to an osrfAppRequest.
85 */
86 static void _osrf_app_request_free( osrfAppRequest * req ) {
87         if( req ) {
88                 if( req->payload )
89                         osrfMessageFree( req->payload );
90
91                 /* Free the messages in the result queue */
92                 osrfMessage* next_msg;
93                 while( req->result ) {
94                         next_msg = req->result->next;
95                         osrfMessageFree( req->result );
96                         req->result = next_msg;
97                 }
98
99                 free( req );
100         }
101 }
102
103 /**
104         @brief Append a new message to the list of responses to a request.
105         @param req Pointer to the osrfAppRequest for the original REQUEST message.
106         @param result Pointer to an osrfMessage received in response to the request.
107
108         For each osrfAppRequest we maintain a linked list of response messages, and traverse
109         it to find the end.
110 */
111 static void _osrf_app_request_push_queue( osrfAppRequest* req, osrfMessage* result ){
112         if(req == NULL || result == NULL)
113                 return;
114
115         osrfLogDebug( OSRF_LOG_MARK, "App Session pushing request [%d] onto request queue",
116                         result->thread_trace );
117         if(req->result == NULL) {
118                 req->result = result;   // Add the first node
119
120         } else {
121
122                 // Find the last node in the list, and append the new node to it
123                 osrfMessage* ptr = req->result;
124                 osrfMessage* ptr2 = req->result->next;
125                 while( ptr2 ) {
126                         ptr = ptr2;
127                         ptr2 = ptr2->next;
128                 }
129                 ptr->next = result;
130         }
131 }
132
133 /**
134         @brief Remove an osrfAppRequest (identified by request_id) from an osrfAppSession.
135         @param session Pointer to the osrfAppSession that owns the osrfAppRequest.
136         @param req_id request_id of the osrfAppRequest to be removed.
137 */
138 void osrf_app_session_request_finish( osrfAppSession* session, int req_id ) {
139
140         if( session ) {
141                 // Search the hash table for the request in question
142                 unsigned int index = request_id_hash( req_id );
143                 osrfAppRequest* old_req = session->request_hash[ index ];
144                 while( old_req ) {
145                         if( old_req->request_id == req_id )
146                                 break;
147                         else
148                                 old_req = old_req->next;
149                 }
150
151                 if( old_req ) {
152                         // Remove the request from the doubly linked list
153                         if( old_req->prev )
154                                 old_req->prev->next = old_req->next;
155                         else
156                                 session->request_hash[ index ] = old_req->next;
157
158                         if( old_req->next )
159                                 old_req->next->prev = old_req->prev;
160
161                         _osrf_app_request_free( old_req );
162                 }
163         }
164 }
165
166 /**
167         @brief Derive a hash key from a request id.
168         @param req_id The request id.
169         @return The corresponding hash key; an index into request_hash[].
170
171         If OSRF_REQUEST_HASH_SIZE is a power of two, then this calculation should
172         reduce to a binary AND.
173 */
174 static inline unsigned int request_id_hash( int req_id ) {
175         return ((unsigned int) req_id ) % OSRF_REQUEST_HASH_SIZE;
176 }
177
178 /**
179         @brief Search for an osrfAppRequest in the hash table, given a request id.
180         @param session Pointer to the relevant osrfAppSession.
181         @param req_id The request_id of the osrfAppRequest being sought.
182         @return A pointer to the osrfAppRequest if found, or NULL if not.
183 */
184 static osrfAppRequest* find_app_request( const osrfAppSession* session, int req_id ) {
185
186         osrfAppRequest* req = session->request_hash[ request_id_hash( req_id) ];
187         while( req ) {
188                 if( req->request_id == req_id )
189                         break;
190                 else
191                         req = req->next;
192         }
193
194         return req;
195 }
196
197 /**
198         @brief Add an osrfAppRequest to the hash table of a given osrfAppSession.
199         @param session Pointer to the session to which the request belongs.
200         @param req Pointer to the osrfAppRequest to be stored.
201
202         Find the right spot in the hash table; then add the request to the linked list at that
203         spot.  We just add it to the head of the list, without trying to maintain any particular
204         ordering.
205 */
206 static void add_app_request( osrfAppSession* session, osrfAppRequest* req ) {
207         if( session && req ) {
208                 unsigned int index = request_id_hash( req->request_id );
209                 req->next = session->request_hash[ index ];
210                 req->prev = NULL;
211                 session->request_hash[ index ] = req;
212         }
213 }
214
215 /**
216         @brief Request a reset of the timeout period for a request.
217         @param session Pointer to the relevant osrfAppSession.
218         @param req_id Request ID of the request whose timeout is to be reset.
219
220         This happens when a client receives a STATUS message with a status code
221         OSRF_STATUS_CONTINUE; in effect the server is asking for more time.
222
223         The request to be reset is identified by the combination of session and request id.
224 */
225 void osrf_app_session_request_reset_timeout( osrfAppSession* session, int req_id ) {
226         if(session == NULL)
227                 return;
228         osrfLogDebug( OSRF_LOG_MARK, "Resetting request timeout %d", req_id );
229         osrfAppRequest* req = find_app_request( session, req_id );
230         if( req )
231                 req->reset_timeout = 1;
232 }
233
234 /**
235         @brief Fetch the next response message to a given previous request, subject to a timeout.
236         @param req Pointer to the osrfAppRequest representing the request.
237         @param timeout Maxmimum time to wait, in seconds.
238
239         @return Pointer to the next osrfMessage for this request, if one is available, or if it
240         becomes available before the end of the timeout; otherwise NULL;
241
242         If there is already a message available in the input queue for this request, dequeue and
243         return it immediately.  Otherwise wait up to timeout seconds until you either get an
244         input message for the specified request, run out of time, or encounter an error.
245
246         If the only message we receive for this request is a STATUS message with a status code
247         OSRF_STATUS_COMPLETE, then return NULL.  That means that the server has nothing further
248         to send in response to this request.
249
250         You may also receive other messages for other requests, and other sessions.  These other
251         messages will be wholly or partially processed behind the scenes while you wait for the
252         one you want.
253 */
254 static osrfMessage* _osrf_app_request_recv( osrfAppRequest* req, int timeout ) {
255
256         if(req == NULL) return NULL;
257
258         if( req->result != NULL ) {
259                 /* Dequeue the next message in the list */
260                 osrfMessage* tmp_msg = req->result;
261                 req->result = req->result->next;
262                 return tmp_msg;
263         }
264
265         time_t start = time(NULL);
266         time_t remaining = (time_t) timeout;
267
268         // Wait repeatedly for input messages until you either receive one for the request
269         // you're interested in, run out of time, or encounter an error.
270         // Wait repeatedly because you may also receive messages for other requests, or for
271         // other sessions, and process them behind the scenes. These are not the messages
272         // you're looking for.
273         while( remaining >= 0 ) {
274                 /* tell the session to wait for stuff */
275                 osrfLogDebug( OSRF_LOG_MARK,  "In app_request receive with remaining time [%d]",
276                                 (int) remaining );
277
278
279                 osrf_app_session_queue_wait( req->session, 0, NULL );
280                 if(req->session->transport_error) {
281                         osrfLogError(OSRF_LOG_MARK, "Transport error in recv()");
282                         return NULL;
283                 }
284
285                 if( req->result != NULL ) { /* if we received any results for this request */
286                         /* dequeue the first message in the list */
287                         osrfLogDebug( OSRF_LOG_MARK, "app_request_recv received a message, returning it" );
288                         osrfMessage* ret_msg = req->result;
289                         req->result = ret_msg->next;
290                         if (ret_msg->sender_locale)
291                                 osrf_app_session_set_locale(req->session, ret_msg->sender_locale);
292
293                         return ret_msg;
294                 }
295
296                 if( req->complete )
297                         return NULL;
298
299                 osrf_app_session_queue_wait( req->session, (int) remaining, NULL );
300
301                 if(req->session->transport_error) {
302                         osrfLogError(OSRF_LOG_MARK, "Transport error in recv()");
303                         return NULL;
304                 }
305
306                 if( req->result != NULL ) { /* if we received any results for this request */
307                         /* dequeue the first message in the list */
308                         osrfLogDebug( OSRF_LOG_MARK,  "app_request_recv received a message, returning it");
309                         osrfMessage* ret_msg = req->result;
310                         req->result = ret_msg->next;
311                         if (ret_msg->sender_locale)
312                                 osrf_app_session_set_locale(req->session, ret_msg->sender_locale);
313
314                         return ret_msg;
315                 }
316
317                 if( req->complete )
318                         return NULL;
319
320                 // Determine how much time is left
321                 if(req->reset_timeout) {
322                         // We got a reprieve.  This happens when a client receives a STATUS message
323                         // with a status code OSRF_STATUS_CONTINUE.  We restart the timer from the
324                         // beginning -- but only once.  We reset reset_timeout to zero. so that a
325                         // second attempted reprieve will allow, at most, only one more second.
326                         remaining = (time_t) timeout;
327                         req->reset_timeout = 0;
328                         osrfLogDebug( OSRF_LOG_MARK, "Received a timeout reset");
329                 } else {
330                         remaining -= (int) (time(NULL) - start);
331                 }
332         }
333
334         // Timeout exhausted; no messages for the request in question
335         char* paramString = jsonObjectToJSON(req->payload->_params);
336         osrfLogInfo( OSRF_LOG_MARK, "Returning NULL from app_request_recv after timeout: %s %s",
337                 req->payload->method_name, paramString);
338         free(paramString);
339
340         return NULL;
341 }
342
343 // --------------------------------------------------------------------------
344 // Session API
345 // --------------------------------------------------------------------------
346
347 /**
348         @brief Install a copy of a locale string in a specified session.
349         @param session Pointer to the osrfAppSession in which the locale is to be installed.
350         @param locale The locale string to be copied and installed.
351         @return A pointer to the installed copy of the locale string.
352 */
353 char* osrf_app_session_set_locale( osrfAppSession* session, const char* locale ) {
354         if (!session || !locale)
355                 return NULL;
356
357         if(session->session_locale) {
358                 if( strlen(session->session_locale) >= strlen(locale) ) {
359                         /* There's room available; just copy */
360                         strcpy(session->session_locale, locale);
361                 } else {
362                         free(session->session_locale);
363                         session->session_locale = strdup( locale );
364                 }
365         } else {
366                 session->session_locale = strdup( locale );
367         }
368
369         return session->session_locale;
370 }
371
372 /**
373         @brief Find the osrfAppSession for a given session id.
374         @param session_id The session id to look for.
375         @return Pointer to the corresponding osrfAppSession if found, or NULL if not.
376
377         Search the global session cache for the specified session id.
378 */
379 osrfAppSession* osrf_app_session_find_session( const char* session_id ) {
380         if(session_id)
381                 return osrfHashGet( osrfAppSessionCache, session_id );
382         return NULL;
383 }
384
385
386 /**
387         @brief Add a session to the global session cache, keyed by session id.
388         @param session Pointer to the osrfAppSession to be added.
389
390         If a cache doesn't exist yet, create one.  It's an osrfHash using session ids for the
391         key and osrfAppSessions for the data.
392 */
393 static void _osrf_app_session_push_session( osrfAppSession* session ) {
394         if( session ) {
395                 if( osrfAppSessionCache == NULL )
396                         osrfAppSessionCache = osrfNewHash();
397                 if( osrfHashGet( osrfAppSessionCache, session->session_id ) )
398                         return;   // A session with this id is already in the cache.  Shouldn't happen.
399                 osrfHashSet( osrfAppSessionCache, session, session->session_id );
400         }
401 }
402
403 /**
404         @brief Create an osrfAppSession for a client.
405         @param remote_service Name of the service to which to connect
406         @return Pointer to the new osrfAppSession if successful, or NULL upon error.
407
408         Allocate memory for an osrfAppSession, and initialize it as follows:
409
410         - For talking with Jabber, grab an existing transport_client.  It must have been
411         already set up by a prior call to osrfSystemBootstrapClientResc().
412         - Build a Jabber ID for addressing the service.
413         - Build a session ID based on a fine-grained timestamp and a process ID.  This ID is
414         intended to be unique across the system, but uniqueness is not strictly guaranteed.
415         - Initialize various other bits and scraps.
416         - Add the session to the global session cache.
417
418         Do @em not connect to the service at this point.
419 */
420 osrfAppSession* osrfAppSessionClientInit( const char* remote_service ) {
421
422         if (!remote_service) {
423                 osrfLogWarning( OSRF_LOG_MARK, "No remote service specified in osrfAppSessionClientInit");
424                 return NULL;
425         }
426
427         osrfAppSession* session = safe_malloc(sizeof(osrfAppSession));
428
429         // Grab an existing transport_client for talking with Jabber
430         session->transport_handle = osrfSystemGetTransportClient();
431         if( session->transport_handle == NULL ) {
432                 osrfLogWarning( OSRF_LOG_MARK, "No transport client for service 'client'");
433                 free( session );
434                 return NULL;
435         }
436
437         // Get a list of domain names from the config settings;
438         // ignore all but the first one in the list.
439         osrfStringArray* arr = osrfNewStringArray(8);
440         osrfConfigGetValueList(NULL, arr, "/domain");
441         const char* domain = osrfStringArrayGetString(arr, 0);
442         if (!domain) {
443                 osrfLogWarning( OSRF_LOG_MARK, "No domains specified in the OpenSRF config file");
444                 free( session );
445                 osrfStringArrayFree(arr);
446                 return NULL;
447         }
448
449         // Get a router name from the config settings.
450         char* router_name = osrfConfigGetValue(NULL, "/router_name");
451         if (!router_name) {
452                 osrfLogWarning( OSRF_LOG_MARK, "No router name specified in the OpenSRF config file");
453                 free( session );
454                 osrfStringArrayFree(arr);
455                 return NULL;
456         }
457
458         char target_buf[512];
459         target_buf[ 0 ] = '\0';
460
461         // Using the router name, domain, and service name,
462         // build a Jabber ID for addressing the service.
463         int len = snprintf( target_buf, sizeof(target_buf), "%s@%s/%s",
464                         router_name ? router_name : "(null)",
465                         domain ? domain : "(null)",
466                         remote_service ? remote_service : "(null)" );
467         osrfStringArrayFree(arr);
468         free(router_name);
469
470         if( len >= sizeof( target_buf ) ) {
471                 osrfLogWarning( OSRF_LOG_MARK, "Buffer overflow for remote_id");
472                 free( session );
473                 return NULL;
474         }
475
476         session->remote_id = strdup(target_buf);
477         session->orig_remote_id = strdup(session->remote_id);
478         session->remote_service = strdup(remote_service);
479         session->session_locale = NULL;
480         session->transport_error = 0;
481         session->panic = 0;
482
483         #ifdef ASSUME_STATELESS
484         session->stateless = 1;
485         osrfLogDebug( OSRF_LOG_MARK, "%s session is stateless", remote_service );
486         #else
487         session->stateless = 0;
488         osrfLogDebug( OSRF_LOG_MARK, "%s session is NOT stateless", remote_service );
489         #endif
490
491         /* build a chunky, random session id */
492         char id[256];
493
494         snprintf(id, sizeof(id), "%f.%d%ld", get_timestamp_millis(), (int)time(NULL), (long) getpid());
495         session->session_id = strdup(id);
496         osrfLogDebug( OSRF_LOG_MARK,  "Building a new client session with id [%s] [%s]",
497                         session->remote_service, session->session_id );
498
499         session->thread_trace = 0;
500         session->state = OSRF_SESSION_DISCONNECTED;
501         session->type = OSRF_SESSION_CLIENT;
502
503         session->userData = NULL;
504         session->userDataFree = NULL;
505
506         // Initialize the hash table
507         int i;
508         for( i = 0; i < OSRF_REQUEST_HASH_SIZE; ++i )
509                 session->request_hash[ i ] = NULL;
510
511         _osrf_app_session_push_session( session );
512         return session;
513 }
514
515 /**
516         @brief Create an osrfAppSession for a server.
517         @param session_id The session ID.  In practice this comes from the thread member of
518         the transport message from the client.
519         @param our_app The name of the service being provided.
520         @param remote_id Jabber ID of the client.
521         @return Pointer to the newly created osrfAppSession if successful, or NULL upon failure.
522
523         If there is already a session with the specified id, report an error.  Otherwise:
524
525         - Allocate memory for an osrfAppSession.
526         - For talking with Jabber, grab an existing transport_client.  It should have been
527         already set up by a prior call to osrfSystemBootstrapClientResc().
528         - Install a copy of the @a our_app string as remote_service.
529         - Install copies of the @a remote_id string as remote_id and orig_remote_id.
530         - Initialize various other bits and scraps.
531         - Add the session to the global session cache.
532
533         Do @em not respond to the client at this point.
534 */
535 osrfAppSession* osrf_app_server_session_init(
536                 const char* session_id, const char* our_app, const char* remote_id ) {
537
538         osrfLogDebug( OSRF_LOG_MARK, "Initing server session with session id %s, service %s,"
539                         " and remote_id %s", session_id, our_app, remote_id );
540
541         osrfAppSession* session = osrf_app_session_find_session( session_id );
542         if(session) {
543                 osrfLogWarning( OSRF_LOG_MARK, "App session already exists for session id %s",
544                                 session_id );
545                 return NULL;
546         }
547
548         session = safe_malloc(sizeof(osrfAppSession));
549
550         // Grab an existing transport_client for talking with Jabber
551         session->transport_handle = osrfSystemGetTransportClient();
552         if( session->transport_handle == NULL ) {
553                 osrfLogWarning( OSRF_LOG_MARK, "No transport client for service '%s'", our_app );
554                 free(session);
555                 return NULL;
556         }
557
558         // Decide from a config setting whether the session is stateless or not.  However
559         // this determination is pointless because it will immediately be overruled according
560         // to the compile-time macro ASSUME_STATELESS.
561         int stateless = 0;
562         char* statel = osrf_settings_host_value("/apps/%s/stateless", our_app );
563         if(statel) stateless = atoi(statel);
564         free(statel);
565
566         session->remote_id = strdup(remote_id);
567         session->orig_remote_id = strdup(remote_id);
568         session->session_id = strdup(session_id);
569         session->remote_service = strdup(our_app);
570         session->stateless = stateless;
571
572         #ifdef ASSUME_STATELESS
573         session->stateless = 1;
574         #else
575         session->stateless = 0;
576         #endif
577
578         session->thread_trace = 0;
579         session->state = OSRF_SESSION_DISCONNECTED;
580         session->type = OSRF_SESSION_SERVER;
581         session->session_locale = NULL;
582
583         session->userData = NULL;
584         session->userDataFree = NULL;
585
586         // Initialize the hash table
587         int i;
588         for( i = 0; i < OSRF_REQUEST_HASH_SIZE; ++i )
589                 session->request_hash[ i ] = NULL;
590
591         _osrf_app_session_push_session( session );
592         return session;
593 }
594
595 /**
596         @brief Create a REQUEST message, send it, and save it for future reference.
597         @param session Pointer to the current session, which has the addressing information.
598         @param params One way of specifying the parameters for the method.
599         @param method_name The name of the method to be called.
600         @param protocol Protocol.
601         @param param_strings Another way of specifying the parameters for the method.
602         @return The request ID of the resulting REQUEST message, or -1 upon error.
603
604         DEPRECATED.  Use osrfAppSessionSendRequest() instead.  It is identical except that it
605         doesn't use the param_strings argument, which is redundant, confusing, and unused.
606
607         If @a params is non-NULL, use it to specify the parameters to the method.  Otherwise
608         use @a param_strings.
609
610         If @a params points to a JSON_ARRAY, then pass each element of the array as a separate
611         parameter.  If @a params points to any other kind of jsonObject, pass it as a single
612         parameter.
613
614         If @a params is NULL, and @a param_strings is not NULL, then each pointer in the
615         osrfStringArray must point to a JSON string encoding a parameter.  Pass them.
616
617         At this writing, all calls to this function use @a params to pass parameters, rather than
618         @a param_strings.
619
620         This function is a thin wrapper for osrfAppSessionMakeLocaleRequest().
621 */
622 int osrfAppSessionMakeRequest(
623                 osrfAppSession* session, const jsonObject* params,
624                 const char* method_name, int protocol, osrfStringArray* param_strings ) {
625
626         osrfLogWarning( OSRF_LOG_MARK, "Function osrfAppSessionMakeRequest() is deprecasted; "
627                         "call osrfAppSessionSendRequest() instead" );
628         return osrfAppSessionMakeLocaleRequest( session, params,
629                         method_name, protocol, param_strings, NULL );
630 }
631
632 /**
633         @brief Create a REQUEST message, send it, and save it for future reference.
634         @param session Pointer to the current session, which has the addressing information.
635         @param params One way of specifying the parameters for the method.
636         @param method_name The name of the method to be called.
637         @param protocol Protocol.
638         @return The request ID of the resulting REQUEST message, or -1 upon error.
639
640         If @a params points to a JSON_ARRAY, then pass each element of the array as a separate
641         parameter.  If @a params points to any other kind of jsonObject, pass it as a single
642         parameter.
643
644         This function is a thin wrapper for osrfAppSessionMakeLocaleRequest().
645 */
646 int osrfAppSessionSendRequest( osrfAppSession* session, const jsonObject* params,
647                 const char* method_name, int protocol ) {
648
649         return osrfAppSessionMakeLocaleRequest( session, params,
650                  method_name, protocol, NULL, NULL );
651 }
652
653 /**
654         @brief Create a REQUEST message, send it, and save it for future reference.
655         @param session Pointer to the current session, which has the addressing information.
656         @param params One way of specifying the parameters for the method.
657         @param method_name The name of the method to be called.
658         @param protocol Protocol.
659         @param param_strings Another way of specifying the parameters for the method.
660         @param locale Pointer to a locale string.
661         @return The request ID of the resulting REQUEST message, or -1 upon error.
662
663         See the discussion of osrfAppSessionSendRequest(), which at this writing is the only
664         place that calls this function, except for the similar but deprecated function
665         osrfAppSessionMakeRequest().
666
667         At this writing, the @a param_strings and @a locale parameters are always NULL.
668 */
669 static int osrfAppSessionMakeLocaleRequest(
670                 osrfAppSession* session, const jsonObject* params, const char* method_name,
671                 int protocol, osrfStringArray* param_strings, char* locale ) {
672
673         if(session == NULL) return -1;
674
675         osrfLogMkXid();
676
677         osrfMessage* req_msg = osrf_message_init( REQUEST, ++(session->thread_trace), protocol );
678         osrf_message_set_method(req_msg, method_name);
679
680         if (locale) {
681                 osrf_message_set_locale(req_msg, locale);
682         } else if (session->session_locale) {
683                 osrf_message_set_locale(req_msg, session->session_locale);
684         }
685
686         if(params) {
687                 osrf_message_set_params(req_msg, params);
688
689         } else {
690
691                 if(param_strings) {
692                         int i;
693                         for(i = 0; i!= param_strings->size ; i++ ) {
694                                 osrf_message_add_param(req_msg,
695                                         osrfStringArrayGetString(param_strings,i));
696                         }
697                 }
698         }
699
700         osrfAppRequest* req = _osrf_app_request_init( session, req_msg );
701         if(_osrf_app_session_send( session, req_msg ) ) {
702                 osrfLogWarning( OSRF_LOG_MARK,  "Error sending request message [%d]",
703                                 session->thread_trace );
704                 _osrf_app_request_free(req);
705                 return -1;
706         }
707
708         osrfLogDebug( OSRF_LOG_MARK,  "Pushing [%d] onto request queue for session [%s] [%s]",
709                         req->request_id, session->remote_service, session->session_id );
710         add_app_request( session, req );
711         return req->request_id;
712 }
713
714 /**
715         @brief Mark an osrfAppRequest (identified by session and ID) as complete.
716         @param session Pointer to the osrfAppSession that owns the request.
717         @param request_id Request ID of the osrfAppRequest.
718 */
719 void osrf_app_session_set_complete( osrfAppSession* session, int request_id ) {
720         if(session == NULL)
721                 return;
722
723         osrfAppRequest* req = find_app_request( session, request_id );
724         if(req)
725                 req->complete = 1;
726 }
727
728 /**
729         @brief Determine whether a osrfAppRequest, identified by session and ID, is complete.
730         @param session Pointer to the osrfAppSession that owns the request.
731         @param request_id Request ID of the osrfAppRequest.
732         @return Non-zero if the request is complete; zero if it isn't, or if it can't be found.
733 */
734 int osrf_app_session_request_complete( const osrfAppSession* session, int request_id ) {
735         if(session == NULL)
736                 return 0;
737
738         osrfAppRequest* req = find_app_request( session, request_id );
739         if(req)
740                 return req->complete;
741
742         return 0;
743 }
744
745 /**
746         @brief Reset the remote ID of a session to its original remote ID.
747         @param session Pointer to the osrfAppSession to be reset.
748 */
749 void osrf_app_session_reset_remote( osrfAppSession* session ){
750         if( session==NULL )
751                 return;
752
753         osrfLogDebug( OSRF_LOG_MARK,  "App Session [%s] [%s] resetting remote id to %s",
754                         session->remote_service, session->session_id, session->orig_remote_id );
755
756         osrf_app_session_set_remote( session, session->orig_remote_id );
757 }
758
759 /**
760         @brief Set a session's remote ID to a specified value.
761         @param session Pointer to the osrfAppSession whose remote ID is to be set.
762         @param remote_id Pointer to the new remote id.
763 */
764 void osrf_app_session_set_remote( osrfAppSession* session, const char* remote_id ) {
765         if( session == NULL || remote_id == NULL )
766                 return;
767
768         if( session->remote_id ) {
769                 if( strlen(session->remote_id) >= strlen(remote_id) ) {
770                         // There's enough room; just copy it
771                         strcpy(session->remote_id, remote_id);
772                 } else {
773                         free(session->remote_id );
774                         session->remote_id = strdup( remote_id );
775                 }
776         } else
777                 session->remote_id = strdup( remote_id );
778 }
779
780 /**
781         @brief Append an osrfMessage to the list of responses to an osrfAppRequest.
782         @param session Pointer to the osrfAppSession that owns the request.
783         @param msg Pointer to the osrfMessage to be added.
784
785         The thread_trace member of the osrfMessage is the request_id of the osrfAppRequest.
786         Find the corresponding request in the session and append the osrfMessage to its list.
787 */
788 void osrf_app_session_push_queue( osrfAppSession* session, osrfMessage* msg ) {
789         if( session && msg ) {
790                 osrfAppRequest* req = find_app_request( session, msg->thread_trace );
791                 if( req )
792                         _osrf_app_request_push_queue( req, msg );
793         }
794 }
795
796 /**
797         @brief Connect to the remote service.
798         @param session Pointer to the osrfAppSession for the service.
799         @return 1 if successful, or 0 if not.
800
801         If already connected, exit immediately, reporting success.  Otherwise, build a CONNECT
802         message and send it to the service.  Wait for up to five seconds for an acknowledgement.
803
804         The timeout value is currently hard-coded.  Perhaps it should be configurable.
805 */
806 int osrfAppSessionConnect( osrfAppSession* session ) {
807
808         if(session == NULL)
809                 return 0;
810
811         if(session->state == OSRF_SESSION_CONNECTED) {
812                 return 1;
813         }
814
815         int timeout = 5; /* XXX CONFIG VALUE */
816
817         osrfLogDebug( OSRF_LOG_MARK,  "AppSession connecting to %s", session->remote_id );
818
819         /* defaulting to protocol 1 for now */
820         osrfMessage* con_msg = osrf_message_init( CONNECT, session->thread_trace, 1 );
821
822         // Address this message to the router
823         osrf_app_session_reset_remote( session );
824         session->state = OSRF_SESSION_CONNECTING;
825         int ret = _osrf_app_session_send( session, con_msg );
826         osrfMessageFree(con_msg);
827         if(ret)
828                 return 0;
829
830         time_t start = time(NULL);
831         time_t remaining = (time_t) timeout;
832
833         // Wait for the acknowledgement.  We look for it repeatedly because, under the covers,
834         // we may receive and process messages other than the one we're looking for.
835         while( session->state != OSRF_SESSION_CONNECTED && remaining >= 0 ) {
836                 osrf_app_session_queue_wait( session, remaining, NULL );
837                 if(session->transport_error) {
838                         osrfLogError(OSRF_LOG_MARK, "cannot communicate with %s", session->remote_service);
839                         return 0;
840                 }
841                 remaining -= (int) (time(NULL) - start);
842         }
843
844         if(session->state == OSRF_SESSION_CONNECTED)
845                 osrfLogDebug( OSRF_LOG_MARK, " * Connected Successfully to %s", session->remote_service );
846
847         if(session->state != OSRF_SESSION_CONNECTED)
848                 return 0;
849
850         return 1;
851 }
852
853 /**
854         @brief Disconnect from the remote service.  No response is expected.
855         @param session Pointer to the osrfAppSession to be disconnected.
856         @return 1 in all cases.
857
858         If we're already disconnected, return immediately without doing anything.  Likewise if
859         we have a stateless session and we're in the process of connecting.  Otherwise, send a
860         DISCONNECT message to the service.
861 */
862 int osrf_app_session_disconnect( osrfAppSession* session){
863         if(session == NULL)
864                 return 1;
865
866         if(session->state == OSRF_SESSION_DISCONNECTED)
867                 return 1;
868
869         if(session->stateless && session->state != OSRF_SESSION_CONNECTED) {
870                 osrfLogDebug( OSRF_LOG_MARK,
871                                 "Exiting disconnect on stateless session %s",
872                                 session->session_id);
873                 return 1;
874         }
875
876         osrfLogDebug(OSRF_LOG_MARK,  "AppSession disconnecting from %s", session->remote_id );
877
878         osrfMessage* dis_msg = osrf_message_init( DISCONNECT, session->thread_trace, 1 );
879         _osrf_app_session_send( session, dis_msg );
880         session->state = OSRF_SESSION_DISCONNECTED;
881
882         osrfMessageFree( dis_msg );
883         osrf_app_session_reset_remote( session );
884         return 1;
885 }
886
887 /**
888         @brief Resend a request message, as specified by session and request id.
889         @param session Pointer to the osrfAppSession.
890         @param req_id Request ID for the request to be resent.
891         @return Zero if successful, or if the specified request cannot be found; 1 if the
892         request is already complete, or if the attempt to resend the message fails.
893
894         The choice of return codes may seem seem capricious, but at this writing nothing
895         pays any attention to the return code anyway.
896 */
897 int osrf_app_session_request_resend( osrfAppSession* session, int req_id ) {
898         osrfAppRequest* req = find_app_request( session, req_id );
899
900         int rc;
901         if(req == NULL) {
902                 rc = 0;
903         } else if(!req->complete) {
904                 osrfLogDebug( OSRF_LOG_MARK, "Resending request [%d]", req->request_id );
905                 rc = _osrf_app_session_send( req->session, req->payload );
906         } else {
907                 rc = 1;
908         }
909
910         return rc;
911 }
912
913 /**
914         @brief Send one or more osrfMessages to the remote service or client.
915         @param session Pointer to the osrfAppSession responsible for sending the message(s).
916         @param msgs Pointer to an array of pointers to osrfMessages.
917         @param size How many messages to send.
918         @return 0 upon success, or -1 upon failure.
919 */
920 static int osrfAppSessionSendBatch( osrfAppSession* session, osrfMessage* msgs[], int size ) {
921
922         if( !(session && msgs && size > 0) ) return -1;
923         int retval = 0;
924
925         osrfMessage* msg = msgs[0];
926
927         if(msg) {
928
929                 // First grab and process any input messages, for any app session.  This gives us
930                 // a chance to see any CONNECT or DISCONNECT messages that may have arrived.  We
931                 // may also see some unrelated messages, but we have to process those sooner or
932                 // later anyway, so we might as well do it now.
933                 osrf_app_session_queue_wait( session, 0, NULL );
934
935                 if(session->state != OSRF_SESSION_CONNECTED)  {
936
937                         if(session->stateless) { /* stateless session always send to the root listener */
938                                 osrf_app_session_reset_remote(session);
939
940                         } else {
941
942                                 /* do an auto-connect if necessary */
943                                 if( ! session->stateless &&
944                                         (msg->m_type != CONNECT) &&
945                                         (msg->m_type != DISCONNECT) &&
946                                         (session->state != OSRF_SESSION_CONNECTED) ) {
947
948                                         if(!osrfAppSessionConnect( session ))
949                                                 return -1;
950                                 }
951                         }
952                 }
953         }
954
955         // Bundle all the osrfMessages into a single transport_message, then send it.
956         char* string = osrfMessageSerializeBatch(msgs, size);
957
958         if( string ) {
959
960                 transport_message* t_msg = message_init(
961                                 string, "", session->session_id, session->remote_id, NULL );
962                 message_set_osrf_xid( t_msg, osrfLogGetXid() );
963
964                 retval = client_send_message( session->transport_handle, t_msg );
965                 if( retval )
966                         osrfLogError(OSRF_LOG_MARK, "client_send_message failed");
967
968                 osrfLogInfo(OSRF_LOG_MARK, "[%s] sent %d bytes of data to %s",
969                         session->remote_service, strlen(string), t_msg->recipient );
970
971                 osrfLogDebug(OSRF_LOG_MARK, "Sent: %s", string );
972
973                 free(string);
974                 message_free( t_msg );
975         }
976
977         return retval;
978 }
979
980 /**
981         @brief Send a single osrfMessage to the remote service or client.
982         @param session Pointer to the osrfAppSession.
983         @param msg Pointer to the osrfMessage to be sent.
984         @return zero upon success, or 1 upon failure.
985
986         A thin wrapper.  Create an array of one element, and pass it to osrfAppSessionSendBatch().
987 */
988 static int _osrf_app_session_send( osrfAppSession* session, osrfMessage* msg ){
989         if( !(session && msg) )
990                 return 1;
991         osrfMessage* a[1];
992         a[0] = msg;
993         return  - osrfAppSessionSendBatch( session, a, 1 );
994 }
995
996
997 /**
998         @brief Wait for any input messages to arrive, and process them as needed.
999         @param session Pointer to the osrfAppSession whose transport_session we will use.
1000         @param timeout How many seconds to wait for the first input message.
1001         @param recvd Pointer to an boolean int.  If you receive at least one message, set the boolean
1002         to true; otherwise set it to false.
1003         @return 0 upon success (even if a timeout occurs), or -1 upon failure.
1004
1005         A thin wrapper for osrf_stack_process().  The timeout applies only to the first
1006         message; process subsequent messages if they are available, but don't wait for them.
1007
1008         The first parameter identifies an osrfApp session, but all we really use it for is to
1009         get a pointer to the transport_session.  Typically, a given process opens only a single
1010         transport_session (to talk to the Jabber server), and all app sessions in that process
1011         use the same transport_session.
1012
1013         Hence this function indiscriminately waits for input messages for all osrfAppSessions
1014         tied to the same Jabber session, not just the one specified.
1015
1016         Dispatch each message to the appropriate processing routine, depending on its type
1017         and contents, and on whether we're acting as a client or as a server for that message.
1018         For example, a response to a request may be appended to the input queue of the
1019         relevant request.  A server session receiving a REQUEST message may execute the
1020         requested method.  And so forth.
1021 */
1022 int osrf_app_session_queue_wait( osrfAppSession* session, int timeout, int* recvd ){
1023         if(session == NULL) return 0;
1024         osrfLogDebug(OSRF_LOG_MARK, "AppSession in queue_wait with timeout %d", timeout );
1025         return osrf_stack_process(session->transport_handle, timeout, recvd);
1026 }
1027
1028 /**
1029         @brief Shut down and destroy an osrfAppSession.
1030         @param session Pointer to the osrfAppSession to be destroyed.
1031
1032         If this is a client session, send a DISCONNECT message.
1033
1034         Remove the session from the global session cache.
1035
1036         Free all associated resources, including any pending osrfAppRequests.
1037 */
1038 void osrfAppSessionFree( osrfAppSession* session ){
1039         if(session == NULL) return;
1040
1041         /* Disconnect */
1042
1043         osrfLogDebug(OSRF_LOG_MARK,  "AppSession [%s] [%s] destroying self and deleting requests",
1044                         session->remote_service, session->session_id );
1045         /* disconnect if we're a client */
1046         if(session->type == OSRF_SESSION_CLIENT
1047                         && session->state != OSRF_SESSION_DISCONNECTED ) {
1048                 osrfMessage* dis_msg = osrf_message_init( DISCONNECT, session->thread_trace, 1 );
1049                 _osrf_app_session_send( session, dis_msg );
1050                 osrfMessageFree(dis_msg);
1051         }
1052
1053         /* Remove self from the global session cache */
1054
1055         osrfHashRemove( osrfAppSessionCache, session->session_id );
1056
1057         /* Free the memory */
1058
1059         if( session->userDataFree && session->userData )
1060                 session->userDataFree(session->userData);
1061
1062         if(session->session_locale)
1063                 free(session->session_locale);
1064
1065         free(session->remote_id);
1066         free(session->orig_remote_id);
1067         free(session->session_id);
1068         free(session->remote_service);
1069
1070         // Free the request hash
1071         int i;
1072         for( i = 0; i < OSRF_REQUEST_HASH_SIZE; ++i ) {
1073                 osrfAppRequest* app = session->request_hash[ i ];
1074                 while( app ) {
1075                         osrfAppRequest* next = app->next;
1076                         _osrf_app_request_free( app );
1077                         app = next;
1078                 }
1079         }
1080         free(session);
1081 }
1082
1083 /**
1084         @brief Wait for a response to a given request, subject to a timeout.
1085         @param session Pointer to the osrfAppSession that owns the request.
1086         @param req_id Request ID for the request.
1087         @param timeout How many seconds to wait.
1088         @return A pointer to the received osrfMessage if one arrives; otherwise NULL.
1089
1090         A thin wrapper.  Given a session and a request ID, look up the corresponding request
1091         and pass it to _osrf_app_request_recv().
1092 */
1093 osrfMessage* osrfAppSessionRequestRecv(
1094                 osrfAppSession* session, int req_id, int timeout ) {
1095         if(req_id < 0 || session == NULL)
1096                 return NULL;
1097         osrfAppRequest* req = find_app_request( session, req_id );
1098         return _osrf_app_request_recv( req, timeout );
1099 }
1100
1101 /**
1102         @brief In response to a specified request, send a payload of data to a client.
1103         @param ses Pointer to the osrfAppSession that owns the request.
1104         @param requestId Request ID of the osrfAppRequest.
1105         @param data Pointer to a jsonObject containing the data payload.
1106         @return 0 upon success, or -1 upon failure.
1107
1108         Translate the jsonObject to a JSON string, and send it wrapped in a RESULT message.
1109
1110         The only failure detected is if either of the two pointer parameters is NULL.
1111 */
1112 int osrfAppRequestRespond( osrfAppSession* ses, int requestId, const jsonObject* data ) {
1113         if( !ses || ! data )
1114                 return -1;
1115
1116         osrfMessage* msg = osrf_message_init( RESULT, requestId, 1 );
1117         osrf_message_set_status_info( msg, NULL, "OK", OSRF_STATUS_OK );
1118         char* json = jsonObjectToJSON( data );
1119
1120         osrf_message_set_result_content( msg, json );
1121         _osrf_app_session_send( ses, msg );
1122
1123         free(json);
1124         osrfMessageFree( msg );
1125
1126         return 0;
1127 }
1128
1129
1130 /**
1131         @brief Send one or two messages to a client in response to a specified request.
1132         @param ses Pointer to the osrfAppSession that owns the request.
1133         @param requestId Request ID of the osrfAppRequest.
1134         @param data Pointer to a jsonObject containing the data payload.
1135         @return  Zero in all cases.
1136
1137         If the @a data parameter is not NULL, translate the jsonObject into a JSON string, and
1138         incorporate that string into a RESULT message as as the payload .  Also build a STATUS
1139         message indicating that the response is complete.  Send both messages bundled together
1140         in the same transport_message.
1141
1142         If the @a data parameter is NULL, send only a STATUS message indicating that the response
1143         is complete.
1144 */
1145 int osrfAppRequestRespondComplete(
1146                 osrfAppSession* ses, int requestId, const jsonObject* data ) {
1147
1148         osrfMessage* status = osrf_message_init( STATUS, requestId, 1);
1149         osrf_message_set_status_info( status, "osrfConnectStatus", "Request Complete",
1150                         OSRF_STATUS_COMPLETE );
1151
1152         if (data) {
1153                 osrfMessage* payload = osrf_message_init( RESULT, requestId, 1 );
1154                 osrf_message_set_status_info( payload, NULL, "OK", OSRF_STATUS_OK );
1155
1156                 char* json = jsonObjectToJSON( data );
1157                 osrf_message_set_result_content( payload, json );
1158                 free(json);
1159
1160                 osrfMessage* ms[2];
1161                 ms[0] = payload;
1162                 ms[1] = status;
1163
1164                 osrfAppSessionSendBatch( ses, ms, 2 );
1165
1166                 osrfMessageFree( payload );
1167         } else {
1168                 osrfAppSessionSendBatch( ses, &status, 1 );
1169         }
1170
1171         osrfMessageFree( status );
1172
1173         return 0;
1174 }
1175
1176 /**
1177         @brief Send a STATUS message, for a specified request, back to the client.
1178         @param ses Pointer to the osrfAppSession connected to the client.
1179         @param type A numeric code denoting the status.
1180         @param name A string naming the status.
1181         @param reqId The request ID of the request.
1182         @param message A brief message describing the status.
1183         @return 0 upon success, or -1 upon failure.
1184
1185         The only detected failure is when the @a ses parameter is NULL.
1186 */
1187 int osrfAppSessionStatus( osrfAppSession* ses, int type,
1188                 const char* name, int reqId, const char* message ) {
1189
1190         if(ses) {
1191                 osrfMessage* msg = osrf_message_init( STATUS, reqId, 1);
1192                 osrf_message_set_status_info( msg, name, message, type );
1193                 _osrf_app_session_send( ses, msg );
1194                 osrfMessageFree( msg );
1195                 return 0;
1196         } else
1197                 return -1;
1198 }
1199
1200 /**
1201         @brief Free the global session cache.
1202
1203         Note that the osrfHash that implements the global session cache does @em not have a
1204         callback function installed for freeing its cargo.  As a result, any remaining
1205         osrfAppSessions are leaked, along with all the osrfAppRequests and osrfMessages they
1206         own.
1207 */
1208 void osrfAppSessionCleanup( void ) {
1209         osrfHashFree(osrfAppSessionCache);
1210         osrfAppSessionCache = NULL;
1211 }
1212
1213 /**
1214         @brief Arrange for immediate termination of the process.
1215         @param ses Pointer to the current osrfAppSession.
1216
1217         Typical use case: a server drone loses its database connection, thereby becoming useless.
1218         It terminates so that it will not receive further requests, being unable to service them.
1219 */
1220 void osrfAppSessionPanic( osrfAppSession* ses ) {
1221         if( ses )
1222                 ses->panic = 1;
1223 }