| 590 | } |
| 591 | |
| 592 | cbm_daemon_subscription_result_t cbm_daemon_watch_subscribe( |
| 593 | cbm_daemon_coordinator_t *coordinator, cbm_daemon_client_id_t client_id, |
| 594 | const char *project_key, cbm_daemon_subscription_id_t *subscription_id) { |
| 595 | if (subscription_id) { |
| 596 | *subscription_id = CBM_DAEMON_SUBSCRIPTION_ID_INVALID; |
| 597 | } |
| 598 | if (!coordinator || !subscription_id || !project_key || project_key[0] == '\0' || |
| 599 | client_id == CBM_DAEMON_CLIENT_ID_INVALID) { |
| 600 | return CBM_DAEMON_SUBSCRIPTION_REJECTED; |
| 601 | } |
| 602 | |
| 603 | cbm_mutex_lock(&coordinator->mutex); |
| 604 | if (coordinator->state != CBM_DAEMON_COORDINATOR_RUNNING || |
| 605 | !find_client_locked(coordinator, client_id)) { |
| 606 | cbm_mutex_unlock(&coordinator->mutex); |
| 607 | return CBM_DAEMON_SUBSCRIPTION_REJECTED; |
| 608 | } |
| 609 | cbm_daemon_watch_t *watch = find_watch_locked(coordinator, project_key); |
| 610 | bool started = watch == NULL; |
| 611 | cbm_daemon_watch_t *new_watch = NULL; |
| 612 | char *key_copy = NULL; |
| 613 | cbm_daemon_subscription_t *subscription = malloc(sizeof(*subscription)); |
| 614 | if (started) { |
| 615 | new_watch = calloc(1, sizeof(*new_watch)); |
| 616 | key_copy = daemon_string_dup(project_key); |
| 617 | } |
| 618 | if (!subscription || (started && (!new_watch || !key_copy))) { |
| 619 | free(subscription); |
| 620 | free(new_watch); |
| 621 | free(key_copy); |
| 622 | cbm_mutex_unlock(&coordinator->mutex); |
| 623 | return CBM_DAEMON_SUBSCRIPTION_REJECTED; |
| 624 | } |
| 625 | |
| 626 | cbm_daemon_subscription_id_t id = issue_subscription_id_locked(coordinator); |
| 627 | if (id == CBM_DAEMON_SUBSCRIPTION_ID_INVALID) { |
| 628 | free(subscription); |
| 629 | free(new_watch); |
| 630 | free(key_copy); |
| 631 | cbm_mutex_unlock(&coordinator->mutex); |
| 632 | return CBM_DAEMON_SUBSCRIPTION_REJECTED; |
| 633 | } |
| 634 | if (started) { |
| 635 | new_watch->project_key = key_copy; |
| 636 | new_watch->next = coordinator->watches; |
| 637 | coordinator->watches = new_watch; |
| 638 | coordinator->watch_count++; |
| 639 | watch = new_watch; |
| 640 | } |
| 641 | subscription->id = id; |
| 642 | subscription->client_id = client_id; |
| 643 | subscription->next = watch->subscriptions; |
| 644 | watch->subscriptions = subscription; |
| 645 | watch->subscription_count++; |
| 646 | *subscription_id = id; |
| 647 | cbm_mutex_unlock(&coordinator->mutex); |
| 648 | return started ? CBM_DAEMON_SUBSCRIPTION_STARTED : CBM_DAEMON_SUBSCRIPTION_JOINED; |
| 649 | } |
no test coverage detected