22#include <winpr/handle.h>
23#include <winpr/pipe.h>
28static BOOL test_roundtrip(HANDLE hRead, HANDLE hWrite)
30 char formatted[256] = WINPR_C_ARRAY_INIT;
31 if (!winpr_exportHandleToString(hWrite,
"--fdIn={}", formatted,
sizeof(formatted)))
33 printf(
"[roundtrip] winpr_exportHandleToString failed\n");
36 printf(
"[roundtrip] exported as '%s'\n", formatted);
38 HANDLE imported = winpr_importHandleFromString(formatted,
"--fdIn={}");
39 if (!imported || (imported == INVALID_HANDLE_VALUE))
41 printf(
"[roundtrip] winpr_importHandleFromString failed\n");
45 const char payload[] =
"PING";
47 if (!WriteFile(imported, payload,
sizeof(payload) - 1, &written,
nullptr) ||
48 (written !=
sizeof(payload) - 1))
50 printf(
"[roundtrip] WriteFile through the imported handle failed\n");
51 (void)CloseHandle(imported);
55 char readBuf[16] = WINPR_C_ARRAY_INIT;
57 if (!ReadFile(hRead, readBuf,
sizeof(payload) - 1, &nread,
nullptr) ||
58 (nread !=
sizeof(payload) - 1))
60 printf(
"[roundtrip] ReadFile on the original read end failed\n");
61 (void)CloseHandle(imported);
65 if (memcmp(readBuf, payload,
sizeof(payload) - 1) != 0)
67 printf(
"[roundtrip] data read back does not match what was written\n");
68 (void)CloseHandle(imported);
72 (void)CloseHandle(imported);
78static BOOL test_export_rejects_missing_placeholder(HANDLE hWrite)
80 char buf[64] = WINPR_C_ARRAY_INIT;
81 if (winpr_exportHandleToString(hWrite,
"no-placeholder-here", buf,
sizeof(buf)))
83 printf(
"[missing-placeholder] expected export to fail, but it succeeded\n");
91static BOOL test_export_rejects_short_buffer(HANDLE hWrite)
93 char tiny[2] = WINPR_C_ARRAY_INIT;
94 if (winpr_exportHandleToString(hWrite,
"--fdIn={}", tiny,
sizeof(tiny)))
96 printf(
"[short-buffer] expected export to fail, but it succeeded\n");
104static BOOL test_import_rejects_format_mismatch(
void)
106 HANDLE h = winpr_importHandleFromString(
"--other=5",
"--fdIn={}");
107 if (h != INVALID_HANDLE_VALUE)
109 printf(
"[format-mismatch] expected INVALID_HANDLE_VALUE, got a handle\n");
110 (void)CloseHandle(h);
117static BOOL test_import_rejects_garbage_value(
void)
119 HANDLE h = winpr_importHandleFromString(
"--fdIn=notanumber",
"--fdIn={}");
120 if (h != INVALID_HANDLE_VALUE)
122 printf(
"[garbage-value] expected INVALID_HANDLE_VALUE, got a handle\n");
123 (void)CloseHandle(h);
129int TestHandleExportImportString(
int argc,
char* argv[])
134 HANDLE hRead =
nullptr;
135 HANDLE hWrite =
nullptr;
136 if (!CreatePipe(&hRead, &hWrite,
nullptr, 0))
138 printf(
"CreatePipe failed\n");
143 if (!test_roundtrip(hRead, hWrite))
145 if (!test_export_rejects_missing_placeholder(hWrite))
147 if (!test_export_rejects_short_buffer(hWrite))
149 if (!test_import_rejects_format_mismatch())
151 if (!test_import_rejects_garbage_value())
154 (void)CloseHandle(hRead);
155 (void)CloseHandle(hWrite);