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 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#include <cassert>
#include <cerrno>
#include <string>
#include <vector>
#include <list>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <readline/readline.h>

#include "cmdline_parser.hpp"
#include "xmlrpc-c/girerr.hpp"
using girerr::throwf;

#ifdef __cplusplus
extern "C" {
#endif

#include "dumpvalue.h"  /* An internal Xmlrpc-c header file ! */

#ifdef __cplusplus
}
#endif

#include <xmlrpc-c/base.hpp>
#include <xmlrpc-c/client.hpp>
#include <xmlrpc-c/client_transport.hpp>

using namespace std;
using namespace xmlrpc_c;

/*----------------------------------------------------------------------------
   Command line
-----------------------------------------------------------------------------*/

class cmdlineInfo {
public:
    int            serverfd;
    bool           interactive;

    // Valid only if !interactive:
    string         methodName;
    vector<string> params;

    cmdlineInfo(int           const argc,
                const char ** const argv);

private:
    cmdlineInfo();
};



static void
parseCommandLine(cmdlineInfo * const cmdlineP,
                 int           const argc,
                 const char ** const argv) {

    CmdlineParser cp;

    cp.defineOption("serverfd",       CmdlineParser::UINT);

    try {
        cp.processOptions(argc, argv);
    } catch (exception const& e) {
        throwf("Command syntax error.  %s", e.what());
    }

    if (cp.optionIsPresent("serverfd")) {
        cmdlineP->serverfd = cp.getOptionValueUint("serverfd");
    } else
        cmdlineP->serverfd = 3;
    
    if (cp.argumentCount() < 1)
        cmdlineP->interactive = true;
    else {
        cmdlineP->interactive = false;
        cmdlineP->methodName = cp.getArgument(0);
        for (uint argI = 1; argI < cp.argumentCount(); ++argI)
            cmdlineP->params.push_back(cp.getArgument(argI));
    }            
}



cmdlineInfo::
cmdlineInfo(int           const argc,
            const char ** const argv) {

    try {
        parseCommandLine(this, argc, argv);
    } catch (exception const& e) {
        throwf("Command syntax error.  %s", e.what());
    }
}



static value
bytestringValFromParm(string const& valueString) {

    value retval;

    if (valueString.length() / 2 * 2 != valueString.length())
        throwf("Hexadecimal text is not an even "
               "number of characters (it is %u characters)",
               (unsigned)valueString.length());
    else {
        vector<unsigned char> byteString(valueString.length() / 2);
        size_t strCursor;

        strCursor = 0;

        while (strCursor < valueString.length()) {
            string const hexByte(valueString.substr(strCursor, 2));

            unsigned char byte;
            int rc;

            rc = sscanf(hexByte.c_str(), "%2hhx", &byte);

            byteString.push_back(byte);

            if (rc != 1)
                throwf("Invalid hex data '%s'", hexByte.c_str());
            else
                strCursor += 2;
        }
        retval = value_bytestring(byteString);
    }
    return retval;
}



static value
intValFromParm(string const& valueString) {

    value retval;

    if (valueString.length() < 1)
        throwf("Integer argument has nothing after the 'i/'");
    else {
        long longValue;
        char * tailptr;

        errno = 0;
        
        longValue = strtol(valueString.c_str(), &tailptr, 10);

        if (errno == ERANGE)
            throwf("'%s' is out of range for a 32 bit integer",
                   valueString.c_str());
        else if (errno != 0)
            throwf("Mysterious failure of strtol(), errno=%d (%s)",
                   errno, strerror(errno));
        else {
            if (*tailptr != '\0')
                throwf("Integer argument has non-digit crap in it: '%s'",
                       tailptr);
            else
                retval = value_int(longValue);
        }
    }
    return retval;
}



static value
boolValFromParm(string const& valueString) {

    value retval;

    if (valueString == "t" || valueString == "true")
        retval = value_boolean(true);
    else if (valueString == "f" || valueString == "false")
        retval = value_boolean(false);
    else
        throwf("Boolean argument has unrecognized value '%s'.  "
               "recognized values are 't', 'f', 'true', and 'false'.",
               valueString.c_str());

    return retval;
} 



static value
doubleValFromParm(string const& valueString) {

    value retval;

    if (valueString.length() < 1)
        throwf("\"Double\" argument has nothing after the 'd/'");
    else {
        double value;
        char * tailptr;

        value = strtod(valueString.c_str(), &tailptr);

        if (*tailptr != '\0')
            throwf("\"Double\" argument has non-decimal crap in it: '%s'",
                   tailptr);
        else
            retval = value_double(value);
    }
    return retval;
}



static value
nilValFromParm(string const& valueString) {

    value retval;

    if (valueString.length() > 0)
        throwf("Nil argument has something after the 'n/'");
    else
        retval = value_nil();

    return retval;
}



static value
i8ValFromParm(string  const& valueString) {

    value retval;

    if (valueString.length() < 1)
        throwf("Integer argument has nothing after the 'I/'");
    else {
        long long value;
        char * tailptr;
        
        errno = 0;

        value = strtoll(valueString.c_str(), &tailptr, 10);

        if (errno == ERANGE)
            throwf("'%s' is out of range for a 64 bit integer",
                   valueString.c_str());
        else if (errno != 0)
            throwf("Mysterious failure of strtoll(), errno=%d (%s)",
                   errno, strerror(errno));
        else {
            if (*tailptr != '\0')
                throwf("64 bit integer argument has non-digit crap "
                       "in it: '%s'",
                       tailptr);
            else
                retval = value_i8(value);
        }
    }
    return retval;
}



static value
parameterFromArg(string  const& paramArg) {

    value param;

    try {
        if (paramArg.substr(0, 2) == "s/")
            param = value_string(paramArg.substr(2));
        else if (paramArg.substr(0, 2) == "h/")
            param = bytestringValFromParm(paramArg.substr(2));
        else if (paramArg.substr(0, 2) == "i/")
            param = intValFromParm(paramArg.substr(2));
        else if (paramArg.substr(0, 2) == "I/")
            param = i8ValFromParm(paramArg.substr(2));
        else if (paramArg.substr(0, 2) == "d/")
            param = doubleValFromParm(paramArg.substr(2));
        else if (paramArg.substr(0, 2) == "b/")
            param = boolValFromParm(paramArg.substr(2));
        else if (paramArg.substr(0, 2) == "n/")
            param = nilValFromParm(paramArg.substr(2));
        else {
            /* It's not in normal type/value format, so we take it to be
               the shortcut string notation 
            */
            param = value_string(paramArg);
        }
    } catch (exception const& e) {
        throwf("Failed to interpret parameter argument '%s'.  %s",
               paramArg.c_str(), e.what());
    }
    return param;
}



static paramList
paramListFromParamArgs(vector<string> const& params) {
    
    paramList paramList;

    for (vector<string>::const_iterator p = params.begin();
         p != params.end(); ++p)
        paramList.add(parameterFromArg(*p));

    return paramList;
}



static void
callWithClient(client *  const  clientP,
               string    const& methodName,
               paramList const& paramList,
               value *   const  resultP) {
               
    rpcPtr myRpcP(methodName, paramList);

    carriageParm_pstream myCarriageParm;  // Empty - no parm needed

    try {
        myRpcP->call(clientP, &myCarriageParm);
    } catch (exception const& e) {
        throwf("RPC failed.  %s", e.what());
    }
    *resultP = myRpcP->getResult();
}



static void
dumpResult(value const& result) {

    cout << "Result:" << endl << endl;

    /* Here we borrow code from inside Xmlrpc-c, and also use an
       internal interface of xmlrpc_c::value.  This sliminess is one
       reason that this is Bryan's private code instead of part of the
       Xmlrpc-c package.
       
       Note that you must link with the dumpvalue.o object module from
       inside an Xmlrpc-c build tree.
    */

    dumpValue("", result.cValueP);
}



static list<string>
parseWordList(string const& wordString) {

    list<string> retval;

    unsigned int pos;

    pos = 0;

    while (pos < wordString.length()) {
        pos = wordString.find_first_not_of(' ', pos);

        if (pos < wordString.length()) {
            unsigned int const end = wordString.find_first_of(' ', pos);

            retval.push_back(wordString.substr(pos, end - pos));

            pos = end;
        }
    }
    return retval;
}
              


static void
parseCommand(string           const& cmd,
             string *         const  methodNameP,
             vector<string> * const  paramListP) {

    list<string> const wordList(parseWordList(cmd));

    list<string>::const_iterator cmdWordP;

    cmdWordP = wordList.begin();

    if (cmdWordP == wordList.end())
        throwf("Command '%s' does not have a method name", cmd.c_str());
    else {
        *methodNameP = *cmdWordP++;

        *paramListP = vector<string>();  // Start empty
        
        while (cmdWordP != wordList.end())
            paramListP->push_back(*cmdWordP++);
    }
}



static void
doCommand(client_xml *   const  clientP,
          string         const& methodName,
          vector<string> const& paramArgs) {

    value result;

    callWithClient(clientP, methodName, paramListFromParamArgs(paramArgs),
                   &result);

    try {
        dumpResult(result);
    } catch(exception const& e) {
        throwf("Error showing result after RPC completed normally.  %s",
               e.what());
    }
}



static void
getCommand(string * const cmdP,
           bool*    const eofP) {

    const char * cmd;

    cmd = readline(">");

    *eofP = (cmd == NULL);

    if (cmd != NULL) {
        *cmdP = string(cmd);

        free(const_cast<char *>(cmd));
    }
}



static void
doInteractive(client_xml * const clientP) {

    bool quitRequested;

    quitRequested = false;

    while (!quitRequested) {
        string cmd;
        bool eof;

        getCommand(&cmd, &eof);

        if (eof) {
            quitRequested = true;
            cout << endl;
        } else {
            try {
                string methodName;
                vector<string> paramArgs;

                parseCommand(cmd, &methodName, &paramArgs);

                doCommand(clientP, methodName, paramArgs);
            } catch (exception const& e) {
                cout << "Command failed.  " << e.what() << endl;
            }
        }
    }
}



int 
main(int           const argc, 
     const char ** const argv) {

    try {
        cmdlineInfo cmdline(argc, argv);

        signal(SIGPIPE, SIG_IGN);

        clientXmlTransport_pstream myTransport(
            clientXmlTransport_pstream::constrOpt()
            .fd(cmdline.serverfd));

        client_xml myClient(&myTransport);

        if (cmdline.interactive) {
            if (cmdline.serverfd == STDIN_FILENO ||
                cmdline.serverfd == STDOUT_FILENO)
                throwf("Can't use Stdin or Stdout for the server fd when "
                       "running interactively.");
            doInteractive(&myClient);
        } else
            doCommand(&myClient, cmdline.methodName, cmdline.params);

    } catch (exception const& e) {
        cerr << "Failed.  " << e.what() << endl;
    } catch (...) {
        cerr << "Code threw unrecognized exception" << endl;
        abort();
    }
    return 0;
}