forked from roastedroot/proxy-wasm-java-host
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathABI.java
More file actions
1924 lines (1688 loc) · 67.7 KB
/
ABI.java
File metadata and controls
1924 lines (1688 loc) · 67.7 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
package io.roastedroot.proxywasm.internal;
import static io.roastedroot.proxywasm.internal.Helpers.bytes;
import static io.roastedroot.proxywasm.internal.Helpers.replaceBytes;
import static io.roastedroot.proxywasm.internal.Helpers.split;
import static io.roastedroot.proxywasm.internal.Helpers.string;
import com.dylibso.chicory.annotations.HostModule;
import com.dylibso.chicory.annotations.WasmExport;
import com.dylibso.chicory.runtime.ExportFunction;
import com.dylibso.chicory.runtime.Instance;
import com.dylibso.chicory.runtime.Memory;
import com.dylibso.chicory.runtime.WasmRuntimeException;
import com.dylibso.chicory.wasm.InvalidException;
import io.roastedroot.proxywasm.LogLevel;
import io.roastedroot.proxywasm.MetricType;
import io.roastedroot.proxywasm.QueueName;
import io.roastedroot.proxywasm.SharedData;
import io.roastedroot.proxywasm.WasmException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@HostModule("env")
class ABI {
private Handler handler;
private Memory memory;
ExportFunction initializeFn;
ExportFunction mainFn;
ExportFunction startFn;
ExportFunction proxyOnContextCreateFn;
ExportFunction proxyOnDoneFn;
ExportFunction mallocFn;
ExportFunction proxyOnLogFn;
ExportFunction proxyOnDeleteFn;
ExportFunction proxyOnVmStartFn;
ExportFunction proxyOnConfigureFn;
ExportFunction proxyOnTickFn;
ExportFunction proxyOnNewConnectionFn;
ExportFunction proxyOnDownstreamDataFn;
ExportFunction proxyOnDownstreamConnectionCloseFn;
ExportFunction proxyOnUpstreamDataFn;
ExportFunction proxyOnUpstreamConnectionCloseFn;
ExportFunction proxyOnRequestHeadersFn;
ExportFunction proxyOnRequestBodyFn;
ExportFunction proxyOnRequestTrailersFn;
ExportFunction proxyOnResponseHeadersFn;
ExportFunction proxyOnResponseBodyFn;
ExportFunction proxyOnResponseTrailersFn;
ExportFunction proxyOnHttpCallResponseFn;
ExportFunction proxyOnGrpcReceiveInitialMetadataFn;
ExportFunction proxyOnGrpcReceiveFn;
ExportFunction proxyOnGrpcReceiveTrailingMetadataFn;
ExportFunction proxyOnGrpcCloseFn;
ExportFunction proxyOnQueueReadyFn;
ExportFunction proxyOnForeignFunctionFn;
Handler getHandler() {
return handler;
}
void setHandler(Handler handler) {
this.handler = handler;
}
void setInstance(Instance instance) {
this.memory = instance.memory();
var exports = instance.exports();
// Since 0_2_0, prefer proxy_on_memory_allocate over malloc
this.mallocFn = lookupFunction(exports, "proxy_on_memory_allocate");
if (this.mallocFn == null) {
this.mallocFn = lookupFunction(exports, "malloc");
}
if (this.mallocFn == null) {
throw new WasmRuntimeException("malloc function not found");
}
this.initializeFn = lookupFunction(exports, "_initialize");
this.mainFn = lookupFunction(exports, "main");
this.startFn = lookupFunction(exports, "_start");
// All callbacks proxyOn* are optional, and will only be called if exposed by the Wasm
// module.
this.proxyOnContextCreateFn = lookupFunction(exports, "proxy_on_context_create");
this.proxyOnDoneFn = lookupFunction(exports, "proxy_on_done");
this.proxyOnLogFn = lookupFunction(exports, "proxy_on_log");
this.proxyOnDeleteFn = lookupFunction(exports, "proxy_on_delete");
this.proxyOnVmStartFn = lookupFunction(exports, "proxy_on_vm_start");
this.proxyOnConfigureFn = lookupFunction(exports, "proxy_on_configure");
this.proxyOnTickFn = lookupFunction(exports, "proxy_on_tick");
this.proxyOnNewConnectionFn = lookupFunction(exports, "proxy_on_new_connection");
this.proxyOnDownstreamDataFn = lookupFunction(exports, "proxy_on_downstream_data");
this.proxyOnDownstreamConnectionCloseFn =
lookupFunction(exports, "proxy_on_downstream_connection_close");
this.proxyOnUpstreamDataFn = lookupFunction(exports, "proxy_on_upstream_data");
this.proxyOnUpstreamConnectionCloseFn =
lookupFunction(exports, "proxy_on_upstream_connection_close");
this.proxyOnRequestHeadersFn = lookupFunction(exports, "proxy_on_request_headers");
this.proxyOnRequestBodyFn = lookupFunction(exports, "proxy_on_request_body");
this.proxyOnRequestTrailersFn = lookupFunction(exports, "proxy_on_request_trailers");
this.proxyOnResponseHeadersFn = lookupFunction(exports, "proxy_on_response_headers");
this.proxyOnResponseBodyFn = lookupFunction(exports, "proxy_on_response_body");
this.proxyOnResponseTrailersFn = lookupFunction(exports, "proxy_on_response_trailers");
this.proxyOnHttpCallResponseFn = lookupFunction(exports, "proxy_on_http_call_response");
this.proxyOnGrpcReceiveInitialMetadataFn =
lookupFunction(exports, "proxy_on_grpc_receive_initial_metadata");
this.proxyOnGrpcReceiveFn = lookupFunction(exports, "proxy_on_grpc_receive");
this.proxyOnGrpcReceiveTrailingMetadataFn =
lookupFunction(exports, "proxy_on_grpc_receive_trailing_metadata");
this.proxyOnGrpcCloseFn = lookupFunction(exports, "proxy_on_grpc_close");
this.proxyOnQueueReadyFn = lookupFunction(exports, "proxy_on_queue_ready");
this.proxyOnForeignFunctionFn = lookupFunction(exports, "proxy_on_foreign_function");
}
// //////////////////////////////////////////////////////////////////////
// Common Helpers
// //////////////////////////////////////////////////////////////////////
// Size of a 32-bit integer in bytes
static final int U32_LEN = 4;
private ExportFunction lookupFunction(Instance.Exports exports, String name) {
try {
return exports.function(name);
} catch (InvalidException e) {
return null;
}
}
/**
* Write a 32-bit unsigned integer to memory().
*
* @param address The address to write to
* @param value The value to write
* @throws WasmException if the memory access is invalid
*/
private void putUint32(int address, int value) throws WasmException {
try {
memory.writeI32(address, value);
} catch (RuntimeException e) {
throw new WasmException(WasmResult.INVALID_MEMORY_ACCESS);
}
}
/**
* Read a 32-bit unsigned integer to memory().
*
* @param address The address to read from
* @throws WasmException if the memory access is invalid
*/
private long getUint32(int address) throws WasmException {
try {
return memory.readU32(address);
} catch (RuntimeException e) {
throw new WasmException(WasmResult.INVALID_MEMORY_ACCESS);
}
}
/**
* Write a byte to memory().
*
* @param address The address to write to
* @param value The value to write
* @throws WasmException if the memory access is invalid
*/
private void putByte(int address, byte value) throws WasmException {
try {
memory.writeByte(address, value);
} catch (RuntimeException e) {
throw new WasmException(WasmResult.INVALID_MEMORY_ACCESS);
}
}
/**
* Write bytes to memory().
*
* @param address The address to write to
* @param data The data to write
* @throws WasmException if the memory access is invalid
*/
private void putMemory(int address, byte[] data) throws WasmException {
try {
memory.write(address, data);
} catch (RuntimeException e) {
throw new WasmException(WasmResult.INVALID_MEMORY_ACCESS);
}
}
/**
* Write bytes to memory().
*
* @param address The address to write to
* @param data The data to write
* @throws WasmException if the memory access is invalid
*/
private void putMemory(int address, ByteBuffer data) throws WasmException {
try {
if (data.hasArray()) {
var array = data.array();
memory.write(address, array, data.position(), data.remaining());
} else {
// This could likely be optimized by extending the memory interface to accept
// ByteBuffer
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
memory.write(address, bytes);
}
} catch (RuntimeException e) {
throw new WasmException(WasmResult.INVALID_MEMORY_ACCESS);
}
}
/**
* Read bytes from memory.
*
* @param address The address to read from
* @param len The number of bytes to read
* @return The value read
* @throws WasmException if the memory access is invalid
*/
private byte[] readMemory(int address, int len) throws WasmException {
try {
return memory.readBytes(address, len);
} catch (RuntimeException e) {
throw new WasmException(WasmResult.INVALID_MEMORY_ACCESS);
}
}
private void copyIntoInstance(byte[] value, int retPtr, int retSize) throws WasmException {
try {
if (value.length != 0) {
int addr = malloc(value.length);
putMemory(addr, value);
putUint32(retPtr, addr);
} else {
putUint32(retPtr, 0);
}
putUint32(retSize, value.length);
} catch (WasmException e) {
throw new WasmException(WasmResult.INVALID_MEMORY_ACCESS);
}
}
// //////////////////////////////////////////////////////////////////////
// Integration
// //////////////////////////////////////////////////////////////////////
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#_initialize
*/
boolean initialize() {
if (this.initializeFn == null) {
return false;
}
this.initializeFn.apply();
return true;
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#main
*/
boolean main(int arg0, int arg1) {
if (mainFn == null) {
return false;
}
mainFn.apply(arg0, arg1);
return true;
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#_start
*/
boolean start() {
if (startFn == null) {
return false;
}
startFn.apply();
return true;
}
// //////////////////////////////////////////////////////////////////////
// Memory management
// //////////////////////////////////////////////////////////////////////
/**
* implements:
* * https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#malloc
* * https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_memory_allocate
*/
int malloc(int size) throws WasmException {
// I've noticed guests fail on malloc(0) so lets avoid that
assert size > 0 : "malloc size must be greater than zero";
long ptr = mallocFn.apply(size)[0];
if (ptr == 0) {
throw new WasmException(WasmResult.INVALID_MEMORY_ACCESS);
}
return (int) ptr;
}
// //////////////////////////////////////////////////////////////////////
// Context lifecycle
// //////////////////////////////////////////////////////////////////////
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_context_create
*/
void proxyOnContextCreate(int contextID, int parentContextID) {
if (proxyOnContextCreateFn == null) {
return;
}
proxyOnContextCreateFn.apply(contextID, parentContextID);
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_done
*/
boolean proxyOnDone(int context_id) {
if (proxyOnDoneFn == null) {
return true;
}
long result = proxyOnDoneFn.apply(context_id)[0];
return result != 0;
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_log
*/
void proxyOnLog(int context_id) {
if (proxyOnLogFn == null) {
return;
}
proxyOnLogFn.apply(context_id);
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_delete
*/
void proxyOnDelete(int context_id) {
if (proxyOnDeleteFn == null) {
return;
}
proxyOnDeleteFn.apply(context_id);
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_done
*/
@WasmExport
int proxyDone() {
return handler.done().getValue();
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_set_effective_context
*/
@WasmExport
int proxySetEffectiveContext(int contextId) {
return handler.setEffectiveContextID(contextId).getValue();
}
// //////////////////////////////////////////////////////////////////////
// Configuration
// //////////////////////////////////////////////////////////////////////
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_vm_start
*/
boolean proxyOnVmStart(int arg0, int arg1) {
if (proxyOnVmStartFn == null) {
return true;
}
long result = proxyOnVmStartFn.apply(arg0, arg1)[0];
return result != 0;
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_configure
*/
boolean proxyOnConfigure(int arg0, int arg1) {
if (proxyOnConfigureFn == null) {
return true;
}
long result = proxyOnConfigureFn.apply(arg0, arg1)[0];
return result != 0;
}
// //////////////////////////////////////////////////////////////////////
// Logging
// //////////////////////////////////////////////////////////////////////
// wasi_snapshot_preview1.fd_write :
// https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#wasi_snapshot_preview1fd_write
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_log
*/
@WasmExport
int proxyLog(int logLevel, int messageData, int messageSize) {
try {
var msg = memory.readBytes(messageData, messageSize);
handler.log(LogLevel.fromInt(logLevel), string(msg));
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_get_log_level
*/
@WasmExport
int proxyGetLogLevel(int returnLogLevel) {
try {
LogLevel level = handler.getLogLevel();
putUint32(returnLogLevel, level.value());
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
// //////////////////////////////////////////////////////////////////////
// Clocks
// //////////////////////////////////////////////////////////////////////
// wasi_snapshot_preview1.clock_time_get
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_get_current_time_nanoseconds
*/
@WasmExport
int proxyGetCurrentTimeNanoseconds(int returnTime) {
try {
int currentTimeNanoseconds = handler.getCurrentTimeNanoseconds();
putUint32(returnTime, currentTimeNanoseconds);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
// //////////////////////////////////////////////////////////////////////
// Timers
// //////////////////////////////////////////////////////////////////////
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_set_tick_period_milliseconds
*/
@WasmExport
int proxySetTickPeriodMilliseconds(int tick_period) {
return handler.setTickPeriodMilliseconds(tick_period).getValue();
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_tick
*/
void proxyOnTick(int arg0) {
if (proxyOnTickFn == null) {
return;
}
proxyOnTickFn.apply(arg0);
}
// //////////////////////////////////////////////////////////////////////
// Randomness
// //////////////////////////////////////////////////////////////////////
// wasi_snapshot_preview1.random_get
// //////////////////////////////////////////////////////////////////////
// Environment variables
// //////////////////////////////////////////////////////////////////////
// wasi_snapshot_preview1.environ_sizes_get
// wasi_snapshot_preview1.environ_get
// //////////////////////////////////////////////////////////////////////
// Buffers
// //////////////////////////////////////////////////////////////////////
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_get_buffer_bytes
*
* @param bufferType The type of buffer to get
* @param start The start index in the buffer
* @param length The number of bytes to get
* @param returnBufferData Pointer to where the buffer data address should be stored
* @param returnBufferSize Pointer to where the buffer size should be stored
* @return WasmResult status code
*/
@WasmExport
int proxyGetBufferBytes(
int bufferType,
int start,
int chunkLength,
int returnBufferData,
int returnBufferSize) {
try {
// Get the buffer based on the buffer type
byte[] b = getBuffer(bufferType);
if (b == null || b.length == 0) {
return WasmResult.NOT_FOUND.getValue();
}
if (start < 0) {
return WasmResult.BAD_ARGUMENT.getValue();
}
int maxChunkLength = b.length - start;
if (chunkLength < 0 || chunkLength > maxChunkLength) {
chunkLength = maxChunkLength;
}
ByteBuffer buffer = ByteBuffer.wrap(b);
if (start + chunkLength > buffer.capacity()) {
chunkLength = buffer.capacity() - start;
}
try {
buffer.position(start);
buffer.limit(start + chunkLength);
} catch (IllegalArgumentException e) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Allocate memory in the WebAssembly instance
int addr = malloc(chunkLength);
putMemory(addr, buffer);
// Write the address to the return pointer
putUint32(returnBufferData, addr);
// Write the length to the return size pointer
putUint32(returnBufferSize, chunkLength);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_set_buffer_bytes
*
* @param bufferType The type of buffer to modify
* @param start The start index in the buffer
* @param length The number of bytes to set
* @param dataPtr Pointer to the data in WebAssembly memory
* @param dataSize Size of the data
* @return WasmResult status code
*/
@WasmExport
int proxySetBufferBytes(int bufferType, int start, int length, int dataPtr, int dataSize) {
try {
// Get the buffer based on the buffer type
var buf = getBuffer(bufferType);
if (buf == null) {
return WasmResult.NOT_FOUND.getValue();
}
// Get content from WebAssembly memory
byte[] content = memory.readBytes(dataPtr, dataSize);
content = replaceBytes(buf, content, start, length);
// Set the buffer using the appropriate handler method
WasmResult result = setBuffer(bufferType, content);
return result.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
}
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_get_buffer_status
*/
@WasmExport
int proxyGetBufferStatus(int bufferType, int returnBufferSize, int returnUnused) {
try {
// Get the buffer based on the buffer type
byte[] b = getBuffer(bufferType);
if (b == null) {
return WasmResult.NOT_FOUND.getValue();
}
// Write the buffer size to the return size pointer
putUint32(returnBufferSize, b.length);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Get a buffer based on the buffer type.
*
* @param bufferType The type of buffer to get
* @return The buffer, or null if not found
*/
private byte[] getBuffer(int bufferType) {
// Return the appropriate buffer based on the buffer type
var knownType = BufferType.fromInt(bufferType);
if (knownType == null) {
return handler.getCustomBuffer(bufferType);
}
switch (knownType) {
case HTTP_REQUEST_BODY:
return handler.getHttpRequestBody();
case HTTP_RESPONSE_BODY:
return handler.getHttpResponseBody();
case DOWNSTREAM_DATA:
return handler.getDownStreamData();
case UPSTREAM_DATA:
return handler.getUpstreamData();
case HTTP_CALL_RESPONSE_BODY:
return handler.getHttpCallResponseBody();
case GRPC_RECEIVE_BUFFER:
return handler.getGrpcReceiveBuffer();
case PLUGIN_CONFIGURATION:
return handler.getPluginConfig();
case VM_CONFIGURATION:
return handler.getVmConfig();
case CALL_DATA:
return handler.getFuncCallData();
}
return null;
}
/**
* Set a buffer based on the buffer type.
*
* @param bufferType The type of buffer to set
* @param buffer The buffer to set
* @return WasmResult indicating success or failure
*/
private WasmResult setBuffer(int bufferType, byte[] buffer) {
// Set the appropriate buffer based on the buffer type
var knownType = BufferType.fromInt(bufferType);
if (knownType == null) {
return handler.setCustomBuffer(bufferType, buffer);
}
// TODO: check if the buffers that can be set may depend on the ABI version.
switch (knownType) {
case HTTP_REQUEST_BODY:
return handler.setHttpRequestBody(buffer);
case HTTP_RESPONSE_BODY:
return handler.setHttpResponseBody(buffer);
case DOWNSTREAM_DATA:
return handler.setDownStreamData(buffer);
case UPSTREAM_DATA:
return handler.setUpstreamData(buffer);
case HTTP_CALL_RESPONSE_BODY:
return handler.setHttpCallResponseBody(buffer);
case GRPC_RECEIVE_BUFFER:
return handler.setGrpcReceiveBuffer(buffer);
case CALL_DATA:
return handler.setFuncCallData(buffer);
}
return WasmResult.NOT_FOUND;
}
// //////////////////////////////////////////////////////////////////////
// HTTP fields
// //////////////////////////////////////////////////////////////////////
/**
* Retrieves serialized size of all key-value pairs from the map mapType
* <p>
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_get_header_map_size
*
* @param mapType The type of map to set
* @param returnSize Pointer to ruturn the size of the map data
* @return WasmResult status code
*/
@WasmExport
int proxyGetHeaderMapSize(int mapType, int returnSize) {
try {
// Get the header map based on the map type
ProxyMap header = getMap(mapType);
if (header == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// to clone the headers so that they don't change on while we process them in the loop
var cloneMap = new ArrayProxyMap(header);
int totalBytesLen = U32_LEN; // Start with space for the count
for (Map.Entry<String, String> entry : cloneMap.entries()) {
String key = entry.getKey();
String value = entry.getValue();
totalBytesLen += U32_LEN + U32_LEN; // keyLen + valueLen
totalBytesLen += key.length() + 1 + value.length() + 1; // key + \0 + value + \0
}
// Write the total size to the return size pointer
putUint32(returnSize, totalBytesLen);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Get header map pairs and format them for WebAssembly memory().
* <p>
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_get_header_map_pairs
*
* @param mapType The type of map to get
* @param returnDataPtr Pointer to where the data address should be stored
* @param returnDataSize Pointer to where the data size should be stored
* @return WasmResult status code
*/
@WasmExport
int proxyGetHeaderMapPairs(int mapType, int returnDataPtr, int returnDataSize) {
try {
// Get the header map based on the map type
ProxyMap header = getMap(mapType);
if (header == null) {
return WasmResult.NOT_FOUND.getValue();
}
var cloneMap = new ArrayList<Map.Entry<byte[], byte[]>>();
int totalBytesLen = U32_LEN; // Start with space for the count
totalBytesLen +=
header.streamBytes()
.mapToInt(
entry -> {
var key = entry.getKey();
var value = entry.getValue();
cloneMap.add(Map.entry(key, value));
return U32_LEN
+ U32_LEN // keyLen + valueLen
+ key.length
+ 1
+ value.length
+ 1; // key + \0 + value + \0
})
.sum();
// Allocate memory in the WebAssembly instance
int addr = malloc(totalBytesLen);
// Write the number of entries to the allocated memory
putUint32(addr, cloneMap.size());
// Calculate pointers for lengths and data
int lenPtr = addr + U32_LEN;
int dataPtr = lenPtr + ((U32_LEN + U32_LEN) * cloneMap.size());
// Write each key-value pair to memory
for (Map.Entry<byte[], byte[]> entry : cloneMap) {
var key = entry.getKey();
var value = entry.getValue();
// Write key length
putUint32(lenPtr, key.length);
lenPtr += U32_LEN;
// Write value length
putUint32(lenPtr, value.length);
lenPtr += U32_LEN;
// Write key bytes
putMemory(dataPtr, key);
dataPtr += key.length;
// Write null terminator for key
putByte(dataPtr, (byte) 0);
dataPtr++;
// Write value bytes
putMemory(dataPtr, value);
dataPtr += value.length;
// Write null terminator for value
putByte(dataPtr, (byte) 0);
dataPtr++;
}
// Write the address to the return pointer
putUint32(returnDataPtr, addr);
// Write the total size to the return size pointer
putUint32(returnDataSize, totalBytesLen);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Set header map pairs from WebAssembly memory().
* <p>
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_set_header_map_pairs
*
* @param mapType The type of map to set
* @param ptr Pointer to the map data in WebAssembly memory
* @param size Size of the map data
* @return WasmResult status code
*/
@WasmExport
int proxySetHeaderMapPairs(int mapType, int ptr, int size) {
try {
// Get the header map based on the map type
ProxyMap headerMap = getMap(mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Decode the map content and set each key-value pair
ProxyMap newMap = decodeMap(ptr, size);
for (Map.Entry<String, String> entry : newMap.entries()) {
headerMap.put(entry.getKey(), entry.getValue());
}
return WasmResult.OK.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Get a value from a header map by key.
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_get_header_map_value
*
* @param mapType The type of map to get from
* @param keyDataPtr Pointer to the key data in WebAssembly memory
* @param keySize Size of the key data
* @param valueDataPtr Pointer to where the value data should be stored
* @param valueSize Size of the value data buffer
* @return WasmResult status code
*/
@WasmExport
int proxyGetHeaderMapValue(
int mapType, int keyDataPtr, int keySize, int valueDataPtr, int valueSize) {
try {
// Get the header map based on the map type
ProxyMap headerMap = getMap(mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Get key from memory
String key = string(readMemory(keyDataPtr, keySize));
// Get value from map
String value = headerMap.get(key);
if (value == null) {
return WasmResult.NOT_FOUND.getValue();
}
// Copy value into WebAssembly memory
copyIntoInstance(bytes(value), valueDataPtr, valueSize);
return WasmResult.OK.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Add a value to a header map.
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_add_header_map_value
*
* @param mapType The type of map to modify
* @param keyDataPtr Pointer to the key data in WebAssembly memory
* @param keySize Size of the key data
* @param valueDataPtr Pointer to the value data in WebAssembly memory
* @param valueSize Size of the value data
* @return WasmResult status code
*/
@WasmExport
int proxyAddHeaderMapValue(
int mapType, int keyDataPtr, int keySize, int valueDataPtr, int valueSize) {
try {
// Get the header map based on the map type
ProxyMap headerMap = getMap(mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Get key from memory
String key = string(readMemory(keyDataPtr, keySize));
// Get value from memory
String value = string(readMemory(valueDataPtr, valueSize));
// Add value in map
headerMap.add(key, value);
return WasmResult.OK.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Replace a value in a header map.
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_replace_header_map_value
*
* @param mapType The type of map to modify
* @param keyDataPtr Pointer to the key data in WebAssembly memory
* @param keySize Size of the key data
* @param valueDataPtr Pointer to the value data in WebAssembly memory
* @param valueSize Size of the value data
* @return WasmResult status code
*/
@WasmExport
int proxyReplaceHeaderMapValue(
int mapType, int keyDataPtr, int keySize, int valueDataPtr, int valueSize) {
try {
// Get the header map based on the map type
ProxyMap headerMap = getMap(mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Get key from memory
String key = string(readMemory(keyDataPtr, keySize));
// Get value from memory
String value = string(readMemory(valueDataPtr, valueSize));
// Replace value in map
headerMap.put(key, value);
return WasmResult.OK.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Remove a value from a header map.
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_remove_header_map_value
*
* @param mapType The type of map to modify
* @param keyDataPtr Pointer to the key data in WebAssembly memory
* @param keySize Size of the key data
* @return WasmResult status code
*/
@WasmExport
int proxyRemoveHeaderMapValue(int mapType, int keyDataPtr, int keySize) {
try {
// Get the header map based on the map type
ProxyMap headerMap = getMap(mapType);
if (headerMap == null) {
return WasmResult.NOT_FOUND.getValue();
}
// Get key from memory
String key = string(readMemory(keyDataPtr, keySize));
if (key.isEmpty()) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Remove key from map
headerMap.remove(key);
return WasmResult.OK.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Get a header map based on the map type.
*
* @param mapType The type of map to get
* @return The header map
*/
private ProxyMap getMap(int mapType) {
var knownType = MapType.fromInt(mapType);