-
Notifications
You must be signed in to change notification settings - Fork 6k
/
lwm2m_rd_client.c
1618 lines (1336 loc) · 39.4 KB
/
lwm2m_rd_client.c
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017 Linaro Limited
* Copyright (c) 2017-2019 Foundries.io
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
* Copyright (c) 2015, Yanzi Networks AB.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Original authors:
* Joakim Eriksson <joakime@sics.se>
* Niclas Finne <nfi@sics.se>
* Joel Hoglund <joel@sics.se>
*/
#define LOG_MODULE_NAME net_lwm2m_rd_client
#define LOG_LEVEL CONFIG_LWM2M_LOG_LEVEL
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(LOG_MODULE_NAME);
#include <zephyr/types.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <zephyr/init.h>
#include <zephyr/sys/printk.h>
#include <zephyr/net/socket.h>
#include "lwm2m_object.h"
#include "lwm2m_engine.h"
#include "lwm2m_rd_client.h"
#include "lwm2m_rw_link_format.h"
#include "lwm2m_util.h"
#define LWM2M_RD_CLIENT_URI "rd"
#define SECONDS_TO_UPDATE_EARLY CONFIG_LWM2M_SECONDS_TO_UPDATE_EARLY
#define CLIENT_EP_LEN CONFIG_LWM2M_RD_CLIENT_ENDPOINT_NAME_MAX_LENGTH
#define CLIENT_BINDING_LEN sizeof("UQ")
#define CLIENT_QUEUE_LEN sizeof("Q")
static void sm_handle_registration_update_failure(void);
static int sm_send_registration_msg(void);
static bool sm_is_suspended(void);
static void lwm2m_rd_client_service(struct k_work *work);
static int64_t calc_next_event(void);
/* The states for the RD client state machine */
/*
* When node is unregistered it ends up in UNREGISTERED
* and this is going to be there until use X or Y kicks it
* back into INIT again
*/
enum sm_engine_state {
ENGINE_IDLE,
ENGINE_INIT,
#if defined(CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP)
ENGINE_DO_BOOTSTRAP_REG,
ENGINE_BOOTSTRAP_REG_SENT,
ENGINE_BOOTSTRAP_REG_DONE,
ENGINE_BOOTSTRAP_TRANS_DONE,
#endif
ENGINE_DO_REGISTRATION,
ENGINE_SEND_REGISTRATION,
ENGINE_REGISTRATION_SENT,
ENGINE_REGISTRATION_DONE,
ENGINE_REGISTRATION_DONE_RX_OFF,
ENGINE_UPDATE_REGISTRATION,
ENGINE_UPDATE_SENT,
ENGINE_SUSPENDED,
ENGINE_DEREGISTER,
ENGINE_DEREGISTER_SENT,
ENGINE_DEREGISTERED,
ENGINE_NETWORK_ERROR,
};
struct lwm2m_rd_client_info {
struct k_mutex mutex;
struct lwm2m_message rd_message;
struct lwm2m_ctx *ctx;
uint32_t lifetime;
uint8_t engine_state;
uint8_t retries;
uint8_t retry_delay;
int64_t last_update;
int64_t last_tx;
int64_t next_event;
char ep_name[CLIENT_EP_LEN];
char server_ep[CLIENT_EP_LEN];
bool use_bootstrap : 1;
bool trigger_update : 1;
bool update_objects : 1;
bool close_socket : 1;
} client;
/* Allocate some data for queries and updates. Make sure it's large enough to
* hold the largest query string, which in most cases will be the endpoint
* string. In other case, 32 bytes are enough to encode any other query string
* documented in the LwM2M specification.
*/
static char query_buffer[MAX(32, sizeof("ep=") + CLIENT_EP_LEN)];
static enum sm_engine_state suspended_client_state;
static struct lwm2m_message *rd_get_message(void)
{
if (client.rd_message.ctx) {
/* Free old message */
lwm2m_reset_message(&client.rd_message, true);
}
client.rd_message.ctx = client.ctx;
return &client.rd_message;
}
static void rd_client_message_free(void)
{
lwm2m_reset_message(lwm2m_get_ongoing_rd_msg(), true);
}
struct lwm2m_message *lwm2m_get_ongoing_rd_msg(void)
{
if (!client.ctx || !client.rd_message.ctx) {
return NULL;
}
return &client.rd_message;
}
void engine_update_tx_time(void)
{
client.last_tx = k_uptime_get();
}
static void next_event_at(int64_t timestamp)
{
(void)lwm2m_engine_call_at(lwm2m_rd_client_service, timestamp);
}
static void set_sm_state(uint8_t sm_state)
{
k_mutex_lock(&client.mutex, K_FOREVER);
enum lwm2m_rd_client_event event = LWM2M_RD_CLIENT_EVENT_NONE;
/* Determine if a callback to the app is needed */
#if defined(CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP)
if (sm_state == ENGINE_BOOTSTRAP_REG_DONE) {
event = LWM2M_RD_CLIENT_EVENT_BOOTSTRAP_REG_COMPLETE;
} else if (client.engine_state == ENGINE_BOOTSTRAP_TRANS_DONE &&
sm_state == ENGINE_DO_REGISTRATION) {
event = LWM2M_RD_CLIENT_EVENT_BOOTSTRAP_TRANSFER_COMPLETE;
} else
#endif
if (client.engine_state == ENGINE_UPDATE_SENT &&
(sm_state == ENGINE_REGISTRATION_DONE ||
sm_state == ENGINE_REGISTRATION_DONE_RX_OFF)) {
lwm2m_push_queued_buffers(client.ctx);
event = LWM2M_RD_CLIENT_EVENT_REG_UPDATE_COMPLETE;
} else if (sm_state == ENGINE_REGISTRATION_DONE) {
lwm2m_push_queued_buffers(client.ctx);
event = LWM2M_RD_CLIENT_EVENT_REGISTRATION_COMPLETE;
} else if (sm_state == ENGINE_REGISTRATION_DONE_RX_OFF) {
event = LWM2M_RD_CLIENT_EVENT_QUEUE_MODE_RX_OFF;
} else if ((sm_state == ENGINE_INIT ||
sm_state == ENGINE_DEREGISTERED) &&
(client.engine_state >= ENGINE_DO_REGISTRATION &&
client.engine_state <= ENGINE_DEREGISTER_SENT)) {
event = LWM2M_RD_CLIENT_EVENT_DISCONNECT;
} else if (sm_state == ENGINE_NETWORK_ERROR) {
lwm2m_socket_close(client.ctx);
client.retry_delay = 1 << client.retries;
client.retries++;
if (client.retries > CONFIG_LWM2M_RD_CLIENT_MAX_RETRIES) {
client.retries = 0;
event = LWM2M_RD_CLIENT_EVENT_NETWORK_ERROR;
}
} else if (sm_state == ENGINE_UPDATE_REGISTRATION) {
event = LWM2M_RD_CLIENT_EVENT_REG_UPDATE;
}
if (sm_is_suspended()) {
/* Just change the state where we are going to resume next */
suspended_client_state = sm_state;
} else {
client.engine_state = sm_state;
}
if (event > LWM2M_RD_CLIENT_EVENT_NONE && client.ctx->event_cb) {
client.ctx->event_cb(client.ctx, event);
}
/* Suspend socket after Event callback */
if (event == LWM2M_RD_CLIENT_EVENT_QUEUE_MODE_RX_OFF) {
if (IS_ENABLED(CONFIG_LWM2M_RD_CLIENT_SUSPEND_SOCKET_AT_IDLE) ||
IS_ENABLED(CONFIG_LWM2M_RD_CLIENT_STOP_POLLING_AT_IDLE)) {
lwm2m_socket_suspend(client.ctx);
} else if (IS_ENABLED(CONFIG_LWM2M_RD_CLIENT_CLOSE_SOCKET_AT_IDLE)) {
lwm2m_close_socket(client.ctx);
}
}
next_event_at(0);
k_mutex_unlock(&client.mutex);
}
static bool sm_is_bootstrap(void)
{
#if defined(CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP)
k_mutex_lock(&client.mutex, K_FOREVER);
bool is_bootstrap = (client.engine_state >= ENGINE_DO_BOOTSTRAP_REG &&
client.engine_state <= ENGINE_BOOTSTRAP_TRANS_DONE);
k_mutex_unlock(&client.mutex);
return is_bootstrap;
#else
return false;
#endif
}
static bool sm_is_registered(void)
{
k_mutex_lock(&client.mutex, K_FOREVER);
bool registered = (client.engine_state >= ENGINE_REGISTRATION_DONE &&
client.engine_state <= ENGINE_DEREGISTER_SENT);
k_mutex_unlock(&client.mutex);
return registered;
}
static bool sm_is_suspended(void)
{
k_mutex_lock(&client.mutex, K_FOREVER);
bool suspended = (client.engine_state == ENGINE_SUSPENDED);
k_mutex_unlock(&client.mutex);
return suspended;
}
static uint8_t get_sm_state(void)
{
k_mutex_lock(&client.mutex, K_FOREVER);
uint8_t state = client.engine_state;
k_mutex_unlock(&client.mutex);
return state;
}
static void sm_handle_timeout_state(struct lwm2m_message *msg,
enum sm_engine_state sm_state)
{
k_mutex_lock(&client.mutex, K_FOREVER);
enum lwm2m_rd_client_event event = LWM2M_RD_CLIENT_EVENT_NONE;
#if defined(CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP)
if (client.engine_state == ENGINE_BOOTSTRAP_REG_SENT) {
event = LWM2M_RD_CLIENT_EVENT_BOOTSTRAP_REG_FAILURE;
} else
#endif
{
if (client.engine_state == ENGINE_REGISTRATION_SENT) {
event = LWM2M_RD_CLIENT_EVENT_REG_TIMEOUT;
} else if (client.engine_state == ENGINE_UPDATE_SENT) {
event = LWM2M_RD_CLIENT_EVENT_REG_TIMEOUT;
} else if (client.engine_state == ENGINE_DEREGISTER_SENT) {
event = LWM2M_RD_CLIENT_EVENT_DEREGISTER_FAILURE;
} else {
/* TODO: unknown timeout state */
}
}
set_sm_state(sm_state);
if (event > LWM2M_RD_CLIENT_EVENT_NONE && client.ctx->event_cb) {
client.ctx->event_cb(client.ctx, event);
}
k_mutex_unlock(&client.mutex);
}
static void sm_handle_failure_state(enum sm_engine_state sm_state)
{
k_mutex_lock(&client.mutex, K_FOREVER);
enum lwm2m_rd_client_event event = LWM2M_RD_CLIENT_EVENT_NONE;
#if defined(CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP)
if (client.engine_state == ENGINE_BOOTSTRAP_REG_SENT) {
event = LWM2M_RD_CLIENT_EVENT_BOOTSTRAP_REG_FAILURE;
} else
#endif
if (client.engine_state == ENGINE_REGISTRATION_SENT) {
event = LWM2M_RD_CLIENT_EVENT_REGISTRATION_FAILURE;
} else if (client.engine_state == ENGINE_UPDATE_SENT) {
sm_handle_registration_update_failure();
k_mutex_unlock(&client.mutex);
return;
} else if (client.engine_state == ENGINE_DEREGISTER_SENT) {
event = LWM2M_RD_CLIENT_EVENT_DEREGISTER_FAILURE;
}
lwm2m_engine_stop(client.ctx);
set_sm_state(sm_state);
if (event > LWM2M_RD_CLIENT_EVENT_NONE && client.ctx->event_cb) {
client.ctx->event_cb(client.ctx, event);
}
k_mutex_unlock(&client.mutex);
}
/* force state machine restart */
static void socket_fault_cb(int error)
{
LOG_ERR("RD Client socket error: %d", error);
if (sm_is_bootstrap()) {
client.ctx->sec_obj_inst = -1;
/* force full registration */
client.last_update = 0;
}
lwm2m_socket_close(client.ctx);
/* Network error state causes engine to re-register,
* so only trigger that state if we are not stopping the
* engine.
*/
if (client.engine_state > ENGINE_IDLE &&
client.engine_state < ENGINE_SUSPENDED) {
set_sm_state(ENGINE_NETWORK_ERROR);
} else if (client.engine_state != ENGINE_SUSPENDED) {
sm_handle_failure_state(ENGINE_IDLE);
}
}
/* force re-update with remote peer */
void engine_trigger_update(bool update_objects)
{
k_mutex_lock(&client.mutex, K_FOREVER);
if (client.engine_state < ENGINE_REGISTRATION_SENT ||
client.engine_state > ENGINE_UPDATE_SENT) {
k_mutex_unlock(&client.mutex);
return;
}
client.trigger_update = true;
if (update_objects) {
client.update_objects = true;
}
k_mutex_unlock(&client.mutex);
}
static inline const char *code2str(uint8_t code)
{
switch (code) {
case COAP_RESPONSE_CODE_BAD_REQUEST:
return "Bad Request";
case COAP_RESPONSE_CODE_FORBIDDEN:
return "Forbidden";
case COAP_RESPONSE_CODE_NOT_FOUND:
return "Not Found";
case COAP_RESPONSE_CODE_PRECONDITION_FAILED:
return "Precondition Failed";
default:
break;
}
return "Unknown";
}
/* state machine reply callbacks */
#if defined(CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP)
static int do_bootstrap_reply_cb(const struct coap_packet *response,
struct coap_reply *reply,
const struct sockaddr *from)
{
uint8_t code;
code = coap_header_get_code(response);
LOG_DBG("Bootstrap callback (code:%u.%u)",
COAP_RESPONSE_CODE_CLASS(code),
COAP_RESPONSE_CODE_DETAIL(code));
if (code == COAP_RESPONSE_CODE_CHANGED) {
LOG_INF("Bootstrap registration done!");
set_sm_state(ENGINE_BOOTSTRAP_REG_DONE);
return 0;
}
LOG_ERR("Failed with code %u.%u (%s). Not Retrying.",
COAP_RESPONSE_CODE_CLASS(code), COAP_RESPONSE_CODE_DETAIL(code),
code2str(code));
sm_handle_failure_state(ENGINE_IDLE);
return 0;
}
static void do_bootstrap_reg_timeout_cb(struct lwm2m_message *msg)
{
LOG_WRN("Bootstrap Timeout");
/* TODO:
* Look for the "next" BOOTSTRAP server entry in our security info
*/
/* Restart from scratch */
sm_handle_timeout_state(msg, ENGINE_INIT);
}
#endif
int engine_trigger_bootstrap(void)
{
#if defined(CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP)
k_mutex_lock(&client.mutex, K_FOREVER);
if (client.use_bootstrap) {
/* Bootstrap is not possible to trig */
LOG_WRN("Bootstrap process ongoing");
k_mutex_unlock(&client.mutex);
return -EPERM;
}
LOG_INF("Server Initiated Bootstrap");
/* Free ongoing possible message */
rd_client_message_free();
client.use_bootstrap = true;
client.trigger_update = false;
client.engine_state = ENGINE_INIT;
next_event_at(0);
k_mutex_unlock(&client.mutex);
return 0;
#else
return -EPERM;
#endif
}
static int do_registration_reply_cb(const struct coap_packet *response,
struct coap_reply *reply,
const struct sockaddr *from)
{
struct coap_option options[2];
uint8_t code;
int ret = -EINVAL;
code = coap_header_get_code(response);
LOG_DBG("Registration callback (code:%u.%u)",
COAP_RESPONSE_CODE_CLASS(code),
COAP_RESPONSE_CODE_DETAIL(code));
/* check state and possibly set registration to done */
if (code == COAP_RESPONSE_CODE_CREATED) {
ret = coap_find_options(response, COAP_OPTION_LOCATION_PATH,
options, 2);
if (ret < 2) {
LOG_ERR("Unexpected endpoint data returned. ret = %d", ret);
ret = -EINVAL;
goto fail;
}
/* option[0] should be "rd" */
if (options[1].len + 1 > sizeof(client.server_ep)) {
LOG_ERR("Unexpected length of query: "
"%u (expected %zu)\n",
options[1].len,
sizeof(client.server_ep));
ret = -EINVAL;
goto fail;
}
/* remember the last reg time */
client.last_update = k_uptime_get();
memcpy(client.server_ep, options[1].value,
options[1].len);
client.server_ep[options[1].len] = '\0';
set_sm_state(ENGINE_REGISTRATION_DONE);
LOG_INF("Registration Done (EP='%s')",
client.server_ep);
return 0;
} else if (code == COAP_RESPONSE_CODE_CONTINUE) {
#if defined(CONFIG_LWM2M_COAP_BLOCK_TRANSFER)
return 0;
#else
LOG_ERR("Response code CONTINUE not supported");
#endif
}
LOG_ERR("Failed with code %u.%u (%s). Not Retrying.",
COAP_RESPONSE_CODE_CLASS(code), COAP_RESPONSE_CODE_DETAIL(code),
code2str(code));
fail:
sm_handle_failure_state(ENGINE_IDLE);
return ret;
}
static void do_registration_timeout_cb(struct lwm2m_message *msg)
{
LOG_WRN("Registration Timeout");
/* Restart from scratch */
sm_handle_timeout_state(msg, ENGINE_INIT);
}
static int do_update_reply_cb(const struct coap_packet *response,
struct coap_reply *reply,
const struct sockaddr *from)
{
uint8_t code;
code = coap_header_get_code(response);
LOG_INF("Update callback (code:%u.%u)",
COAP_RESPONSE_CODE_CLASS(code),
COAP_RESPONSE_CODE_DETAIL(code));
/* If NOT_FOUND just continue on */
if ((code == COAP_RESPONSE_CODE_CHANGED) ||
(code == COAP_RESPONSE_CODE_CREATED)) {
/* remember the last reg time */
client.last_update = k_uptime_get();
set_sm_state(ENGINE_REGISTRATION_DONE);
LOG_INF("Update Done");
return 0;
}
LOG_ERR("Failed with code %u.%u (%s). Retrying registration.",
COAP_RESPONSE_CODE_CLASS(code), COAP_RESPONSE_CODE_DETAIL(code),
code2str(code));
sm_handle_failure_state(ENGINE_DO_REGISTRATION);
return 0;
}
static void do_update_timeout_cb(struct lwm2m_message *msg)
{
LOG_WRN("Registration Update Timeout");
if (client.ctx->sock_fd > -1) {
client.close_socket = true;
}
/* Re-do registration */
sm_handle_timeout_state(msg, ENGINE_DO_REGISTRATION);
}
static int do_deregister_reply_cb(const struct coap_packet *response,
struct coap_reply *reply,
const struct sockaddr *from)
{
uint8_t code;
code = coap_header_get_code(response);
LOG_DBG("Deregister callback (code:%u.%u)",
COAP_RESPONSE_CODE_CLASS(code),
COAP_RESPONSE_CODE_DETAIL(code));
if (code == COAP_RESPONSE_CODE_DELETED) {
LOG_INF("Deregistration success");
set_sm_state(ENGINE_DEREGISTERED);
return 0;
}
LOG_ERR("Failed with code %u.%u (%s). Not Retrying",
COAP_RESPONSE_CODE_CLASS(code), COAP_RESPONSE_CODE_DETAIL(code),
code2str(code));
sm_handle_failure_state(ENGINE_IDLE);
return 0;
}
static void do_deregister_timeout_cb(struct lwm2m_message *msg)
{
LOG_WRN("De-Registration Timeout");
sm_handle_timeout_state(msg, ENGINE_IDLE);
}
static bool sm_bootstrap_verify(bool bootstrap_server, int sec_obj_inst)
{
bool bootstrap;
int ret;
ret = lwm2m_get_bool(&LWM2M_OBJ(0, sec_obj_inst, 1), &bootstrap);
if (ret < 0) {
LOG_WRN("Failed to check bootstrap, err %d", ret);
return false;
}
if (bootstrap == bootstrap_server) {
return true;
} else {
return false;
}
}
static bool sm_update_lifetime(int srv_obj_inst, uint32_t *lifetime)
{
uint32_t new_lifetime;
if (lwm2m_get_u32(&LWM2M_OBJ(1, srv_obj_inst, 1), &new_lifetime) < 0) {
new_lifetime = CONFIG_LWM2M_ENGINE_DEFAULT_LIFETIME;
LOG_INF("Using default lifetime: %u", new_lifetime);
}
if (new_lifetime < CONFIG_LWM2M_ENGINE_DEFAULT_LIFETIME) {
new_lifetime = CONFIG_LWM2M_ENGINE_DEFAULT_LIFETIME;
lwm2m_set_u32(&LWM2M_OBJ(1, srv_obj_inst, 1), new_lifetime);
LOG_INF("Overwrite a server lifetime with default");
}
if (new_lifetime != *lifetime) {
*lifetime = new_lifetime;
return true;
}
return false;
}
static int sm_select_server_inst(int sec_obj_inst, int *srv_obj_inst,
uint32_t *lifetime)
{
uint16_t server_id;
int ret, obj_inst_id;
ret = lwm2m_get_u16(&LWM2M_OBJ(0, sec_obj_inst, 10), &server_id);
if (ret < 0) {
LOG_WRN("Failed to obtain Short Server ID, err %d", ret);
return -EINVAL;
}
obj_inst_id = lwm2m_server_short_id_to_inst(server_id);
if (obj_inst_id < 0) {
LOG_WRN("Failed to obtain Server Object instance, err %d",
obj_inst_id);
return -EINVAL;
}
sm_update_lifetime(obj_inst_id, lifetime);
*srv_obj_inst = obj_inst_id;
return 0;
}
static int sm_select_security_inst(bool bootstrap_server, int *sec_obj_inst)
{
int i, obj_inst_id = -1;
/* lookup existing index */
i = lwm2m_security_inst_id_to_index(*sec_obj_inst);
if (i >= 0 && sm_bootstrap_verify(bootstrap_server, *sec_obj_inst)) {
return 0;
}
*sec_obj_inst = -1;
/* Iterate over all instances to find the correct one. */
for (i = 0; i < CONFIG_LWM2M_SECURITY_INSTANCE_COUNT; i++) {
obj_inst_id = lwm2m_security_index_to_inst_id(i);
if (obj_inst_id < 0) {
LOG_WRN("Failed to get inst id for %d", i);
continue;
}
if (sm_bootstrap_verify(bootstrap_server, obj_inst_id)) {
*sec_obj_inst = obj_inst_id;
return 0;
}
}
LOG_WRN("sec_obj_inst: No matching servers found.");
return -ENOENT;
}
/* state machine step functions */
static int sm_do_init(void)
{
lwm2m_engine_stop(client.ctx);
client.ctx->sec_obj_inst = -1;
client.ctx->srv_obj_inst = -1;
client.trigger_update = false;
client.lifetime = 0U;
client.retries = 0U;
client.last_update = 0U;
client.close_socket = false;
/* Do bootstrap or registration */
#if defined(CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP)
if (client.use_bootstrap) {
set_sm_state(ENGINE_DO_BOOTSTRAP_REG);
} else {
set_sm_state(ENGINE_DO_REGISTRATION);
}
#else
set_sm_state(ENGINE_DO_REGISTRATION);
#endif
return 0;
}
#if defined(CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP)
static int sm_send_bootstrap_registration(void)
{
struct lwm2m_message *msg;
int ret;
msg = rd_get_message();
if (!msg) {
LOG_ERR("Unable to get a lwm2m message!");
return -ENOMEM;
}
msg->type = COAP_TYPE_CON;
msg->code = COAP_METHOD_POST;
msg->mid = coap_next_id();
msg->tkl = LWM2M_MSG_TOKEN_GENERATE_NEW;
msg->reply_cb = do_bootstrap_reply_cb;
msg->message_timeout_cb = do_bootstrap_reg_timeout_cb;
ret = lwm2m_init_message(msg);
if (ret) {
goto cleanup;
}
/* TODO: handle return error */
coap_packet_append_option(&msg->cpkt, COAP_OPTION_URI_PATH,
"bs", strlen("bs"));
snprintk(query_buffer, sizeof(query_buffer) - 1, "ep=%s",
client.ep_name);
/* TODO: handle return error */
coap_packet_append_option(&msg->cpkt, COAP_OPTION_URI_QUERY,
query_buffer, strlen(query_buffer));
if (IS_ENABLED(CONFIG_LWM2M_VERSION_1_1)) {
int pct = LWM2M_FORMAT_OMA_TLV;
if (IS_ENABLED(CONFIG_LWM2M_RW_SENML_CBOR_SUPPORT)) {
pct = LWM2M_FORMAT_APP_SENML_CBOR;
} else if (IS_ENABLED(CONFIG_LWM2M_RW_SENML_JSON_SUPPORT)) {
pct = LWM2M_FORMAT_APP_SEML_JSON;
}
snprintk(query_buffer, sizeof(query_buffer) - 1, "pct=%d", pct);
coap_packet_append_option(&msg->cpkt, COAP_OPTION_URI_QUERY,
query_buffer, strlen(query_buffer));
}
/* log the bootstrap attempt */
LOG_DBG("Register ID with bootstrap server as '%s'",
query_buffer);
lwm2m_send_message_async(msg);
return 0;
cleanup:
lwm2m_reset_message(msg, true);
return ret;
}
static int sm_do_bootstrap_reg(void)
{
int ret;
/* clear out existing connection data */
if (client.ctx->sock_fd > -1) {
lwm2m_engine_stop(client.ctx);
}
client.ctx->bootstrap_mode = true;
ret = sm_select_security_inst(client.ctx->bootstrap_mode,
&client.ctx->sec_obj_inst);
if (ret < 0) {
/* no bootstrap server found, let's move to registration */
LOG_WRN("Bootstrap server not found! Try normal registration.");
set_sm_state(ENGINE_DO_REGISTRATION);
return ret;
}
LOG_INF("Bootstrap started with endpoint '%s' with client lifetime %d",
client.ep_name, client.lifetime);
ret = lwm2m_engine_start(client.ctx);
if (ret < 0) {
LOG_ERR("Cannot init LWM2M engine (%d)", ret);
set_sm_state(ENGINE_NETWORK_ERROR);
return ret;
}
ret = sm_send_bootstrap_registration();
if (!ret) {
set_sm_state(ENGINE_BOOTSTRAP_REG_SENT);
} else {
LOG_ERR("Bootstrap registration err: %d", ret);
set_sm_state(ENGINE_NETWORK_ERROR);
}
return ret;
}
void engine_bootstrap_finish(void)
{
LOG_INF("Bootstrap data transfer done!");
set_sm_state(ENGINE_BOOTSTRAP_TRANS_DONE);
}
static int sm_bootstrap_trans_done(void)
{
/* close down context resources */
lwm2m_engine_stop(client.ctx);
/* reset security object instance */
client.ctx->sec_obj_inst = -1;
client.use_bootstrap = false;
set_sm_state(ENGINE_DO_REGISTRATION);
return 0;
}
#endif
static int sm_send_registration(bool send_obj_support_data,
coap_reply_t reply_cb,
lwm2m_message_timeout_cb_t timeout_cb)
{
struct lwm2m_message *msg;
int ret;
char binding[CLIENT_BINDING_LEN];
char queue[CLIENT_QUEUE_LEN];
msg = rd_get_message();
if (!msg) {
LOG_ERR("Unable to get a lwm2m message!");
return -ENOMEM;
}
msg->type = COAP_TYPE_CON;
msg->code = COAP_METHOD_POST;
msg->mid = coap_next_id();
msg->tkl = LWM2M_MSG_TOKEN_GENERATE_NEW;
msg->reply_cb = reply_cb;
msg->message_timeout_cb = timeout_cb;
ret = lwm2m_init_message(msg);
if (ret) {
goto cleanup;
}
ret = coap_packet_append_option(&msg->cpkt, COAP_OPTION_URI_PATH,
LWM2M_RD_CLIENT_URI,
strlen(LWM2M_RD_CLIENT_URI));
if (ret < 0) {
goto cleanup;
}
if (sm_is_registered()) {
ret = coap_packet_append_option(
&msg->cpkt, COAP_OPTION_URI_PATH,
client.server_ep, strlen(client.server_ep));
if (ret < 0) {
goto cleanup;
}
}
if (send_obj_support_data) {
ret = coap_append_option_int(
&msg->cpkt, COAP_OPTION_CONTENT_FORMAT,
LWM2M_FORMAT_APP_LINK_FORMAT);
if (ret < 0) {
goto cleanup;
}
}
if (!sm_is_registered()) {
snprintk(query_buffer, sizeof(query_buffer) - 1,
"lwm2m=%s", LWM2M_PROTOCOL_VERSION_STRING);
ret = coap_packet_append_option(
&msg->cpkt, COAP_OPTION_URI_QUERY,
query_buffer, strlen(query_buffer));
if (ret < 0) {
goto cleanup;
}
snprintk(query_buffer, sizeof(query_buffer) - 1,
"ep=%s", client.ep_name);
ret = coap_packet_append_option(
&msg->cpkt, COAP_OPTION_URI_QUERY,
query_buffer, strlen(query_buffer));
if (ret < 0) {
goto cleanup;
}
}
/* Send lifetime only if changed or on initial registration.*/
if (sm_update_lifetime(client.ctx->srv_obj_inst, &client.lifetime) ||
!sm_is_registered()) {
snprintk(query_buffer, sizeof(query_buffer) - 1,
"lt=%d", client.lifetime);
ret = coap_packet_append_option(
&msg->cpkt, COAP_OPTION_URI_QUERY,
query_buffer, strlen(query_buffer));
if (ret < 0) {
goto cleanup;
}
}
lwm2m_engine_get_binding(binding);
lwm2m_engine_get_queue_mode(queue);
/* UDP is a default binding, no need to add option if UDP without queue is used. */
if ((!sm_is_registered() && (strcmp(binding, "U") != 0 || strcmp(queue, "Q") == 0))) {
snprintk(query_buffer, sizeof(query_buffer) - 1,
"b=%s", binding);
ret = coap_packet_append_option(
&msg->cpkt, COAP_OPTION_URI_QUERY,
query_buffer, strlen(query_buffer));
if (ret < 0) {
goto cleanup;
}
#if CONFIG_LWM2M_VERSION_1_1
/* In LwM2M 1.1, queue mode is a separate parameter */
uint16_t len = strlen(queue);
if (len) {
ret = coap_packet_append_option(
&msg->cpkt, COAP_OPTION_URI_QUERY,
queue, len);
if (ret < 0) {
goto cleanup;
}
}
#endif
}
if (send_obj_support_data) {
ret = coap_packet_append_payload_marker(&msg->cpkt);
if (ret < 0) {
goto cleanup;
}
msg->out.out_cpkt = &msg->cpkt;
msg->out.writer = &link_format_writer;
ret = do_register_op_link_format(msg);
if (ret < 0) {
goto cleanup;
}
}
lwm2m_send_message_async(msg);
/* log the registration attempt */
LOG_DBG("registration sent [%s]",
lwm2m_sprint_ip_addr(&client.ctx->remote_addr));
return 0;
cleanup:
LOG_ERR("error %d when sending registration message", ret);
lwm2m_reset_message(msg, true);
return ret;
}