-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseaplus.c
More file actions
1359 lines (963 loc) · 33.4 KB
/
Copy pathseaplus.c
File metadata and controls
1359 lines (963 loc) · 33.4 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
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) 2018-2026 Olivier Boudeville
*
* This file is part of the Ceylan-Seaplus library.
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License or
* the GNU General Public License, as they are published by the Free Software
* Foundation, either version 3 of these Licenses, or (at your option)
* any later version.
* You can also redistribute it and/or modify it under the terms of the
* Mozilla Public License, version 1.1 or later.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License and the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License, of the GNU General Public License and of the Mozilla Public License
* along with this library.
* If not, see <http://www.gnu.org/licenses/> and
* <http://www.mozilla.org/MPL/>.
*
* Author: Olivier Boudeville [olivier (dot) boudeville (at) esperide (dot) com]
* Creation date: Sunday, December 16, 2018.
*
*/
#include "seaplus.h"
// For read and write, get_pid:
#include <unistd.h>
// For time and localtime:
#include <time.h>
// For exit, free:
#include <stdlib.h>
// For strlen:
#include <string.h>
// For fprintf, sprintf:
#include <stdio.h>
// For vffprintf:
#include <stdarg.h>
// For strerror:
#include <errno.h>
const char *default_log_base_filename = "seaplus-driver";
/* Current size of the input buffer (possibly increased during the processing),
* used for decoding input parameters:
*
*/
// If wanting to test buffer expansion:
// byte_count input_buffer_size = 4 ;
byte_count input_buffer_size = 4096 * 8;
// Default upper bound of string sizes:
const byte_count string_size = 150;
// For reading and writing terms:
input_buffer buffer = NULL;
// Actual file used for logging:
FILE *log_file = NULL;
/**
* Tells whether a list (e.g. the top-level parameter one, or one that is nested
* in it) was wrongly encoded by term_to_binary/1 as a string (a series of
* bytes, i.e. 8-bit characters) instead of a real list happening to contain
* only small integers; see
* http://erlang.org/doc/man/ei.html#ei_decode_list_header for more details.
*
* This "simple" scheme will work as string-encoded lists cannot be nested (so
* there is up to one level of them).
*
* Note that, afterwards, for that command, only read_int_parameter/2 will read
* its data from that list-as-a-string.
*
*/
bool encoded_as_string;
/**
* The temporary string whence list element will be read, should an unintended
* string-encoding of a list have been done:
*
*/
char *encoded_string = NULL;
/**
* The index within a list encoded as a string corresponding to the next
* (integer) element that will be read:
*
*/
buffer_index encoded_index;
// The number of elements in any current list encoded as a string:
list_size encoded_length;
#include <stdio.h>
// Forward references:
void check_encoded_list();
char *interpret_type_at(const input_buffer buffer, const buffer_index *index);
/*
* Logging is especially useful as drivers, based on C-nodes, are silently run
* and leave no trace.
*
*/
void start_logging(const char *log_filename) {
#if SEAPLUS_ENABLE_LOG
if (log_file == NULL) {
/* Opens a text file for writing, truncating it; if it does not exist,
* then a new file is created:
*/
log_file = fopen(log_filename, "w");
// No buffering wanted here:
setbuf(log_file, NULL);
log_debug("Logger for Seaplus driver: starting new session...");
} else {
log_debug("Error: Seaplus session already started.");
}
#endif // SEAPLUS_ENABLE_LOG
}
void stop_logging() {
#if SEAPLUS_ENABLE_LOG
if (log_file != NULL) {
log_debug("Stopping Seaplus session.");
fclose(log_file);
log_file = NULL;
}
#endif // SEAPLUS_ENABLE_LOG
}
#define SEAPLUS_TIMESTAMP_FORMAT "[%d/%d/%d %d:%02d:%02d]"
// Logs the specified debug message.
void log_debug(const char *format, ...) {
if (log_file != NULL) {
time_t t = time(NULL);
struct tm tm = *localtime(&t);
fprintf(log_file, SEAPLUS_TIMESTAMP_FORMAT "[debug] ", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
va_list arg_ptr;
va_start(arg_ptr, format);
vfprintf(log_file, format, arg_ptr);
va_end(arg_ptr);
fprintf(log_file, "\n");
}
}
// Logs the specified trace message.
void log_trace(const char *format, ...) {
if (log_file != NULL) {
time_t t = time(NULL);
struct tm tm = *localtime(&t);
fprintf(log_file, SEAPLUS_TIMESTAMP_FORMAT "[trace] ", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
va_list arg_ptr;
va_start(arg_ptr, format);
vfprintf(log_file, format, arg_ptr);
va_end(arg_ptr);
fprintf(log_file, "\n");
}
}
// Logs the specified warning message.
void log_warning(const char *format, ...) {
if (log_file != NULL) {
time_t t = time(NULL);
struct tm tm = *localtime(&t);
fprintf(log_file, SEAPLUS_TIMESTAMP_FORMAT "[warning] ", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
va_list arg_ptr;
va_start(arg_ptr, format);
vfprintf(log_file, format, arg_ptr);
va_end(arg_ptr);
fprintf(log_file, "\n");
}
}
// Logs the specified error message.
void log_error(const char *format, ...) {
if (log_file != NULL) {
time_t t = time(NULL);
struct tm tm = *localtime(&t);
fprintf(log_file, SEAPLUS_TIMESTAMP_FORMAT "[error] ", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
va_list arg_ptr;
va_start(arg_ptr, format);
vfprintf(log_file, format, arg_ptr);
va_end(arg_ptr);
fprintf(log_file, "\n");
}
}
/* Raises the specified error, based on specified arguments: reports it in logs,
* and halts.
*
*/
void raise_error(const char *format, ...) {
va_list extra_values;
va_start(extra_values, format);
raise_error_variadic(format, &extra_values);
va_end(extra_values);
}
/* Raises the specified error, based on a variadic argument: reports it in logs,
* and halts.
*
* Useful to report errors from a driver. For an example, see in Ceylan-Mobile:
* void raise_gammu_error( GSM_StateMachine * gammu_fsm,
* const char * format, ... )
*
* Of course crashing the Seaplus driver will impact (freeze/time-out) any
* process trying to interact with it.
*
*/
void raise_error_variadic(const char *format, va_list *values) {
// (log_error could be used)
if (log_file != NULL) {
fprintf(log_file, "[error] ");
vfprintf(log_file, format, *values);
fprintf(log_file, "\n");
}
exit(EXIT_FAILURE);
}
// Reference function comments to be found in seaplus.h.
/**
* Starts the C driver.
*
* Returns the (plain) input buffer (for parameter decoding).
*
*/
void start_seaplus_driver(input_buffer buf) {
pid_t current_pid = getpid();
char log_filename[100];
int res = sprintf(log_filename, "%s.%i.log", default_log_base_filename,
current_pid);
if (res < 0)
exit(EXIT_FAILURE);
start_logging(log_filename);
// Now always written, even in debug mode:
log_debug("Starting the Seaplus C driver, with an input buffer of %u bytes.",
input_buffer_size);
// Needing clarity w.r.t. driver log activation:
#if SEAPLUS_ENABLE_LOG > 0
#ifdef DEBUG_SEAPLUS
log_debug("As SEAPLUS_ENABLE_LOG is defined and not zero, and DEBUG_SEAPLUS is set, all conditional logs are enabled.");
#else
log_debug("SEAPLUS_ENABLE_LOG is defined and not zero, but DEBUG_SEAPLUS is not set, so all conditional logs are disabled.");
#endif
#else
#ifdef DEBUG_SEAPLUS
log_debug("SEAPLUS_ENABLE_LOG is not set to a non-zero value (whereas DEBUG_SEAPLUS is set), so all conditional logs are disabled.");
#else
log_debug("SEAPLUS_ENABLE_LOG is not set to a non-zero value (and DEBUG_SEAPLUS is not set), so all conditional logs are disabled.");
#endif
#endif
ei_error error = ei_init();
if (error != 0)
raise_error("The ei service could not be successfully initialised: %s.",
strerror(error));
*buf = (byte *) malloc(input_buffer_size);
if (*buf == NULL)
raise_error("Allocation of the input buffer failed.");
}
/**
* Stops the C Seaplus driver.
*
*/
void stop_seaplus_driver(input_buffer input_buffer) {
log_debug("Stopping the Seaplus C driver.");
if (encoded_string != NULL) {
free(encoded_string);
encoded_string = NULL;
}
free(*input_buffer);
*input_buffer = NULL;
// No ei_init/0 counterpart found.
stop_logging();
}
/**
* Initialises the main smart buffer (the internal fields thereof) according to
* the Erlang binary format.
*
*/
void init_output_buffer(output_buffer *sm_buf) {
if (ei_x_new_with_version(sm_buf) != 0)
raise_error("Initialization of smart buffer failed.");
}
// Clears the specified smart buffer (the internal fields thereof).
void clear_output_buffer(output_buffer *sm_buf) {
if (ei_x_free(sm_buf) != 0)
raise_error("Clearing of smart buffer failed.");
}
/**
* Prepares for the encoding of the next, upcoming command.
*
* A (smart) buffer is specified, as in some cases (e.g. interrupt handling)
* multiple output buffers may be useful.
*
*/
void prepare_for_command(output_buffer *output_sm_buf) {
/* finalize_command/1 is expected to have already freed appropriately the
* internals of that smart buffer:
*
*/
init_output_buffer(output_sm_buf);
}
/**
* Finalises the current command, supposed to have performed a writing (which is
* by far the most general case).
*
*/
void finalize_command_after_writing(output_buffer *output_sm_buf) {
write_buffer(output_sm_buf);
clear_output_buffer(output_sm_buf);
}
/**
* Reads the specified number of bytes from the specified receive buffer.
*
* Returns, if positive, the number of bytes read, otherwise an error code.
*
* (helper)
*
*/
byte_count read_exact(byte *buf, byte_count len) {
byte_count got = 0;
LOG_DEBUG("%d bytes to read.", len);
do {
// Reading from file descriptor #0:
byte_count i = read(0, buf + got, len - got);
if (i <= 0) {
// Possibly 0 byte if the port has been closed in the meantime:
if (i == 0)
return 0;
// Expected to be -1 (error) then:
raise_error("Reading from buffer %p at position %i "
"for a count of %i bytes failed: %s.",
buf, got, len - got, strerror(errno));
}
LOG_DEBUG("%i bytes actually read.", len);
got += i;
} while (got < len);
LOG_DEBUG("Read %i bytes.", len);
return len;
}
/**
* Receives the next command from the port's input file descriptor, and stores
* it in the specified buffer.
*
*/
byte_count read_command(input_buffer buf) {
LOG_DEBUG("Reading a new command, from address %p.", buf);
// Two bytes for command length:
byte_count len = read_exact(*buf, 2);
// Not reading these length bytes may not be abnormal, if stopping:
if (len == 2) {
// Beware to infamous signed chars and negative lengths:
len =
((((unsigned char *)(*buf))[0]) << 8) | (((unsigned char *)(*buf))[1]);
LOG_DEBUG("Command payload to read: %d bytes.", len);
#ifdef DEBUG_SEAPLUS
if (len < 0)
raise_error("Invalid length to read (%d bytes).", len);
#endif
// Not len + 2, we restart at the beginning of the buffer:
if (len > input_buffer_size) {
/* Better to resize than:
raise_error( "Read length (%i) is too high (buffer size: %i).",
len, input_buffer_size ) ;
*/
LOG_DEBUG("Expanding input buffer from %i bytes to %i.",
input_buffer_size, len);
// May involve a useless copy as will be overwritten:
byte *tmp = (byte *)realloc(*buf, len);
if (tmp == NULL) {
raise_error("Could not expand input buffer from %i bytes to %i.",
input_buffer_size, len);
} else {
*buf = tmp;
input_buffer_size = len;
}
}
return read_exact(*buf, len);
} else {
if (len == 0) {
LOG_DEBUG("No byte read, port expected to be closed.");
return 0;
} else {
raise_error("Reading of the length of the command buffer failed "
"(read %i bytes).",
len);
// Silence compiler:
return 0;
}
}
}
/**
* Determines, from the specified buffer, the information regarding the
* (Erlang-side) specified function, namely its function identifier and its
* parameters, set in the variables whose reference (pointer) is specified.
*
*/
void read_function_information(input_buffer input_buffer, buffer_index *index,
fun_id *current_fun_id, arity *param_count) {
LOG_TRACE("Getting function information.");
int format_version;
/* According to How_to_use_ei_to_marshal_binary_terms_in_port_programs on
* https://erlangcentral.org/wiki, the first token in a binary term is the
* version magic number for the Erlang binary term format (131, at the time
* of this writing).
*
*/
if (ei_decode_version(*input_buffer, index, &format_version) != 0)
raise_error("The version magic number of the binary term format could "
"not be successfully decoded.");
LOG_DEBUG("Read Erlang binary term format version number: %i, "
"from index %i.",
format_version, *index);
/*
* Reads a {FunId, FunParams} pair (e.g. {5, [140, true]}) thanks to, now,
* ei:
*
* (see http://erlang.org/doc/man/ei.html)
*
* A single term (pair) is expected here:
*
*/
tuple_size tuple_s;
if (ei_decode_tuple_header(*input_buffer, index, &tuple_s) != 0)
raise_error("The function pair could not be successfully decoded. "
"Detected type: %s.",
interpret_type_at(input_buffer, index));
if (tuple_s != 2)
raise_error("Unexpected size of function tuple: not a pair, "
"%i elements to decode.",
tuple_s);
/* Gets the first element of the pair, i.e. the Seaplus-defined function
* identifier (e.g. whose value is FOO_1_ID):
*
*/
if (ei_decode_long(*input_buffer, index, current_fun_id) != 0)
raise_error("The function identifier could not be successfully "
"decoded. Detected type: %s.",
interpret_type_at(input_buffer, index));
LOG_DEBUG("Reading command: function identifier is %i (index is %i).",
*current_fun_id, *index);
/* Second element of the pair is the list of the call parameters (hence the
* arity of the function to be called can be checked):
*
*/
read_list_header_parameter(input_buffer, index, param_count);
LOG_DEBUG("%u parameter(s) received for this function.", *param_count);
/* The (*param_count)+1 elements follow in the input buffer, starting from the
* current updated index (the last one is the tail of the list, normally an
* empty list).
*
* The handler for the corresponding function identifier is now to read in
* turn its parameters.
*
*/
LOG_TRACE("Function information obtained.");
}
/**
* Raises an error should the actual arity not be the expected one for the
* specified function.
*
*/
void check_arity_is(arity expected, arity actual, fun_id id) {
if (expected != actual)
raise_error("Expecting arity %u for function identifier %u, "
"got %u instead.",
expected, id, actual);
}
// Accessors to (parameter) values (getters).
/**
* Returns the element at the current buffer location, supposed to be a (long,
* signed) integer.
*
*/
long read_int_parameter(input_buffer decode_buffer, buffer_index *index) {
long res;
// Default, normal case:
if (!encoded_as_string) {
LOG_DEBUG("Reading long integer at index %i.", *index);
ei_error error = ei_decode_long(*decode_buffer, index, &res);
if (error != 0)
raise_error("Parameter at index %i cannot be decoded to (long) integer: "
"%s; its actual type is %s.",
index, strerror(error),
interpret_type_at(decode_buffer, index));
LOG_DEBUG("Read (long, signed) integer parameter %ld.", res);
return res;
} else {
// Here we have an incorrect encoding ([0..255] became string()):
res = (long)encoded_string[encoded_index];
encoded_index++;
if (encoded_index == encoded_length) {
LOG_DEBUG("Read last small integer %ld of string-based list "
"(of size %i).",
res, encoded_length);
free(encoded_string);
encoded_string = NULL;
encoded_as_string = false;
} else {
// Elements start at 1 here:
LOG_DEBUG("Read small integer %ld of string-based list (element %i/%i).",
res, encoded_index, encoded_length);
}
return res;
}
}
/**
* Returns the element at current buffer location, supposed to be a (long,
* unsigned) integer.
*
*/
unsigned long read_unsigned_int_parameter(input_buffer decode_buffer,
buffer_index *index) {
check_encoded_list();
unsigned long res;
ei_error error = ei_decode_ulong(*decode_buffer, index, &res);
if (error != 0)
raise_error("Parameter at index %i cannot be decoded to (long) "
"unsigned integer: %s; its actual type is %s.",
index, strerror(error),
interpret_type_at(decode_buffer, index));
LOG_DEBUG("Read (long, unsigned) integer parameter %ul.", res);
return res;
}
/**
* Returns the element at current buffer location, supposed to be a double.
*
*/
double read_double_parameter(input_buffer decode_buffer, buffer_index *index) {
check_encoded_list();
double res;
ei_error error = ei_decode_double(*decode_buffer, index, &res);
if (error != 0)
raise_error("Parameter at index %i cannot be decoded to double: %s; "
"its actual type is %s.",
index, strerror(error),
interpret_type_at(decode_buffer, index));
LOG_DEBUG("Read double parameter %lf.", res);
return res;
}
/**
* Returns the element at the current buffer location, supposed to be an atom,
* translated to a char*, whose ownership is transferred to the caller (who is
* thus supposed to deallocate it ultimately, with standard free/1).
*
*/
char *read_atom_parameter(input_buffer decode_buffer, buffer_index *index) {
check_encoded_list();
char *res = (char *) malloc(MAXATOMLEN * sizeof(char));
if (res == NULL)
raise_error("Failed to allocate atom buffer.");
ei_error error = ei_decode_atom(*decode_buffer, index, res);
if (error != 0)
raise_error("Parameter at index %i cannot be decoded to atom: %s; "
"its actual type is %s.",
index, strerror(error),
interpret_type_at(decode_buffer, index));
LOG_DEBUG("Read atom parameter '%s'.", res);
return res;
}
/**
* Returns the element at current buffer location, supposed to be a (plain)
* string, whose ownership is transferred to the caller (who is thus supposed to
* deallocate it ultimately, with standard free/1)..
*
*/
char *read_string_parameter(input_buffer decode_buffer, buffer_index *index) {
check_encoded_list();
int type;
int size;
if (ei_get_type(*decode_buffer, index, &type, &size) != 0)
raise_error("Cannot determine the type encoded at index %i", index);
if (type != ERL_STRING_EXT)
raise_error("Not a string at index %i, got %s.", index,
interpret_type_at(decode_buffer, index));
// For the null terminator:
char *res = (char *) malloc((size + 1) * sizeof(char));
if (res == NULL)
raise_error("Failed to allocate string buffer.");
if (ei_decode_string(*decode_buffer, index, res) != 0)
raise_error("Parameter at index %i cannot be decoded to string; "
"its actual type is %s.",
*index, interpret_type_at(decode_buffer, index));
LOG_DEBUG("Read (plain) string: '%s'.", res);
return res;
}
/**
* Returns the element at current buffer location, supposed to be a binary,
* returned as a (plain, null-terminated) string whose ownership is transferred
* to the caller (who is thus supposed to deallocate it ultimately, with
* standard free/1).
*
*/
char *read_binary_parameter(input_buffer decode_buffer, buffer_index *index) {
check_encoded_list();
int type;
int size;
ei_error error = ei_get_type(*decode_buffer, index, &type, &size);
if (error != 0)
raise_error("Cannot determine the type encoded at index %i: %s.", index,
strerror(error));
if (type != ERL_BINARY_EXT)
raise_error("Not a binary at index %i; got %s instead.", index,
interpret_type_at(decode_buffer, index));
// Incremented for null terminator:
size_t buf_size = (size + 1) * sizeof(char);
char *res = (char *) malloc(buf_size);
if (res == NULL)
raise_error("Failed to allocate binary buffer.");
long l_size;
if (ei_decode_binary(*decode_buffer, index, res, &l_size) != 0)
raise_error("Parameter at index %i cannot be decoded to binary: %s; "
"its actual type is %s.",
index, strerror(error),
interpret_type_at(decode_buffer, index));
// Never expected to happen:
if (l_size > buf_size)
raise_error("Buffer overrun when decoding binary.");
/* Makes it a null-terminated string; proved necessary (otherwise the rest of
* the buffer will be read):
*
*/
res[l_size] = (char)0;
LOG_DEBUG("Read binary: '%s'.", res);
return res;
}
/**
* Reads the header of a list that is supposed to exist at current buffer
* location, and sets the specified size accordingly (i.e. with the number of
* elements in that list).
*
* Note: handles transparently the lists containing only small integers (0..255)
* that are unintendendly interpreted as strings.
*
*/
void read_list_header_parameter(input_buffer buffer, buffer_index *index,
arity *size) {
// Init:
encoded_as_string = false;
if (ei_decode_list_header(*buffer, index, size) != 0) {
/* Could not be interpreted as a list, probably because term_to_binary/1
* mistook that list for a string...
*
*/
LOG_DEBUG("List could not be successfully decoded as such; "
"actual detected type: %s (index is %i).",
interpret_type_at(buffer, index), *index);
int type;
if (ei_get_type(*buffer, index, &type, size) != 0)
raise_error("The actual type of the list at %i could not be "
"determined.",
index);
if (type != ERL_STRING_EXT)
raise_error("The actual type of the list is not a string either, "
"it is: %s.",
interpret_type_at(buffer, index));
encoded_as_string = true;
if (encoded_string != NULL)
free(encoded_string);
// Null-terminated:
encoded_string = (char *) malloc((*size + 1) * sizeof(char));
if (ei_decode_string(*buffer, index, encoded_string) != 0)
raise_error("Detected an unintended string-encoding of parameters, "
"yet was not able to decode it.");
LOG_DEBUG("Switching to string-based list of size %i", *size);
encoded_index = 0;
encoded_length = *size;
return;
}
// Here we had a normal list, nothing more to do.
LOG_DEBUG("Normal list found at index %i, having %i element(s).", *index,
*size);
}
/* Second, setters of values, to encode from C to Erlang.
*
*/
/**
* Writes in the specified return buffer the specified bool result.
*
*/
void write_bool_result(output_buffer *output_sm_buf, bool b) {
if (ei_x_encode_boolean(output_sm_buf, b) != 0)
raise_error("Erlang bool encoding failed.");
}
/**
* Writes in the specified return buffer the specified (signed) integer result.
*
*/
void write_int_result(output_buffer *output_sm_buf, int i) {
if (ei_x_encode_long(output_sm_buf, (long)i) != 0)
raise_error("Erlang (signed) integer encoding failed.");
}
/**
* Writes in the specified return buffer the specified unsigned integer result.
*
*/
void write_unsigned_int_result(output_buffer *output_sm_buf, unsigned int u) {
if (ei_x_encode_ulong(output_sm_buf, (unsigned long)u) != 0)
raise_error("Erlang unsigned integer encoding failed.");
}
/**
* Writes in the specified return buffer the specified double result.
*
*/
void write_double_result(output_buffer *output_sm_buf, double d) {
if (ei_x_encode_double(output_sm_buf, d) != 0)
raise_error("Erlang double encoding failed.");
}