Yet another WIN32 fix for connect notify.
[yazpp-moved-to-github.git] / src / yaz-client.cpp
1 /*
2  * Copyright (c) 1998-2000, Index Data.
3  * See the file LICENSE for details.
4  * 
5  * $Log: yaz-client.cpp,v $
6  * Revision 1.16  2000-11-01 14:22:59  adam
7  * Added fd parameter for method IYaz_PDU_Observer::clone.
8  *
9  * Revision 1.15  2000/10/11 11:58:16  adam
10  * Moved header files to include/yaz++. Switched to libtool and automake.
11  * Configure script creates yaz++-config script.
12  *
13  * Revision 1.14  2000/09/08 10:23:42  adam
14  * Added skeleton of yaz-z-server.
15  *
16  * Revision 1.13  2000/09/06 14:23:45  adam
17  * WIN32 updates.
18  *
19  * Revision 1.12  2000/09/04 08:59:16  adam
20  * Changed call to logging functions (yaz_ added).
21  *
22  * Revision 1.11  2000/07/04 13:48:49  adam
23  * Implemented upper-limit on proxy-to-target sessions.
24  *
25  * Revision 1.10  2000/05/30 03:12:27  ian
26  * minor change to stop g++ 2.95.2 complaining about taking the address
27  * of a member function.
28  *
29  * Revision 1.9  1999/12/06 13:52:45  adam
30  * Modified for new location of YAZ header files. Experimental threaded
31  * operation.
32  *
33  * Revision 1.8  1999/11/10 10:02:34  adam
34  * Work on proxy.
35  *
36  * Revision 1.7  1999/04/21 12:09:01  adam
37  * Many improvements. Modified to proxy server to work with "sessions"
38  * based on cookies.
39  *
40  * Revision 1.6  1999/04/20 10:30:05  adam
41  * Implemented various stuff for client and proxy. Updated calls
42  * to ODR to reflect new name parameter.
43  *
44  * Revision 1.5  1999/04/09 11:46:57  adam
45  * Added object Yaz_Z_Assoc. Much more functional client.
46  *
47  * Revision 1.4  1999/03/23 14:17:57  adam
48  * More work on timeout handling. Work on yaz-client.
49  *
50  * Revision 1.3  1999/02/02 14:01:18  adam
51  * First WIN32 port of YAZ++.
52  *
53  * Revision 1.2  1999/01/28 13:08:42  adam
54  * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
55  * yaz-socket-manager.cc.
56  *
57  * Revision 1.1.1.1  1999/01/28 09:41:07  adam
58  * First implementation of YAZ++.
59  *
60  */
61
62 #include <yaz/log.h>
63 #include <yaz/options.h>
64 #include <yaz/diagbib1.h>
65 #include <yaz++/yaz-ir-assoc.h>
66 #include <yaz++/yaz-pdu-assoc.h>
67 #include <yaz++/yaz-socket-manager.h>
68
69 extern "C" {
70 #if HAVE_READLINE_READLINE_H
71 #include <readline/readline.h>
72 #endif
73 #if HAVE_READLINE_HISTORY_H
74 #include <readline/history.h>
75 #endif
76 }
77
78 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
79 private:
80     int m_interactive_flag;
81     char m_thisCommand[1024];
82     char m_lastCommand[1024];
83     int m_setOffset;
84     Yaz_SocketManager *m_socketManager;
85 public:
86     MyClient(IYaz_PDU_Observable *the_PDU_Observable,
87              Yaz_SocketManager *the_SocketManager);
88     IYaz_PDU_Observer *clone(IYaz_PDU_Observable *the_PDU_Observable, int fd);
89     int args(Yaz_SocketManager *socketManager, int argc, char **argv);
90     int interactive(Yaz_SocketManager *socketManager);
91     int wait();
92     void recv_initResponse(Z_InitResponse *initResponse);
93     void recv_searchResponse(Z_SearchResponse *searchResponse);
94     void recv_presentResponse(Z_PresentResponse *presentResponse);
95     void recv_records (Z_Records *records);
96     void recv_diagrecs(Z_DiagRec **pp, int num);
97     void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
98     void recv_record(Z_DatabaseRecord *record, int offset,
99                      const char *databaseName);
100     void recv_textRecord(int type, const char *buf, size_t len);
101     void recv_genericRecord(Z_GenericRecord *r);
102     void display_genericRecord(Z_GenericRecord *r, int level);
103     void display_variant(Z_Variant *v, int level);
104     void connectNotify();
105     void failNotify();
106     void timeoutNotify();
107     char *get_cookie (Z_OtherInformation **oi);
108     int processCommand(const char *cmd);
109     const char *MyClient::getCommand();
110     int cmd_open(char *host);
111     int cmd_connect(char *host);
112     int cmd_quit(char *args);
113     int cmd_close(char *args);
114     int cmd_find(char *args);
115     int cmd_show(char *args);
116     int cmd_cookie(char *args);
117     int cmd_init(char *args);
118     int cmd_format(char *args);
119     int cmd_proxy(char *args);
120 };
121
122
123 void MyClient::connectNotify()
124 {
125     printf ("Connection accepted by target\n");
126     set_lastReceived(-1);
127 }
128
129 void MyClient::timeoutNotify()
130 {
131     printf ("Connection timeout\n");
132     close();
133 }
134
135 void MyClient::failNotify()
136 {
137     printf ("Connection closed by target\n");
138     set_lastReceived(-1);
139 }
140
141 IYaz_PDU_Observer *MyClient::clone(IYaz_PDU_Observable *the_PDU_Observable,
142                                    int fd)
143
144     return new MyClient(the_PDU_Observable, m_socketManager);
145 }
146
147 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
148                    Yaz_SocketManager *the_socketManager) :
149     Yaz_IR_Assoc (the_PDU_Observable)
150 {
151     m_setOffset = 1;
152     m_interactive_flag = 1;
153     m_thisCommand[0] = '\0';
154     m_lastCommand[0] = '\0';
155     m_socketManager = the_socketManager;
156 }
157
158 void usage(char *prog)
159 {
160     fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
161     exit (1);
162 }
163
164 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
165 {
166     int oid[OID_SIZE];
167     Z_OtherInformationUnit *oi;
168     struct oident ent;
169     ent.proto = PROTO_Z3950;
170     ent.oclass = CLASS_USERINFO;
171     ent.value = (oid_value) VAL_COOKIE;
172
173     if (oid_ent_to_oid (&ent, oid) && 
174         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
175         oi->which == Z_OtherInfo_characterInfo)
176         return oi->information.characterInfo;
177     return 0;
178 }
179
180 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
181 {
182     printf ("Got InitResponse. Status ");
183     if (*initResponse->result)
184     {
185         printf ("Ok\n");
186
187         const char *p = get_cookie (&initResponse->otherInfo);
188         if (p)
189         {
190             printf ("cookie = %s\n", p);
191             set_cookie(p);
192         }
193     }
194     else
195         printf ("Fail\n");
196 }
197
198 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
199 {
200     int i;
201     oident *ent;
202     Z_DefaultDiagFormat *r;
203
204     printf("Diagnostic message(s) from database:\n");
205     for (i = 0; i<num; i++)
206     {
207         Z_DiagRec *p = pp[i];
208         if (p->which != Z_DiagRec_defaultFormat)
209         {
210             printf("Diagnostic record not in default format.\n");
211             return;
212         }
213         else
214             r = p->u.defaultFormat;
215         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
216             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
217             printf("Missing or unknown diagset\n");
218         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
219 #ifdef ASN_COMPILED
220         switch (r->which)
221         {
222         case Z_DefaultDiagFormat_v2Addinfo:
223             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
224             break;
225         case Z_DefaultDiagFormat_v3Addinfo:
226             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
227             break;
228         }
229 #else
230         if (r->addinfo && *r->addinfo)
231             printf(" -- '%s'\n", r->addinfo);
232         else
233             printf("\n");
234 #endif
235     }
236 }
237
238 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
239 {
240     fwrite (buf, 1, len, stdout);
241     fputc ('\n', stdout);
242 }
243
244 void MyClient::display_variant(Z_Variant *v, int level)
245 {
246     int i;
247
248     for (i = 0; i < v->num_triples; i++)
249     {
250         printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
251             *v->triples[i]->type);
252         if (v->triples[i]->which == Z_Triple_internationalString)
253             printf(",value=%s\n", v->triples[i]->value.internationalString);
254         else
255             printf("\n");
256     }
257 }
258
259 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
260 {
261     int i;
262
263     if (!r)
264         return;
265     for (i = 0; i < r->num_elements; i++)
266     {
267         Z_TaggedElement *t;
268
269         printf("%*s", level * 4, "");
270         t = r->elements[i];
271         printf("(");
272         if (t->tagType)
273             printf("%d,", *t->tagType);
274         else
275             printf("?,");
276         if (t->tagValue->which == Z_StringOrNumeric_numeric)
277             printf("%d) ", *t->tagValue->u.numeric);
278         else
279             printf("%s) ", t->tagValue->u.string);
280         if (t->content->which == Z_ElementData_subtree)
281         {
282             printf("\n");
283             display_genericRecord(t->content->u.subtree, level+1);
284         }
285         else if (t->content->which == Z_ElementData_string)
286             printf("%s\n", t->content->u.string);
287         else if (t->content->which == Z_ElementData_numeric)
288             printf("%d\n", *t->content->u.numeric);
289         else if (t->content->which == Z_ElementData_oid)
290         {
291             int *ip = t->content->u.oid;
292             oident *oent;
293
294             if ((oent = oid_getentbyoid(t->content->u.oid)))
295                 printf("OID: %s\n", oent->desc);
296             else
297             {
298                 printf("{");
299                 while (ip && *ip >= 0)
300                     printf(" %d", *(ip++));
301                 printf(" }\n");
302             }
303         }
304         else if (t->content->which == Z_ElementData_noDataRequested)
305             printf("[No data requested]\n");
306         else if (t->content->which == Z_ElementData_elementEmpty)
307             printf("[Element empty]\n");
308         else if (t->content->which == Z_ElementData_elementNotThere)
309             printf("[Element not there]\n");
310         else
311             printf("??????\n");
312         if (t->appliedVariant)
313             display_variant(t->appliedVariant, level+1);
314         if (t->metaData && t->metaData->supportedVariants)
315         {
316             int c;
317
318             printf("%*s---- variant list\n", (level+1)*4, "");
319             for (c = 0; c < t->metaData->num_supportedVariants; c++)
320             {
321                 printf("%*svariant #%d\n", (level+1)*4, "", c);
322                 display_variant(t->metaData->supportedVariants[c], level + 2);
323             }
324         }
325     }
326 }
327
328 void MyClient::recv_genericRecord(Z_GenericRecord *r)
329 {
330     display_genericRecord(r, 0);
331 }
332
333 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
334                            const char *databaseName)
335 {
336     Z_External *r = (Z_External*) record;
337     oident *ent = oid_getentbyoid(r->direct_reference);
338
339     /*
340      * Tell the user what we got.
341      */
342     if (r->direct_reference)
343     {
344         printf("Record type: ");
345         if (ent)
346             printf("%s\n", ent->desc);
347     }
348     /* Check if this is a known, ASN.1 type tucked away in an octet string */
349     Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
350     if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
351         && (etype = z_ext_getentbyref(ent->value)))
352
353     {
354         void *rr;
355         /*
356          * Call the given decoder to process the record.
357          */
358         odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
359                    record->u.octet_aligned->len, 0);
360         if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
361         {
362             odr_perror(odr_decode(), "Decoding constructed record.");
363             fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
364             fprintf(stderr, "Packet dump:\n---------\n");
365             odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
366                         record->u.octet_aligned->len);
367             fprintf(stderr, "---------\n");
368         }
369         if (etype->what == Z_External_sutrs)
370         {
371             Z_SUTRS *sutrs = (Z_SUTRS *) rr;
372             recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
373                              (size_t) sutrs->len);
374         }
375         return;
376     }
377     if (r->which == Z_External_octet && record->u.octet_aligned->len)
378     {
379         recv_textRecord((int) ent->value,
380                         (const char *) record->u.octet_aligned->buf,
381                         (size_t) record->u.octet_aligned->len);
382     }
383     else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
384         recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
385                         (size_t) r->u.sutrs->len);
386     else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
387         recv_genericRecord(r->u.grs1);
388     else 
389     {
390         printf("Unknown record representation.\n");
391         if (!z_External(odr_print(), &r, 0, 0))
392         {
393             odr_perror(odr_print(), "Printing external");
394             odr_reset(odr_print());
395         }
396     }    
397 }
398
399 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
400 {
401     if (zpr->databaseName)
402         printf("[%s]", zpr->databaseName);
403     if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
404         recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
405     else
406         recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
407 }
408
409 void MyClient::recv_records (Z_Records *records)
410 {
411 #ifdef ASN_COMPILED
412     Z_DiagRec dr, *dr_p = &dr;
413 #endif
414     if (!records)
415         return;
416     int i;
417     switch (records->which)
418     {
419     case Z_Records_DBOSD:
420         for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
421             recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
422                                 records[i], i + m_setOffset);
423         m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
424         break;
425     case Z_Records_NSD:
426 #ifdef ASN_COMPILED
427         dr.which = Z_DiagRec_defaultFormat;
428         dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
429         recv_diagrecs (&dr_p, 1);
430 #else
431         recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
432 #endif
433         break;
434     case Z_Records_multipleNSD:
435         recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
436                        records->u.multipleNonSurDiagnostics->num_diagRecs);
437         break;
438     }
439 }
440
441 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
442 {
443     printf ("Got SearchResponse. Status ");
444     if (!*searchResponse->searchStatus)
445     {
446         printf ("Fail\n");
447         return;
448     }
449     printf ("Ok\n");
450     printf ("Hits: %d\n", *searchResponse->resultCount);
451     recv_records (searchResponse->records);
452 }
453
454 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
455 {
456     printf ("Got PresentResponse\n");
457     recv_records (presentResponse->records);
458 }
459
460 int MyClient::wait()
461 {
462     set_lastReceived(0);
463     while (m_socketManager->processEvent() > 0)
464     {
465         if (get_lastReceived())
466             return 1;
467     }
468     return 0;
469 }
470
471 #define C_PROMPT "Z>"
472
473 int MyClient::cmd_connect(char *host)
474 {
475     client (host);
476     timeout (10);
477     wait ();
478     timeout (0);
479     return 1;
480 }
481
482 int MyClient::cmd_open(char *host)
483 {
484     client (host);
485     timeout (10);
486     wait ();
487     timeout (0);
488     send_initRequest();
489     wait ();
490     return 1;
491 }
492
493 int MyClient::cmd_init(char *args)
494 {
495     if (send_initRequest() >= 0)
496         wait();
497     else
498         close();
499     return 1;
500 }
501
502 int MyClient::cmd_quit(char *args)
503 {
504     return 0;
505 }
506
507 int MyClient::cmd_close(char *args)
508 {
509     close();
510     return 1;
511 }
512
513 int MyClient::cmd_find(char *args)
514 {
515     Yaz_Z_Query query;
516
517     if (query.set_rpn(args) <= 0)
518     {
519         printf ("Bad RPN query\n");
520         return 1;
521     }
522     if (send_searchRequest(&query) >= 0)
523         wait();
524     else
525         printf ("Not connected\n");
526     return 1;
527 }
528
529 int MyClient::cmd_show(char *args)
530 {
531     int start = m_setOffset, number = 1;
532
533     sscanf (args, "%d %d", &start, &number);
534     m_setOffset = start;
535     if (send_presentRequest(start, number) >= 0)
536         wait();
537     else
538         printf ("Not connected\n");
539     return 1;
540 }
541
542 int MyClient::cmd_cookie(char *args)
543 {
544     set_cookie(*args ? args : 0);
545     return 1;
546 }
547
548 int MyClient::cmd_format(char *args)
549 {
550     set_preferredRecordSyntax(args);
551     return 1;
552 }
553
554 int MyClient::cmd_proxy(char *args)
555 {
556     set_proxy(args);
557     return 1;
558 }
559
560 int MyClient::processCommand(const char *commandLine)
561 {
562     char cmdStr[1024], cmdArgs[1024];
563     cmdArgs[0] = '\0';
564     cmdStr[0] = '\0';
565     static struct {
566         char *cmd;
567         int (MyClient::*fun)(char *arg);
568         char *ad;
569     } cmd[] = {
570         {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
571         {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
572         {"quit", &MyClient::cmd_quit, ""},
573         {"close", &MyClient::cmd_close, ""},
574         {"find", &MyClient::cmd_find, "<query>"},
575         {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
576         {"cookie", &MyClient::cmd_cookie, "<cookie>"},
577         {"init", &MyClient::cmd_init, ""},
578         {"format", &MyClient::cmd_format, "<record-syntax>"},
579         {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
580         {0,0,0}
581     };
582     
583     if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
584         return 1;
585     int i;
586     for (i = 0; cmd[i].cmd; i++)
587         if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
588             break;
589     
590     int res = 1;
591     if (cmd[i].cmd) // Invoke command handler
592         res = (this->*cmd[i].fun)(cmdArgs);
593     else            // Dump help screen
594     {
595         printf("Unknown command: %s.\n", cmdStr);
596         printf("Currently recognized commands:\n");
597         for (i = 0; cmd[i].cmd; i++)
598             printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
599     }
600     return res;
601 }
602
603 const char *MyClient::getCommand()
604 {
605 #if HAVE_READLINE_READLINE_H
606     // Read using GNU readline
607     char *line_in;
608     line_in=readline(C_PROMPT);
609     if (!line_in)
610         return 0;
611 #if HAVE_READLINE_HISTORY_H
612     if (*line_in)
613         add_history(line_in);
614 #endif
615     strncpy(m_thisCommand,line_in, 1023);
616     m_thisCommand[1023] = '\0';
617     free (line_in);
618 #else    
619     // Read using fgets(3)
620     printf (C_PROMPT);
621     fflush(stdout);
622     if (!fgets(m_thisCommand, 1023, stdin))
623         return 0;
624 #endif
625     // Remove trailing whitespace
626     char *cp = m_thisCommand + strlen(m_thisCommand);
627     while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
628         cp--;
629     *cp = '\0';
630     cp = m_thisCommand;
631     // Remove leading spaces...
632     while (*cp && strchr ("\t \n", *cp))
633         cp++;
634     // Save command if non-empty
635     if (*cp != '\0')
636         strcpy (m_lastCommand, cp);
637     return m_lastCommand;
638 }
639
640 int MyClient::interactive(Yaz_SocketManager *socketManager)
641 {
642     const char *cmd;
643     if (!m_interactive_flag)
644         return 0;
645     while ((cmd = getCommand()))
646     {
647         if (!processCommand(cmd))
648             break;
649     }
650     return 0;
651 }
652
653 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
654 {
655     char *host = 0;
656     char *proxy = 0;
657     char *arg;
658     char *prog = argv[0];
659     int ret;
660
661     while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
662     {
663         switch (ret)
664         {
665         case 0:
666             if (host)
667             {
668                 usage(prog);
669                 return 1;
670             }
671             host = arg;
672             break;
673         case 'p':
674             if (proxy)
675             {
676                 usage(prog);
677                 return 1;
678             }
679             set_proxy(arg);
680             break;
681         case 'c':
682             set_cookie(arg);
683             break;
684         case 'v':
685             yaz_log_init_level (yaz_log_mask_str(arg));
686             break;
687         case 'q':
688             m_interactive_flag = 0;
689             break;
690         default:
691             usage(prog);
692             return 1;
693         }
694     }
695     if (host)
696     {
697         client (host);
698         timeout (10);
699         wait ();
700         timeout (0);
701         send_initRequest();
702         wait ();
703     }
704     return 0;
705 }
706
707 int main(int argc, char **argv)
708 {
709     Yaz_SocketManager mySocketManager;
710     Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
711
712     MyClient z(some, &mySocketManager);
713
714     if (z.args(&mySocketManager, argc, argv))
715         exit (1);
716     if (z.interactive(&mySocketManager))
717         exit (1);
718     return 0;
719 }