aboutsummaryrefslogtreecommitdiff
path: root/client/client.c
blob: 9bd0d3051167638dea5e681ae0160c0e18ce56f8 (plain)
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <getopt.h>
#include <libgen.h>
#include <stdarg.h>
#include <errno.h>

#include <glib.h>
#include <dbus/dbus.h>
#include <dbus/dbus-glib-lowlevel.h>

#include <res-conn.h>

#define REQHASH_BITS     6
#define REQHASH_DIM      (1 << REQHASH_BITS)
#define REQHASH_MASK     (REQHASH_DIM - 1)
#define REQHASH_INDEX(r) ((r) & REQHASH_MASK)


typedef struct {
    int             trace;
    uint32_t        id;
    char           *class;
    uint32_t        mode;
    resmsg_rset_t   rset;
    int             verbose;
} conf_t;

typedef struct {
    uint32_t        value;
    const char     *name;
} rdef_t;

typedef struct {
    uint32_t        value;
    const char     *name;
} mdef_t;

typedef struct {
    GIOChannel     *chan;
    guint           evsrc;
    int             accept;
    char            buf[256];
    int             len;        /* buffer length */
} input_t;

static void     install_signal_handlers(void);
static void     signal_handler(int, siginfo_t *, void *);

static void     create_mainloop(void);
static void     destroy_mainloop(void);
static void     run_mainloop(void);

static void     create_input(void);
static void     destroy_input(void);
static void     accept_input(int);
static void     print_input(void);
static void     parse_input(void);
static gboolean input_cb(GIOChannel *, GIOCondition, gpointer);

static void     create_dbus(void);
static void     destroy_dbus(void);

static void     create_manager(void);
static void     destroy_manager();
static void     connect_to_manager(resconn_t *);
static void     manager_status(resset_t *, resmsg_t *);
static void     manager_receive_message(resmsg_t *, resset_t *, void *);
static void     manager_send_message(resmsg_t *);

static void     print_error(char *, ...);
static void     print_message(char *fmt, ...);

static void     usage(int);
static void     parse_options(int, char **);
static char    *parse_class_string(char *);
static uint32_t parse_resource_list(char *, int);
static uint32_t parse_mode_values(char *, int);


static char            *exe_name = "";
static conf_t           config;
static GMainLoop       *main_loop;
static input_t          input;
static DBusConnection  *dconn;
static resconn_t       *rconn;
static resset_t        *rset;
static uint32_t         rid;
static uint32_t         reqno; 
static resmsg_type_t    reqtyp[REQHASH_DIM];

int main(int argc, char **argv)
{
    parse_options(argc, argv);
    install_signal_handlers();

    create_mainloop();
    create_input();
    create_dbus();
    create_manager();

    run_mainloop();

    print_message("exiting now ...");

    destroy_manager();
    destroy_dbus();
    destroy_input();
    destroy_mainloop();


  return 0;
}


static void install_signal_handlers(void)
{
    struct sigaction sa;

    memset(&sa, 0, sizeof(struct sigaction));
    sa.sa_sigaction = signal_handler;
    sa.sa_flags = SA_SIGINFO;

    if (sigaction(SIGHUP , &sa, NULL) < 0 ||
        sigaction(SIGTERM, &sa, NULL) < 0 ||
        sigaction(SIGINT , &sa, NULL) < 0   )
    {
        print_error("Failed to install signal handlers");
    }
}


static void signal_handler(int signo, siginfo_t *info, void *data)
{
#if 0
    ucontext_t *uc = (ucontext_t *)data;
#endif

    switch (signo) {
    case SIGHUP:
    case SIGTERM:
    case SIGINT:
        if (main_loop != NULL) {
            g_main_loop_quit(main_loop);
            break;
        }
        /* intentional fall over */

    default:
        exit(EINTR);
    }

    (void)info;
    (void)data;
}

static void create_mainloop(void)
{
    if ((main_loop = g_main_loop_new(NULL, FALSE)) == NULL) {
        print_error("Can't create G-MainLoop");
    }
}

static void destroy_mainloop(void)
{
    g_main_loop_unref(main_loop);
}

static void run_mainloop(void)
{
    g_main_loop_run(main_loop);
}

static void create_input(void)
{
    static GIOCondition cond = G_IO_IN | G_IO_HUP | G_IO_ERR;

    if (fcntl(0, F_SETFL, O_NONBLOCK) == -1)
        printf("Failed to set stdin to non-blocking mode");

    if ((input.chan = g_io_channel_unix_new(0)) == NULL)
        print_error("Failed to create input");

    input.evsrc = g_io_add_watch(input.chan, cond, input_cb, NULL);
}

static void destroy_input(void)
{
    g_source_remove(input.evsrc);
    g_io_channel_unref(input.chan);

    memset(&input, 0, sizeof(input_t));
}

static void accept_input(int accept)
{
    int current = input.accept;

    input.accept = accept;

    if (current != accept) {
        if (accept) {
            input.buf[0] = '\0';
            input.len = 0;
            
            print_message("accepting input");
            print_input();
        }
        else {
            if (input.accept) {
                print_message("rejecting input");
                fflush(stdout);
            }
        }
    }
}

static void print_input(void)
{
    if (input.accept) {
        printf(">%s", input.buf);
        fflush(stdout);
    }
}

static char *skip_whitespaces(char *str)
{
    while (*str && (*str <= 0x20 || *str >= 0x7f))
        str++;

    return str;
}

static void parse_input(void)
{
    char     *str = input.buf;
    char     *p;
    char     *rs;
    uint32_t  res[4];
    int       i;
    resmsg_t  msg;


    if (!strncmp(str, "help", 4)) {
        str = skip_whitespaces(str + 4);
    }
    else if (!strncmp(str, "acquire", 7)) {
        str = skip_whitespaces(str + 7);

        memset(&msg, 0, sizeof(resmsg_t));
        msg.possess.type = RESMSG_ACQUIRE;
        manager_send_message(&msg);
    }
    else if (!strncmp(str, "release", 7)) {
        str = skip_whitespaces(str + 7);

        memset(&msg, 0, sizeof(resmsg_t));
        msg.possess.type = RESMSG_RELEASE;
        manager_send_message(&msg);
    }
    else if (!strncmp(str, "update", 6)) {
        rs = str = skip_whitespaces(str + 6);
  
        for (i = 0;  i < 4; i++) {
            if ((p = strchr(str, ':')) != NULL)
                *p = '\0';
            
            res[i] = *str ? parse_resource_list(str, 0) : 0;
            
            if (p)
                str = p + 1;
            else {
                while (*str)
                    str++;
            }
        }

        if (           !res[0]            ||
            ((res[0] | res[1]) != res[0]) ||
            ((res[0] | res[2]) != res[0])   )
        {
            print_message("invalid resource specification: '%s'", rs);
        }
        else {
            memset(&msg, 0, sizeof(resmsg_t));
            msg.record.type       = RESMSG_UPDATE;
            msg.record.rset.all   = res[0];
            msg.record.rset.opt   = res[1];
            msg.record.rset.share = res[2];
            msg.record.rset.mask  = res[3];
            msg.record.class      = config.class;
            manager_send_message(&msg);
        }
    }
    else {
        print_message("invalid input '%s'", input.buf);
        return;
    }
    
    if (*str) {
        print_message("garbage at the end of input: '%s'", str);
    }
}

static gboolean input_cb(GIOChannel *ch, GIOCondition cond, gpointer data)
{
    char  ignore[512];
    int   lincnt;
    int   rest;
    int   junk;
    char *p;

    (void)ch;
    (void)data;

    if (cond == G_IO_IN) {
        if (!input.accept) {
            while (read(0, ignore, sizeof(ignore)) > 0 || errno == EINTR)
                ;
        }
        else {
            while ((rest = sizeof(input.buf) - input.len) > 0) {

                if ((junk = read(0, input.buf + input.len, rest)) < 0) {
                    if (errno == EAGAIN)
                        break;
                    
                    if (errno == EINTR)
                        continue;
                    
                    print_error("error during input from terminal");
                }
                
                input.len += junk;
            }
            
            lincnt = 0;
            
            while ((p = strchr(input.buf, '\n')) != NULL) {
                *p++ = '\0';
                
                parse_input();
                
                if ((rest = input.len - (p - input.buf)) <= 0)
                    input.len = 0;
                else {
                    memmove(input.buf, p, rest);
                    input.len = rest;
                }
                
                input.buf[input.len] = '\0';
                
                lincnt++;
            }
            
            if (lincnt)
                print_input();
        }

        return TRUE;
    }

    return FALSE;
}


static void create_dbus(void)
{
    DBusError err;

    dbus_error_init(&err);

    if ((dconn = dbus_bus_get(DBUS_BUS_SESSION, &err)) == NULL) {
        print_error("Can't get session bus");
    }

    dbus_connection_setup_with_g_main(dconn, NULL);
    
}

static void destroy_dbus(void)
{
    dbus_connection_unref(dconn);

    dconn = NULL;
}

static void create_manager(void)
{
    int i;

    for (i = 0;  i < REQHASH_DIM; i++)
        reqtyp[i] = RESMSG_INVALID;

    rconn = resproto_init(RESPROTO_ROLE_CLIENT, RESPROTO_TRANSPORT_DBUS,
                          connect_to_manager, dconn);

    if (rconn == NULL)
        print_error("Can't initiate resprot");

    resproto_set_handler(rconn, RESMSG_UNREGISTER, manager_receive_message);
    resproto_set_handler(rconn, RESMSG_GRANT     , manager_receive_message);
    resproto_set_handler(rconn, RESMSG_ADVICE    , manager_receive_message);
    
    connect_to_manager(rconn);
}

static void destroy_manager(void)
{
}

static void connect_to_manager(resconn_t *rc)
{
    resmsg_t  resmsg;
    int       index;

    resmsg.record.type       = RESMSG_REGISTER;
    resmsg.record.id         = config.id;
    resmsg.record.reqno      = ++reqno;
    resmsg.record.rset.all   = config.rset.all;
    resmsg.record.rset.opt   = config.rset.opt;
    resmsg.record.rset.share = config.rset.share;
    resmsg.record.rset.mask  = config.rset.mask;
    resmsg.record.class      = config.class;
    resmsg.record.mode       = config.mode;

    rset = resconn_connect(rc, &resmsg, manager_status);

    index = REQHASH_INDEX(reqno);
    reqtyp[index] = RESMSG_REGISTER;
}

static void manager_status(resset_t *rset, resmsg_t *msg)
{
    char          *str;
    int            idx;
    resmsg_type_t  type;

    if (msg->type != RESMSG_STATUS)
        print_error("%s(): got confused with data structures", __FUNCTION__);
    else {
        idx = REQHASH_INDEX(msg->status.reqno);
        type = reqtyp[idx];

        if (msg->status.errcod) {
            str = resmsg_type_str(reqtyp[idx]);
            print_message("%s request failed (%d): %s",
                          str, msg->status.errcod, msg->status.errmsg);
            print_input();
        }
        else {
            switch (type) {
            case RESMSG_REGISTER:        accept_input(TRUE);      break;
            case RESMSG_UNREGISTER:      accept_input(FALSE);     break;
            default:                                              break;
            }
        }

        reqtyp[idx] = RESMSG_INVALID;
    }
}

static void manager_receive_message(resmsg_t *msg, resset_t *rs, void *data)
{
    char  buf[80];

    (void)data;

    if (rs != rset)
        print_error("%s(): got confused with data structures", __FUNCTION__);
    else {
        switch (msg->type) {

        case RESMSG_UNREGISTER:
            print_message("unregister request from manager");
            accept_input(FALSE);
            break;

        case RESMSG_GRANT:
            resmsg_res_str(msg->notify.resrc, buf, sizeof(buf));
            if (config.verbose)
                print_message("manager granted the resources: %s", buf);
            else 
                print_message("granted: %s", buf);
            print_input();
            break;

        case RESMSG_ADVICE:
            resmsg_res_str(msg->notify.resrc, buf, sizeof(buf));
            if (config.verbose)
                print_message("resources might be acquired: %s", buf);
            else
                print_message("advice: %s", buf);
            print_input();
            break;

        default:
            if (config.verbose) {
                print_message("%s(): unexpected message type %d (%s)",
                              __FUNCTION__, msg->type, 
                              resmsg_type_str(msg->type));
            }
            else {
                print_message("error: wrong message (%d)", msg->type);
            }
            
            print_input();
            break;
        }
    }
}

static void manager_send_message(resmsg_t *msg)
{
    int index;
    int success;

    msg->any.id    = config.id;
    msg->any.reqno = ++reqno;

    index = REQHASH_INDEX(msg->any.reqno);
    reqtyp[index] = msg->type;

    success = resproto_send_message(rset, msg, manager_status);

    if (!success) 
        print_message("failed to send %s request", resmsg_type_str(msg->type));
}



static void print_error(char *fmt, ...)
{
    va_list  ap;
    char     fmtbuf[512];

    if (config.verbose) {
        snprintf(fmtbuf, sizeof(fmtbuf), "%s%s: %s\n",
                 input.accept ? "\n" : "", exe_name, fmt);
    }
    else {
        snprintf(fmtbuf, sizeof(fmtbuf), "%s%s\n",
                 input.accept ? "\n" : "", fmt);
    }

    va_start(ap, fmt);
    vprintf(fmtbuf, ap);
    va_end(ap);

    exit(errno);
}

static void print_message(char *fmt, ...)
{
    va_list  ap;
    char     fmtbuf[512];

    if (config.verbose) {
        snprintf(fmtbuf, sizeof(fmtbuf), "%s%s: %s\n",
                 input.accept ? "\n" : "", exe_name, fmt);
    }
    else {
        snprintf(fmtbuf, sizeof(fmtbuf), "%s%s\n",
                 input.accept ? "\n" : "", fmt);
    }

    va_start(ap, fmt);
    vprintf(fmtbuf, ap);
    va_end(ap);
}

static void usage(int exit_code)
{
    printf("usage: %s [-h] [-t] [-v] [-f mode-values]"
           "[-o optional-resources] [-s shared-resources -m shared-mask] "
           "class all-resources\n",
           exe_name);
    printf("\toptions:\n");
    printf("\t  h\tprint this help message and exit\n");
    printf("\t  t\ttrace messages\n");
    printf("\t  v\tverbose printouts\n");
    printf("\t  f\tmode values. See 'modes' below for the "
           "\n\t\tsyntax of <mode-values>\n");
    printf("\t  o\toptional resources. See 'resources' below for the "
           "syntax of\n\t\t<optional-resources>\n");
    printf("\t  s\tshared resources. See 'resources' below for the "
           "syntax of\n\t\t<shared-resources>\n");
    printf("\t  m\tshared resource mask. See 'resources' below for the "
           "syntax of\n\t\t<shared-mask>\n");
    printf("\tclass:\n");
    printf("\t\tcall\t- for native or 3rd party telephony\n");
    printf("\t\tringtone - for ringtones\n");
    printf("\t\talarm\t - for alarm clock\n");
    printf("\t\tmedia\t - for media playback/recording\n");
    printf("\t\tdefault\t - for nonidentified applications\n");
    printf("\tresources:\n");
    printf("\t  comma separated list of the following resources\n");
    printf("\t\tAudioPlayback\n");
    printf("\t\tVideoPlayback\n");
    printf("\t\tAudioRecording\n");
    printf("\t\tVideoRecording\n");
    printf("\t  no whitespace allowed in the resource list.\n");
    printf("\tmodes:\n");
    printf("\t  comma separated lis of the following modes\n");
    printf("\t\tAutoRelease\n");

    exit(exit_code);
}

static void parse_options(int argc, char **argv)
{
    int   option;

    exe_name = strdup(basename(argv[0]));

    config.trace = FALSE;
    config.id    = 1;

    while ((option = getopt(argc, argv, "htvf:s:o:m:")) != -1) {

        switch (option) {
            
        case 'h':   usage(0);                                            break;
        case 't':   config.trace      = TRUE;                            break;
        case 'v':   config.verbose    = TRUE;                            break;
        case 'f':   config.mode       = parse_mode_values(optarg, 1);    break;
        case 'o':   config.rset.opt   = parse_resource_list(optarg, 1);  break;
        case 's':   config.rset.share = parse_resource_list(optarg, 1);  break;
        case 'm':   config.rset.mask  = parse_resource_list(optarg, 1);  break;
        default:    usage(EINVAL);                                       break;
        
        }
    }

    if (optind != argc - 2)
        usage(EINVAL);
    else {
        config.class    = parse_class_string(argv[optind]);
        config.rset.all = parse_resource_list(argv[optind+1], 1);
    }

    if ((config.rset.all | config.rset.opt) != config.rset.all) {
        print_error("optonal resources are not subset of all resources");
    }

    if ((config.rset.all | config.rset.mask) != config.rset.all) {
        print_error("shared resource mask is not subset of all resources ");
    }

    if ((config.rset.mask | config.rset.share) != config.rset.mask) {
        print_error("shared resource values are not subset of shared mask ");
    }
}

static char *parse_class_string(char *str)
{
    if (strcmp(str, "call"      ) &&
        strcmp(str, "camera"    ) &&
        strcmp(str, "ringtone"  ) &&
        strcmp(str, "alarm"     ) &&
        strcmp(str, "navigator" ) &&
        strcmp(str, "game"      ) &&
        strcmp(str, "player"    ) &&
        strcmp(str, "event"     ) &&
        strcmp(str, "background")   )
   {
       print_error("invalid class '%s'", str);
   }

    return str;
}

static uint32_t parse_resource_list(char *rlist_str, int exit_if_error)
{
    static rdef_t  rdef[] = {
        { RESMSG_AUDIO_PLAYBACK ,  "AudioPlayback"  },
        { RESMSG_VIDEO_PLAYBACK ,  "VideoPlayback"  },
        { RESMSG_AUDIO_RECORDING,  "AudioRecording" },
        { RESMSG_VIDEO_RECORDING,  "VideoRecording" },
        {           0           ,       NULL        }
    };

    uint32_t  rlist = 0;
    char      buf[256];
    rdef_t   *rd;
    char     *p;
    char     *e;

    if (rlist_str == NULL)
        print_message("missing resource list");
    else {
        strncpy(buf, rlist_str, sizeof(buf));
        buf[sizeof(buf)-1] = '\0';

        p = buf;

        do {
            if ((e = strchr(p, ',')) != NULL)
                *e++ = '\0';

            for (rd = rdef;  rd->name != NULL;  rd++) {
                if (!strcmp(p, rd->name))
                    break;
            }

            if (!rd->value) {
                print_message("invalid resource list '%s'", rlist_str);
                rlist = 0;
                break;
            }

            rlist |= rd->value;

        } while((p = e) != NULL);
    }

    if (!rlist && exit_if_error)
        exit(EINVAL);

    return rlist;
}

static uint32_t parse_mode_values(char *mval_str, int exit_if_error)
{
    static rdef_t  mdef[] = {
        { RESMSG_MODE_AUTO_RELEASE ,  "AutoRelease"  },
        {             0            ,       NULL      }
    };

    uint32_t  mode = 0;
    char      buf[256];
    rdef_t   *md;
    char     *p;
    char     *e;

    if (mval_str == NULL)
        print_message("missing mode values");
    else {
        strncpy(buf, mval_str, sizeof(buf));
        buf[sizeof(buf)-1] = '\0';

        p = buf;

        do {
            if ((e = strchr(p, ',')) != NULL)
                *e++ = '\0';

            for (md = mdef;  md->name != NULL;  md++) {
                if (!strcmp(p, md->name))
                    break;
            }

            if (!md->value) {
                print_message("invalid resource values '%s'", mval_str);
                mode = 0;
                break;
            }

            mode |= md->value;

        } while((p = e) != NULL);
    }

    if (!mode && exit_if_error)
        exit(EINVAL);

    return mode;
}

/*
 * Local Variables:
 * c-basic-offset: 4
 * indent-tabs-mode: nil
 * End:
 */