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
1653 lines (1427 loc) · 58.6 KB
/
ABI.java
File metadata and controls
1653 lines (1427 loc) · 58.6 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;
import static io.roastedroot.proxywasm.Helpers.replaceBytes;
import static io.roastedroot.proxywasm.Helpers.string;
import com.dylibso.chicory.experimental.hostmodule.annotations.HostModule;
import com.dylibso.chicory.experimental.hostmodule.annotations.WasmExport;
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 java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@HostModule("env")
public class ABI {
private Handler handler;
private Instance instance;
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public void setInstance(Instance instance) {
this.instance = instance;
}
public Instance.Exports exports() {
return instance.exports();
}
public Memory memory() {
return instance.memory();
}
// //////////////////////////////////////////////////////////////////////
// Common Helpers
// //////////////////////////////////////////////////////////////////////
// Size of a 32-bit integer in bytes
static final int U32_LEN = 4;
public boolean instanceExportsFunction(String name) {
try {
this.exports().function(name);
return true;
} catch (InvalidException e) {
return false;
}
}
/**
* 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
*/
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
*/
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
*/
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
*/
void putMemory(int address, byte[] data) throws WasmException {
try {
// TODO: do we need a better writeU32 method?
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
*/
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
*/
byte[] readMemory(int address, int len) throws WasmException {
try {
return memory().readBytes(address, len);
} catch (RuntimeException e) {
throw new WasmException(WasmResult.INVALID_MEMORY_ACCESS);
}
}
String readString(int address, int len) throws WasmException {
var data = readMemory(address, len);
return new String(data, StandardCharsets.UTF_8);
}
void copyIntoInstance(String value, int retPtr, int retSize) throws WasmException {
copyIntoInstance(value.getBytes(), retPtr, retSize);
}
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
*/
public void initialize() {
exports().function("_initialize").apply();
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#main
*/
public int main(int arg0, int arg1) {
long result = exports().function("main").apply(arg0, arg1)[0];
return (int) result;
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#_start
*/
public void start() {
exports().function("_start").apply();
}
// //////////////////////////////////////////////////////////////////////
// Memory management
// //////////////////////////////////////////////////////////////////////
String mallocFunctionName = "malloc";
public String getMallocFunctionName() {
return mallocFunctionName;
}
public void setMallocFunctionName(String mallocFunctionName) {
this.mallocFunctionName = mallocFunctionName;
}
/**
* 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 = exports().function(mallocFunctionName).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
*/
public void proxyOnContextCreate(int contextID, int parentContextID) {
exports().function("proxy_on_context_create").apply(contextID, parentContextID);
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_done
*/
public boolean proxyOnDone(int context_id) {
long result = exports().function("proxy_on_done").apply(context_id)[0];
return result != 0;
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_log
*/
public void proxyOnLog(int context_id) {
exports().function("proxy_on_log").apply(context_id);
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_delete
*/
public void proxyOnDelete(int context_id) {
exports().function("proxy_on_delete").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
*/
public boolean proxyOnVmStart(int arg0, int arg1) {
long result = exports().function("proxy_on_vm_start").apply(arg0, arg1)[0];
return result != 0;
}
/**
* implements: https://github.com/proxy-wasm/spec/tree/main/abi-versions/vNEXT#proxy_on_configure
*/
public boolean proxyOnConfigure(int arg0, int arg1) {
long result = exports().function("proxy_on_configure").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
public int proxyLog(int logLevel, int messageData, int messageSize) {
try {
var msg = memory().readBytes(messageData, messageSize);
handler.log(LogLevel.fromInt(logLevel), new 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
public 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
*/
public void proxyOnTick(int arg0) {
exports().function("proxy_on_tick").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
public int proxyGetBufferBytes(
int bufferType, int start, int length, 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 > start + length) {
return WasmResult.BAD_ARGUMENT.getValue();
}
ByteBuffer buffer = ByteBuffer.wrap(b);
if (start + length > buffer.capacity()) {
length = buffer.capacity() - start;
}
try {
buffer.position(start);
buffer.limit(start + length);
} catch (IllegalArgumentException e) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Allocate memory in the WebAssembly instance
int addr = malloc(length);
putMemory(addr, buffer);
// Write the address to the return pointer
putUint32(returnBufferData, addr);
// Write the length to the return size pointer
putUint32(returnBufferSize, length);
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
public 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
public 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
*
* 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
public int proxyGetHeaderMapSize(int mapType, int returnSize) {
try {
// Get the header map based on the map type
Map<String, String> 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
final Map<String, String> cloneMap = new HashMap<>();
int totalBytesLen = U32_LEN; // Start with space for the count
for (Map.Entry<String, String> entry : header.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
cloneMap.put(key, value);
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().
*
* 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
public int proxyGetHeaderMapPairs(int mapType, int returnDataPtr, int returnDataSize) {
try {
// Get the header map based on the map type
Map<String, String> header = getMap(mapType);
if (header == null) {
return WasmResult.NOT_FOUND.getValue();
}
// to clone the headers so that they don't change on while we process them in the loop
final Map<String, String> cloneMap = new HashMap<>();
int totalBytesLen = U32_LEN; // Start with space for the count
for (Map.Entry<String, String> entry : header.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
cloneMap.put(key, value);
totalBytesLen += U32_LEN + U32_LEN; // keyLen + valueLen
totalBytesLen += key.length() + 1 + value.length() + 1; // key + \0 + value + \0
}
// 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<String, String> entry : cloneMap.entrySet()) {
String key = entry.getKey();
String 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.getBytes());
dataPtr += key.length();
// Write null terminator for key
putByte(dataPtr, (byte) 0);
dataPtr++;
// Write value bytes
putMemory(dataPtr, value.getBytes());
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().
*
* 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
public int proxySetHeaderMapPairs(int mapType, int ptr, int size) {
try {
// Get the header map based on the map type
Map<String, String> headerMap = getMap(mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Decode the map content and set each key-value pair
Map<String, String> newMap = decodeMap(ptr, size);
for (Map.Entry<String, String> entry : newMap.entrySet()) {
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
public int proxyGetHeaderMapValue(
int mapType, int keyDataPtr, int keySize, int valueDataPtr, int valueSize) {
try {
// Get the header map based on the map type
Map<String, String> headerMap = getMap(mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Get key from memory
String key = readString(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(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
public int proxyAddHeaderMapValue(
int mapType, int keyDataPtr, int keySize, int valueDataPtr, int valueSize) {
return proxyReplaceHeaderMapValue(mapType, keyDataPtr, keySize, valueDataPtr, valueSize);
}
/**
* 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
public int proxyReplaceHeaderMapValue(
int mapType, int keyDataPtr, int keySize, int valueDataPtr, int valueSize) {
try {
// Get the header map based on the map type
Map<String, String> headerMap = getMap(mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Get key from memory
String key = readString(keyDataPtr, keySize);
// Get value from memory
String value = readString(valueDataPtr, valueSize);
// Replace value in map
var copy = new HashMap<>(headerMap);
copy.put(key, value);
setMap(mapType, copy);
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
public int proxyRemoveHeaderMapValue(int mapType, int keyDataPtr, int keySize) {
try {
// Get the header map based on the map type
Map<String, String> headerMap = getMap(mapType);
if (headerMap == null) {
return WasmResult.NOT_FOUND.getValue();
}
// Get key from memory
String key = readString(keyDataPtr, keySize);
if (key.isEmpty()) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Remove key from map
var copy = new HashMap<>(headerMap);
copy.remove(key);
setMap(mapType, copy);
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 Map<String, String> getMap(int mapType) {
var knownType = MapType.fromInt(mapType);
if (knownType == null) {
return handler.getCustomHeaders(mapType);
}
switch (knownType) {
case HTTP_REQUEST_HEADERS:
return handler.getHttpRequestHeaders();
case HTTP_REQUEST_TRAILERS:
return handler.getHttpRequestTrailers();
case HTTP_RESPONSE_HEADERS:
return handler.getHttpResponseHeaders();
case HTTP_RESPONSE_TRAILERS:
return handler.getHttpResponseTrailers();
case HTTP_CALL_RESPONSE_HEADERS:
return handler.getHttpCallResponseHeaders();
case HTTP_CALL_RESPONSE_TRAILERS:
return handler.getHttpCallResponseTrailers();
case GRPC_RECEIVE_INITIAL_METADATA:
return handler.getGrpcReceiveInitialMetaData();
case GRPC_RECEIVE_TRAILING_METADATA:
return handler.getGrpcReceiveTrailerMetaData();
}
return null;
}
/**
* Set a header map based on the map type.
*
* @param mapType The type of map to set
* @param map The header map to set
* @return WasmResult indicating success or failure
*/
private WasmResult setMap(int mapType, Map<String, String> map) {
var knownType = MapType.fromInt(mapType);
if (knownType == null) {
return handler.setCustomHeaders(mapType, map);
}
switch (knownType) {
case HTTP_REQUEST_HEADERS:
return handler.setHttpRequestHeaders(map);
case HTTP_REQUEST_TRAILERS:
return handler.setHttpRequestTrailers(map);
case HTTP_RESPONSE_HEADERS:
return handler.setHttpResponseHeaders(map);
case HTTP_RESPONSE_TRAILERS:
return handler.setHttpResponseTrailers(map);
case HTTP_CALL_RESPONSE_HEADERS:
return handler.setHttpCallResponseHeaders(map);
case HTTP_CALL_RESPONSE_TRAILERS:
return handler.setHttpCallResponseTrailers(map);
case GRPC_RECEIVE_INITIAL_METADATA:
return handler.setGrpcReceiveInitialMetaData(map);
case GRPC_RECEIVE_TRAILING_METADATA:
return handler.setGrpcReceiveTrailerMetaData(map);
}
return WasmResult.NOT_FOUND;
}
/**
* Decodes a byte array containing map data into a Map of String key-value pairs.
* <p>
* The format is:
* - First 4 bytes: number of entries (headerSize) in little endian
* - For each entry:
* - 4 bytes: key size in little endian
* - 4 bytes: value size in little endian
* - Then the actual data:
* - key bytes (null terminated)
* - value bytes (null terminated)
*
* @param addr The memory address to read from
* @param mem_size The size of memory to read
* @return The decoded map containing string keys and values
* @throws WasmException if there is an error accessing memory
*/
private HashMap<String, String> decodeMap(int addr, int mem_size) throws WasmException {
if (mem_size < U32_LEN) {
return new HashMap<>();
}
// Read header size (number of entries)
var mapSize = getUint32(addr);
// Calculate start of data section
// mapSize + (key1_size + value1_size) * mapSize
long dataOffset = U32_LEN + (U32_LEN + U32_LEN) * mapSize;
if (dataOffset >= mem_size) {
return new HashMap<>();
}
// Create result map with initial capacity
var result = new HashMap<String, String>((int) mapSize);
// Process each entry
for (int i = 0; i < mapSize; i++) {
// Calculate index for length values
int keySizeOffset = U32_LEN + (U32_LEN + U32_LEN) * i;
int valueSizeOffset = keySizeOffset + U32_LEN;
// Read key and value sizes
long keySize = getUint32(addr + keySizeOffset);
long valueSize = getUint32(addr + valueSizeOffset);
// Check if we have enough data for the key/value
if (dataOffset >= mem_size || dataOffset + keySize + valueSize + 2 > mem_size) {
break;
}
// Extract key
String key = readString((int) (addr + dataOffset), (int) keySize);
dataOffset += keySize + 1; // Skip null terminator
// Extract value
String value = readString((int) (addr + dataOffset), (int) valueSize);
dataOffset += valueSize + 1;