client_certification_tests.c 17.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
// Copyright (c) 2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/

#include "oc_api.h"
18
#include "oc_core_res.h"
19
#include "oc_swupdate.h"
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
#include "port/oc_clock.h"
#include "oc_pki.h"
#include "oc_introspection.h"
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

static pthread_t event_thread;
static pthread_mutex_t app_sync_lock;
static pthread_mutex_t mutex;
static pthread_cond_t cv;
static struct timespec ts;
static int quit = 0;

typedef struct resource_t
{
  struct resource_t *next;
  oc_endpoint_t *endpoint;
  char uri[64];
} resource_t;

OC_LIST(resources);
OC_MEMB(resources_m, resource_t, 100);

static void
free_resource(resource_t *res)
{
  oc_free_server_endpoints(res->endpoint);
  oc_memb_free(&resources_m, res);
}

static void
free_all_resources(void)
{
  resource_t *l = (resource_t *)oc_list_pop(resources);
  while (l != NULL) {
    free_resource(l);
    l = (resource_t *)oc_list_pop(resources);
  }
}

static int
app_init(void)
{
  int ret = oc_init_platform("OCF", NULL, NULL);
  ret |= oc_add_device("/oic/d", "oic.wk.d", "OCFTestClient", "ocf.2.0.5",
                       "ocf.res.1.3.0,ocf.sh.1.3.0", NULL, NULL);

#if defined(OC_IDD_API)
  FILE *fp;
  uint8_t *buffer;
  size_t buffer_size;
  const char introspection_error[] =
    "\tERROR Could not read client_certification_tests_IDD.cbor\n"
    "\tIntrospection data not set for device.\n";
  fp = fopen("./client_certification_tests_IDD.cbor", "rb");
  if (fp) {
    fseek(fp, 0, SEEK_END);
    buffer_size = ftell(fp);
    rewind(fp);

    buffer = (uint8_t *)malloc(buffer_size * sizeof(uint8_t));
    size_t fread_ret = fread(buffer, buffer_size, 1, fp);
    fclose(fp);

    if (fread_ret == 1) {
      oc_set_introspection_data(0, buffer, buffer_size);
      PRINT("\tIntrospection data set for device.\n");
    } else {
      PRINT("%s", introspection_error);
    }
    free(buffer);
  } else {
    PRINT("%s", introspection_error);
  }
#endif

  return ret;
}

#define SCANF(...)                                                             \
  do {                                                                         \
    if (scanf(__VA_ARGS__) != 1) {                                             \
      PRINT("ERROR Invalid input\n");                                          \
    }                                                                          \
  } while (0)

static void
display_menu(void)
{
  PRINT("\n\n################################################\nClient "
        "Certification Tests"
        "\n################################################\n");
  PRINT("[0] Display this menu\n");
  PRINT("-----------------------------------------------\n");
  PRINT("[1] Discover resources\n");
  PRINT("-----------------------------------------------\n");
  PRINT("[2] GET resource UDP\n");
  PRINT("[3] GET resource TCP\n");
  PRINT("[4] POST binary switch UDP\n");
  PRINT("[5] POST binary switch TCP\n");
  PRINT("[6] Start OBSERVE resource UDP\n");
  PRINT("[7] Stop OBSERVE resource UDP\n");
  PRINT("[8] Start OBSERVE resource TCP\n");
  PRINT("[9] Stop OBSERVE resource TCP\n");
  PRINT("-----------------------------------------------\n");
127 128 129 130 131
#ifdef OC_CLOUD
  PRINT("[20] Send ping message\n");
  PRINT("-----------------------------------------------\n");
#endif /* OC_CLOUD */
  PRINT("[99] Exit\n");
132 133 134 135
  PRINT("################################################\n");
  PRINT("\nSelect option: \n");
}

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
#ifdef OC_SOFTWARE_UPDATE
int
validate_purl(const char *purl)
{
  (void) purl;
  return 0;
}

int
check_new_version(size_t device, const char *url, const char *version)
{
  if (!url) {
    oc_swupdate_notify_done(device, OC_SWUPDATE_RESULT_INVALID_URL);
    return -1;
  }
  PRINT("Package url %s\n", url);
  if (version) {
    PRINT("Package version: %s\n", version);
  }
  oc_swupdate_notify_new_version_available(device, "2.0",
                                           OC_SWUPDATE_RESULT_SUCCESS);
  return 0;
}

int
download_update(size_t device, const char *url)
{
  (void)url;
  oc_swupdate_notify_downloaded(device, "2.0", OC_SWUPDATE_RESULT_SUCCESS);
  return 0;
}

int
perform_upgrade(size_t device, const char *url)
{
  (void)url;
  oc_swupdate_notify_upgrading(device, "2.0", oc_clock_time(),
                               OC_SWUPDATE_RESULT_SUCCESS);

  oc_swupdate_notify_done(device, OC_SWUPDATE_RESULT_SUCCESS);
  return 0;
}
#endif /* OC_SOFTWARE_UPDATE */

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
static void
show_discovered_resources(resource_t **res)
{
  PRINT("\nDiscovered resources:\n");
  resource_t *l = (resource_t *)oc_list_head(resources);
  int i = 0;
  PRINT("\n\n");
  while (l != NULL) {
    if (res != NULL) {
      res[i] = l;
    }
    PRINT("[%d]: %s", i, l->uri);
    oc_endpoint_t *ep = l->endpoint;
    while (ep != NULL) {
      PRINT("\n\t\t");
      PRINTipaddr(*ep);
      ep = ep->next;
    }
    PRINT("\n\n");
    i++;
    l = l->next;
  }
}

static void
signal_event_loop(void)
{
  pthread_mutex_lock(&mutex);
  pthread_cond_signal(&cv);
  pthread_mutex_unlock(&mutex);
}

static void
handle_signal(int signal)
{
  (void)signal;
  signal_event_loop();
  quit = 1;
}

static void *
ocf_event_thread(void *data)
{
  (void)data;
  oc_clock_time_t next_event;
  while (quit != 1) {
    pthread_mutex_lock(&app_sync_lock);
    next_event = oc_main_poll();
    pthread_mutex_unlock(&app_sync_lock);

    pthread_mutex_lock(&mutex);
    if (next_event == 0) {
      pthread_cond_wait(&cv, &mutex);
    } else {
      ts.tv_sec = (next_event / OC_CLOCK_SECOND);
      ts.tv_nsec = (next_event % OC_CLOCK_SECOND) * 1.e09 / OC_CLOCK_SECOND;
      pthread_cond_timedwait(&cv, &mutex, &ts);
    }
    pthread_mutex_unlock(&mutex);
  }
  oc_main_shutdown();
  return NULL;
}

static void
POST_handler(oc_client_response_t *data)
{
  PRINT("POST_handler:\n");
  if (data->code == OC_STATUS_CHANGED) {
    PRINT("POST response OK\n");
  } else {
    PRINT("POST response code %d\n", data->code);
  }

  char buf[4096];
  oc_rep_to_json(data->payload, buf, 4096, true);
  oc_client_cb_t *cb = (oc_client_cb_t *)data->client_cb;
  PRINT("uri: %s\n", oc_string(cb->uri));
  PRINT("query: %s\n", oc_string(cb->query));
  PRINT("payload: %s\n", buf);
  display_menu();
}

static void
GET_handler(oc_client_response_t *data)
{
  PRINT("GET_handler:\n");
  char buf[4096];
  oc_rep_to_json(data->payload, buf, 4096, true);
  oc_client_cb_t *cb = (oc_client_cb_t *)data->client_cb;
  PRINT("uri: %s\n", oc_string(cb->uri));
  PRINT("query: %s\n", oc_string(cb->query));
  PRINT("payload: %s\n", buf);

  display_menu();
}

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
#ifdef OC_CLOUD
static void
ping_handler(oc_client_response_t *data)
{
  (void)data;
  PRINT("\nReceived Pong\n");
}

static void
cloud_send_ping(void)
{
  PRINT("\nEnter receiving endpoint: ");
  char addr[256];
  SCANF("%255s", addr);
  char endpoint_string[267];
  sprintf(endpoint_string, "coap+tcp://%s", addr);
  oc_string_t ep_string;
  oc_new_string(&ep_string, endpoint_string, strlen(endpoint_string));
  oc_endpoint_t endpoint;
  int ret = oc_string_to_endpoint(&ep_string, &endpoint, NULL);
  oc_free_string(&ep_string);
  if (ret < 0) {
    PRINT("\nERROR parsing endpoint string\n");
    return;
  }
  pthread_mutex_lock(&app_sync_lock);
  if (oc_send_ping(false, &endpoint, 10, ping_handler, NULL)) {
    PRINT("\nSuccessfully issued Ping request\n");
  } else {
    PRINT("\nERROR issuing Ping request\n");
  }
  pthread_mutex_unlock(&app_sync_lock);
  signal_event_loop();
}
#endif /* OC_CLOUD */

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
static void
get_resource(bool tcp, bool observe)
{
  pthread_mutex_lock(&app_sync_lock);
  if (oc_list_length(resources) > 0) {
    resource_t *res[100];
    show_discovered_resources(res);
    PRINT("\n\nSelect resource: ");
    int c;
    SCANF("%d", &c);
    if (c < 0 || c > oc_list_length(resources)) {
      PRINT("\nERROR: Invalid selection.. Try again..\n");
    } else {
      oc_endpoint_t *ep = res[c]->endpoint;
      while (ep && (tcp && !(ep->flags & TCP))) {
        ep = ep->next;
      }
      if (observe) {
        if (!oc_do_observe(res[c]->uri, ep, NULL, GET_handler, HIGH_QOS,
                           NULL)) {
          PRINT("\nERROR: Could not issue Observe request\n");
        }
      } else {
        if (!oc_do_get(res[c]->uri, ep, NULL, GET_handler, HIGH_QOS, NULL)) {
          PRINT("\nERROR Could not issue GET request\n");
        }
      }
    }
  } else {
    PRINT("\nERROR: No known resources... Please try discovery...\n");
  }
  pthread_mutex_unlock(&app_sync_lock);
  signal_event_loop();
}

static void
stop_observe_resource(bool tcp)
{
  pthread_mutex_lock(&app_sync_lock);
  if (oc_list_length(resources) > 0) {
    resource_t *res[100];
    show_discovered_resources(res);
    PRINT("\n\nSelect resource: ");
    int c;
    SCANF("%d", &c);
    if (c < 0 || c > oc_list_length(resources)) {
      PRINT("\nERROR: Invalid selection.. Try again..\n");
    } else {
      oc_endpoint_t *ep = res[c]->endpoint;
      while (ep && (tcp && !(ep->flags & TCP))) {
        ep = ep->next;
      }
      oc_stop_observe(res[c]->uri, ep);
    }
  } else {
    PRINT("\nERROR: No known resources... Please try discovery...\n");
  }
  pthread_mutex_unlock(&app_sync_lock);
  signal_event_loop();
}

static void
post_resource(bool tcp)
{
  pthread_mutex_lock(&app_sync_lock);
  if (oc_list_length(resources) > 0) {
    resource_t *res[100];
    show_discovered_resources(res);
    PRINT("\n\nSelect resource: ");
    int c;
    SCANF("%d", &c);
    if (c < 0 || c > oc_list_length(resources)) {
      PRINT("\nERROR: Invalid selection.. Try again..\n");
    } else {
      int s;
      PRINT("Select siwtch value:\n[0]: true\n[1]: false\n\nSelect: ");
      SCANF("%d", &s);
      if (s < 0 || s > 1) {
        PRINT("\nERROR: Invalid selection.. Try again..\n");
      } else {
        oc_endpoint_t *ep = res[c]->endpoint;
        while (ep && (tcp && !(ep->flags & TCP))) {
          ep = ep->next;
        }
        if (oc_init_post(res[c]->uri, ep, NULL, &POST_handler, HIGH_QOS,
                         NULL)) {
          oc_rep_start_root_object();
          if (s == 0) {
            oc_rep_set_boolean(root, value, true);
          } else {
            oc_rep_set_boolean(root, value, false);
          }
          oc_rep_end_root_object();
          if (!oc_do_post()) {
            PRINT("\nERROR: Could not issue POST request\n");
          }
        } else {
          PRINT("\nERROR: Could not initialize POST request\n");
        }
      }
    }
  } else {
    PRINT("\nERROR: No known locks... Please try discovery...\n");
  }
  pthread_mutex_unlock(&app_sync_lock);
  signal_event_loop();
}

static oc_discovery_flags_t
discovery(const char *di, const char *uri, oc_string_array_t types,
          oc_interface_mask_t iface_mask, oc_endpoint_t *endpoint,
          oc_resource_properties_t bm, bool more, void *user_data)
{
  (void)di;
  (void)iface_mask;
  (void)user_data;
  (void)uri;
  (void)types;
  (void)bm;

  resource_t *l = (resource_t *)oc_memb_alloc(&resources_m);
  if (l) {
    oc_endpoint_list_copy(&l->endpoint, endpoint);
    int uri_len = (strlen(uri) >= 64) ? 63 : strlen(uri);
    memcpy(l->uri, uri, uri_len);
    l->uri[uri_len] = '\0';
    oc_list_add(resources, l);
  }

  if (!more) {
    PRINT("\nDiscovered new device.. You may now issue requests...\n");
    display_menu();
  }

  return OC_CONTINUE_DISCOVERY;
}

static oc_discovery_flags_t
null_discovery(const char *di, const char *uri, oc_string_array_t types,
               oc_interface_mask_t iface_mask, oc_endpoint_t *endpoint,
               oc_resource_properties_t bm, void *user_data)
{
  (void)di;
  (void)iface_mask;
  (void)user_data;
  (void)uri;
  (void)types;
  (void)endpoint;
  (void)bm;

  return OC_STOP_DISCOVERY;
}

static void
issue_requests(void)
{
  if (!oc_do_ip_discovery(NULL, &null_discovery, NULL)) {
    PRINT("\nERROR: Could not issue discovery request\n");
  }
}

static void
discover_resources(void)
{
  pthread_mutex_lock(&app_sync_lock);
  free_all_resources();
  if (!oc_do_ip_discovery_all(&discovery, NULL)) {
    PRINT("\nERROR: Could not issue discovery request\n");
  }
  pthread_mutex_unlock(&app_sync_lock);
  signal_event_loop();
}

#ifdef OC_SECURITY
void
random_pin_cb(const unsigned char *pin, size_t pin_len, void *data)
{
  (void)data;
  PRINT("\n\nRandom PIN: %.*s\n\n", (int)pin_len, pin);
}
#endif /* OC_SECURITY */
#if defined(OC_SECURITY) && defined(OC_PKI)
static int
read_pem(const char *file_path, char *buffer, size_t *buffer_len)
{
  FILE *fp = fopen(file_path, "r");
  if (fp == NULL) {
    PRINT("ERROR: unable to read PEM\n");
    return -1;
  }
  if (fseek(fp, 0, SEEK_END) != 0) {
    PRINT("ERROR: unable to read PEM\n");
    fclose(fp);
    return -1;
  }
  long pem_len = ftell(fp);
  if (pem_len < 0) {
    PRINT("ERROR: could not obtain length of file\n");
    fclose(fp);
    return -1;
  }
514
  if (pem_len >= (long)*buffer_len) {
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    PRINT("ERROR: buffer provided too small\n");
    fclose(fp);
    return -1;
  }
  if (fseek(fp, 0, SEEK_SET) != 0) {
    PRINT("ERROR: unable to read PEM\n");
    fclose(fp);
    return -1;
  }
  if (fread(buffer, 1, pem_len, fp) < (size_t)pem_len) {
    PRINT("ERROR: unable to read PEM\n");
    fclose(fp);
    return -1;
  }
  fclose(fp);
530
  buffer[pem_len] = '\0';
531 532 533 534 535 536 537 538 539 540 541 542 543
  *buffer_len = (size_t)pem_len;
  return 0;
}
#endif /* OC_SECURITY && OC_PKI */

void
factory_presets_cb(size_t device, void *data)
{
  (void)device;
  (void)data;
#if defined(OC_SECURITY) && defined(OC_PKI)
  char cert[8192];
  size_t cert_len = 8192;
544
  if (read_pem("pki_certs/certification_tests_ee.pem", cert, &cert_len) < 0) {
545 546 547 548 549 550
    PRINT("ERROR: unable to read certificates\n");
    return;
  }

  char key[4096];
  size_t key_len = 4096;
551
  if (read_pem("pki_certs/certification_tests_key.pem", key, &key_len) < 0) {
552 553 554 555 556 557 558 559 560 561 562 563 564
    PRINT("ERROR: unable to read private key");
    return;
  }

  int ee_credid = oc_pki_add_mfg_cert(0, (const unsigned char *)cert, cert_len,
                                      (const unsigned char *)key, key_len);

  if (ee_credid < 0) {
    PRINT("ERROR installing manufacturer EE cert\n");
    return;
  }

  cert_len = 8192;
565 566
  if (read_pem("pki_certs/certification_tests_subca1.pem", cert, &cert_len) <
      0) {
567 568 569 570 571 572 573 574 575 576 577 578 579
    PRINT("ERROR: unable to read certificates\n");
    return;
  }

  int subca_credid = oc_pki_add_mfg_intermediate_cert(
    0, ee_credid, (const unsigned char *)cert, cert_len);

  if (subca_credid < 0) {
    PRINT("ERROR installing intermediate CA cert\n");
    return;
  }

  cert_len = 8192;
580 581
  if (read_pem("pki_certs/certification_tests_rootca1.pem", cert, &cert_len) <
      0) {
582 583 584 585 586 587 588 589 590 591 592
    PRINT("ERROR: unable to read certificates\n");
    return;
  }

  int rootca_credid =
    oc_pki_add_mfg_trust_anchor(0, (const unsigned char *)cert, cert_len);
  if (rootca_credid < 0) {
    PRINT("ERROR installing root cert\n");
    return;
  }

593 594 595
  oc_pki_set_security_profile(
    0, OC_SP_BASELINE | OC_SP_BLACK | OC_SP_BLUE | OC_SP_PURPLE, OC_SP_BASELINE,
    ee_credid);
596 597 598
#endif /* OC_SECURITY && OC_PKI */
}

599 600 601 602 603 604 605 606 607
void
display_device_uuid(void)
{
  char buffer[OC_UUID_LEN];
  oc_uuid_to_str(oc_core_get_device_id(0), buffer, sizeof(buffer));

  PRINT("Started device with ID: %s\n", buffer);
}

608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
int
main(void)
{
  struct sigaction sa;
  sigfillset(&sa.sa_mask);
  sa.sa_flags = 0;
  sa.sa_handler = handle_signal;
  sigaction(SIGINT, &sa, NULL);

  int init;

  static const oc_handler_t handler = { .init = app_init,
                                        .signal_event_loop = signal_event_loop,
                                        .requests_entry = issue_requests };

623
  oc_set_con_res_announced(true);
624 625 626 627 628 629 630
#ifdef OC_STORAGE
  oc_storage_config("./client_certification_tests_creds");
#endif /* OC_STORAGE */
  oc_set_factory_presets_cb(factory_presets_cb, NULL);
#ifdef OC_SECURITY
  oc_set_random_pin_callback(random_pin_cb, NULL);
#endif
631 632 633 634 635 636 637 638 639
#ifdef OC_SOFTWARE_UPDATE
  static oc_swupdate_cb_t swupdate_impl;
  swupdate_impl.validate_purl = validate_purl;
  swupdate_impl.check_new_version = check_new_version;
  swupdate_impl.download_update = download_update;
  swupdate_impl.perform_upgrade = perform_upgrade;
  oc_swupdate_set_impl(&swupdate_impl);
#endif /* OC_SOFTWARE_UPDATE */

640
  oc_set_max_app_data_size(32768);
641 642 643 644 645 646 647 648
  init = oc_main_init(&handler);
  if (init < 0)
    return init;

  if (pthread_create(&event_thread, NULL, &ocf_event_thread, NULL) != 0) {
    return -1;
  }

649 650
  display_device_uuid();

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
  int c;
  while (quit != 1) {
    display_menu();
    SCANF("%d", &c);
    switch (c) {
    case 0:
      continue;
      break;
    case 1:
      discover_resources();
      break;
    case 2:
      get_resource(false, false);
      break;
    case 3:
      get_resource(true, false);
      break;
    case 4:
      post_resource(false);
      break;
    case 5:
      post_resource(true);
      break;
    case 6:
      get_resource(false, true);
      break;
    case 7:
      stop_observe_resource(false);
      break;
    case 8:
      get_resource(true, true);
      break;
    case 9:
      stop_observe_resource(true);
      break;
686 687 688 689 690 691
#ifdef OC_CLOUD
    case 20:
      cloud_send_ping();
      break;
#endif /* OC_CLOUD */
    case 99:
692 693 694 695 696 697 698 699 700 701 702
      handle_signal(0);
      break;
    default:
      break;
    }
  }

  pthread_join(event_thread, NULL);
  free_all_resources();
  return 0;
}