forked from blues/note-c
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn_request.c
More file actions
503 lines (443 loc) · 14.8 KB
/
n_request.c
File metadata and controls
503 lines (443 loc) · 14.8 KB
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
/*!
* @file n_request.c
*
* Written by Ray Ozzie and Blues Inc. team.
*
* Copyright (c) 2019 Blues Inc. MIT License. Use of this source code is
* governed by licenses granted by the copyright holder including that found in
* the
* <a href="https://github.com/blues/note-c/blob/master/LICENSE">LICENSE</a>
* file.
*
*/
#include "n_lib.h"
// For flow tracing
static int suppressShowTransactions = 0;
// Flag that gets set whenever an error occurs that should force a reset
static bool resetRequired = true;
/**************************************************************************/
/*!
@brief Create an error response document.
@param errmsg
The error message from the Notecard
@returns a `J` cJSON object with the error response.
*/
/**************************************************************************/
static J *errDoc(const char *errmsg)
{
J *rspdoc = JCreateObject();
if (rspdoc != NULL) {
JAddStringToObject(rspdoc, c_err, errmsg);
}
if (suppressShowTransactions == 0) {
_Debug("{\"err\":\"");
_Debug(errmsg);
_Debug("\"}\n");
}
return rspdoc;
}
/**************************************************************************/
/*!
@brief Suppress showing transaction details.
*/
/**************************************************************************/
void NoteSuspendTransactionDebug()
{
suppressShowTransactions++;
}
/**************************************************************************/
/*!
@brief Resume showing transaction details.
*/
/**************************************************************************/
void NoteResumeTransactionDebug()
{
suppressShowTransactions--;
}
/**************************************************************************/
/*!
@brief Create a new request object to populate before sending to the Notecard.
@param request is The name of the request, for example `hub.set`.
@returns a `J` cJSON object with the request name pre-populated.
*/
/**************************************************************************/
J *NoteNewRequest(const char *request)
{
J *reqdoc = JCreateObject();
if (reqdoc != NULL) {
JAddStringToObject(reqdoc, c_req, request);
}
return reqdoc;
}
/**************************************************************************/
/*!
@brief Create a new command object to populate before sending to the Notecard.
@param request is the name of the command, for example `hub.set`.
@returns a `J` cJSON object with the request name pre-populated.
*/
/**************************************************************************/
J *NoteNewCommand(const char *request)
{
J *reqdoc = JCreateObject();
if (reqdoc != NULL) {
JAddStringToObject(reqdoc, c_cmd, request);
}
return reqdoc;
}
/**************************************************************************/
/*!
@brief Send a request to the Notecard.
Frees the request structure from memory after sending the request.
@param req
The `J` cJSON request object.
@returns a boolean. Returns `true` if successful or `false` if an error
occurs, such as an out-of-memory or if an error was returned from
the transaction in the c_err field.
*/
/**************************************************************************/
bool NoteRequest(J *req)
{
// Exit if null request. This allows safe execution of the form NoteRequest(NoteNewRequest("xxx"))
if (req == NULL) {
return false;
}
// Execute the transaction
J *rsp = NoteTransaction(req);
if (rsp == NULL) {
JDelete(req);
return false;
}
// Check for a transaction error, and exit
bool success = JIsNullString(rsp, c_err);
JDelete(req);
JDelete(rsp);
return success;
}
/**************************************************************************/
/*!
@brief Send a request to the Notecard.
Frees the request structure from memory after sending the request.
Retries the request for up to the specified timeoutSeconds if there is
no response, or if the response indicates an io error.
@param req
The `J` cJSON request object.
timeoutSeconds
Upper limit for retries if there is no response, or if the
response contains an io error.
@returns a boolean. Returns `true` if successful or `false` if an error
occurs, such as an out-of-memory or if an error was returned from
the transaction in the c_err field.
*/
/**************************************************************************/
bool NoteRequestWithRetry(J *req, uint32_t timeoutSeconds)
{
// Exit if null request. This allows safe execution of the form NoteRequest(NoteNewRequest("xxx"))
if (req == NULL) {
return false;
}
J *rsp;
// Calculate expiry time in milliseconds
uint32_t expiresMs = _GetMs() + (timeoutSeconds * 1000);
while(true) {
// Execute the transaction
rsp = NoteTransaction(req);
// Loop if there is no response, or if there is an io error
if ( (rsp == NULL) || JContainsString(rsp, c_err, c_ioerr)) {
// Free error response
if (rsp != NULL) {
JDelete(rsp);
rsp = NULL;
}
} else {
// Exit loop on non-null response without io error
break;
}
// Exit loop on timeout
if (_GetMs() >= expiresMs) {
break;
}
}
// Free the request
JDelete(req);
// If there is no response return false
if (rsp == NULL) {
return false;
}
// Check for a transaction error, and exit
bool success = JIsNullString(rsp, c_err);
JDelete(rsp);
return success;
}
/**************************************************************************/
/*!
@brief Send a request to the Notecard and return the response.
Frees the request structure from memory after sending the request.
@param req
The `J` cJSON request object.
@returns a `J` cJSON object with the response, or NULL if there is
insufficient memory.
*/
/**************************************************************************/
J *NoteRequestResponse(J *req)
{
// Exit if null request. This allows safe execution of the form NoteRequestResponse(NoteNewRequest("xxx"))
if (req == NULL) {
return NULL;
}
// Execute the transaction
J *rsp = NoteTransaction(req);
if (rsp == NULL) {
JDelete(req);
return NULL;
}
// Free the request and exit
JDelete(req);
return rsp;
}
/**************************************************************************/
/*!
@brief Send a request to the Notecard and return the response.
Frees the request structure from memory after sending the request.
Retries the request for up to the specified timeoutSeconds if there is
no response, or if the response indicates an io error.
@param req
The `J` cJSON request object.
timeoutSeconds
Upper limit for retries if there is no response, or if the
response contains an io error.
@returns a `J` cJSON object with the response, or NULL if there is
insufficient memory.
*/
/**************************************************************************/
J *NoteRequestResponseWithRetry(J *req, uint32_t timeoutSeconds)
{
// Exit if null request. This allows safe execution of the form NoteRequestResponse(NoteNewRequest("xxx"))
if (req == NULL) {
return NULL;
}
J *rsp;
// Calculate expiry time in milliseconds
uint32_t expiresMs = _GetMs() + (timeoutSeconds * 1000);
while(true) {
// Execute the transaction
rsp = NoteTransaction(req);
// Loop if there is no response, or if there is an io error
if ( (rsp == NULL) || JContainsString(rsp, c_err, c_ioerr)) {
// Free error response
if (rsp != NULL) {
JDelete(rsp);
rsp = NULL;
}
} else {
// Exit loop on non-null response without io error
break;
}
// Exit loop on timeout
if (_GetMs() >= expiresMs) {
break;
}
}
// Free the request
JDelete(req);
if (rsp == NULL) {
return NULL;
}
// Return the response
return rsp;
}
/**************************************************************************/
/*!
@brief Given a JSON string, send a request to the Notecard.
Frees the request structure from memory after sending the request.
@param reqJSON
A c-string containing the JSON request object.
@returns a c-string with the JSON response from the Notecard. After
parsed by the developer, should be freed with `JFree`.
*/
/**************************************************************************/
char *NoteRequestResponseJSON(char *reqJSON)
{
// Parse the incoming JSON string
J *req = JParse(reqJSON);
if (req == NULL) {
return NULL;
}
// Perform the transaction and free the req
J *rsp = NoteRequestResponse(req);
if (rsp == NULL) {
return NULL;
}
// Convert response back to JSON and delete it
char *json = JPrintUnformatted(rsp);
NoteDeleteResponse(rsp);
if (json == NULL) {
return NULL;
}
// Done
return json;
}
/**************************************************************************/
/*!
@brief Initiate a transaction to the Notecard and return the response.
Does NOT free the request structure from memory after sending
the request.
@param req
The `J` cJSON request object.
@returns a `J` cJSON object with the response, or NULL if there is
insufficient memory.
*/
/**************************************************************************/
J *NoteTransaction(J *req)
{
// Validate in case of memory failure of the requestor
if (req == NULL) {
return NULL;
}
// Determine the request or command type
const char *reqType = JGetString(req, "req");
const char *cmdType = JGetString(req, "cmd");
// Add the user agent object only when we're doing a hub.set and only when we're
// specifying the product UID. The intent is that we only piggyback user agent
// data when the host is initializing the Notecard, as opposed to every time
// the host does a hub.set to change mode.
#ifndef NOTE_DISABLE_USER_AGENT
if (!JIsPresent(req, "body") && (strcmp(reqType, "hub.set") == 0) && JIsPresent(req, "product")) {
J *body = NoteUserAgent();
if (body != NULL) {
JAddItemToObject(req, "body", body);
}
}
#endif
// Determine whether or not a response will be expected, by virtue of "cmd" being present
bool noResponseExpected = (reqType[0] == '\0' && cmdType[0] != '\0');
// If a reset of the module is required for any reason, do it now.
// We must do this before acquiring lock.
if (resetRequired) {
if (!NoteReset()) {
return NULL;
}
}
// Lock
_LockNote();
// Serialize the JSON requet
char *json = JPrintUnformatted(req);
if (json == NULL) {
J *rsp = errDoc(ERRSTR("can't convert to JSON",c_bad));
_UnlockNote();
return rsp;
}
if (suppressShowTransactions == 0) {
_Debugln(json);
}
// Pertform the transaction
char *responseJSON;
const char *errStr;
if (noResponseExpected) {
errStr = _Transaction(json, NULL);
} else {
errStr = _Transaction(json, &responseJSON);
}
// Free the json
JFree(json);
// If error, queue up a reset
if (errStr != NULL) {
NoteResetRequired();
J *rsp = errDoc(errStr);
_UnlockNote();
return rsp;
}
// Exit with a blank object (with no err field) if no response expected
if (noResponseExpected) {
_UnlockNote();
return JCreateObject();
}
// Parse the reply from the card on the input stream
J *rspdoc = JParse(responseJSON);
if (rspdoc == NULL) {
_Debug("invalid JSON: ");
_Debug(responseJSON);
_Free(responseJSON);
J *rsp = errDoc(ERRSTR("unrecognized response from card {io}",c_iobad));
_UnlockNote();
return rsp;
}
// Debug
if (suppressShowTransactions == 0) {
if (responseJSON[strlen(responseJSON)-1] == '\n') {
_Debug(responseJSON);
} else {
_Debugln(responseJSON);
}
}
// Discard the buffer now that it's parsed
_Free(responseJSON);
// Unlock
_UnlockNote();
// Done
return rspdoc;
}
/**************************************************************************/
/*!
@brief Mark that a reset will be required before doing further I/O on
a given port.
*/
/**************************************************************************/
void NoteResetRequired()
{
resetRequired = true;
}
/**************************************************************************/
/*!
@brief Initialize or re-initialize the module, returning false if
anything fails.
@returns a boolean. `true` if the reset was successful, `false`, if not.
*/
/**************************************************************************/
bool NoteReset()
{
_LockNote();
resetRequired = !_Reset();
_UnlockNote();
return !resetRequired;
}
/**************************************************************************/
/*!
@brief Check to see if a Notecard error is present in a JSON string.
@param errstr
The error string.
@param errtype
The error type string.
@returns boolean. `true` if the string contains the error provided, `false`
if not.
*/
/**************************************************************************/
bool NoteErrorContains(const char *errstr, const char *errtype)
{
return (strstr(errstr, errtype) != NULL);
}
/**************************************************************************/
/*!
@brief Clean error strings out of the specified buffer.
@param begin
The string buffer to clear of error strings.
*/
/**************************************************************************/
void NoteErrorClean(char *begin)
{
while (true) {
char *end = &begin[strlen(begin)+1];
char *beginBrace = strchr(begin, '{');
if (beginBrace == NULL) {
break;
}
if (beginBrace>begin && *(beginBrace-1) == ' ') {
beginBrace--;
}
char *endBrace = strchr(beginBrace, '}');
if (endBrace == NULL) {
break;
}
char *afterBrace = endBrace + 1;
memmove(beginBrace, afterBrace, end-afterBrace);
}
}