-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtomedo-crawl.cpp
More file actions
2281 lines (2110 loc) · 90.5 KB
/
Copy pathtomedo-crawl.cpp
File metadata and controls
2281 lines (2110 loc) · 90.5 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
// ============================================================
// tomedo-crawl — RAG sidecar for Prodigy
// ============================================================
//
// TOMEDO API DISCOVERY (probed live 2026-04-11, server 192.168.10.9)
// ============================================================
//
// LIVE PROBE EVIDENCE (redacted PII — field shapes confirmed):
//
// $ curl -sk --cert client.pem --key client.pem \
// https://192.168.10.9:8443/tomedo_live/serverstatus
// → {"status":"OK","softwareVersion":"2026-03-30 15:45","revision":121155207,...}
//
// $ curl -sk ... https://192.168.10.9:8443/tomedo_live/patient?flach=true \
// | python3 -c "import json,sys; d=json.load(sys.stdin); print(len(d))"
// → 15421
//
// $ curl -sk ... https://192.168.10.9:8443/tomedo_live/patient?flach=true \
// | python3 -c "import json,sys; print(json.dumps(json.load(sys.stdin)[0],indent=2))"
// → {
// "ident": 1,
// "nachname": "Arnold", ← confirmed field name
// "vorname": "Herbert", ← confirmed field name
// "titel": null,
// "geburtsDatum": -530802000000, ← epoch ms (negative = before 1970)
// "ort": "Pfronstetten",
// "zuletztAufgerufen": 1775631991660,
// "patientenDetails": {"ident": 1}, ← flat list has NO phone data
// "nachname_phonetic": "_ernolc_",
// "vorname_phonetic": "_erferc_",
// "revision": null,
// "geburtsname": null
// }
//
// $ curl -sk ... https://192.168.10.9:8443/tomedo_live/patient/776
// → {
// "nachname": "Kunsch",
// "vorname": "Lothar",
// "patientenDetails": {
// "kontaktdaten": {
// "telefon": "07383-942735", ← confirmed field name
// "telefon2": null,
// "handyNummer": null, ← confirmed field name
// "telefon3": null,
// "weitereTelefonummern": [],
// "fax": null,
// ...
// },
// ...
// }
// }
//
// PHONE SEARCH — CONFIRMED DOES NOT WORK BY PHONE DIGITS:
// $ curl -sk ... ".../patient/searchByAttributes?query=942735&telefonNummern=true"
// → {} ← empty dict, not an array — name-only search confirmed
//
// $ curl -sk ... ".../patient/1403/patientenDetailsRelationen/medikamentenPlan"
// → 12 entries, e.g.:
// { "nameBeiVerordnung": "AMLODIPIN/Valsartan/HCT Heumann 10/160/12,5mg FTA 98 ST",
// "dosierungFrueh": null, "dosierungMittag": null, "dosierungAbend": null,
// "wirkstaerkeBeiVerordnung": "10 mg / 160 mg / 12,5 mg",
// "darreichungBeiVerordnung": "FITBL", ... }
//
// $ curl -sk ... ".../patient/3892/patientenDetailsRelationen?limitScheine=true&limitMedikamentenPlan=50"
// → diagnosen: 101 entries, e.g.:
// { "freitext": "Sinusitis", ← human-readable ICD description confirmed
// "typ": null, ← some entries have null typ, use freitext as primary
// "icdKatalogEintrag": {"ident": 12345}, ... }
// other entries: {"freitext": "lokal allergische Reaktion auf Wespenstich", "typ": "G"}
//
// ============================================================
//
// BASE URL: https://192.168.10.9:8443/tomedo_live/
// AUTH: Mutual TLS — macOS Keychain identity "tomedoClientCert"
// (self-signed RSA-4096; the Tomedo macOS client installs
// this certificate pair automatically on first server
// connection). Export once:
// security export -k ~/Library/Keychains/login.keychain-db \
// -t identities -f pkcs12 -P "" \
// -o /tmp/tomedo_client.p12
// openssl pkcs12 -legacy -in /tmp/tomedo_client.p12 -nodes \
// -passin pass:"" -out /etc/tomedo-crawl/client.pem
// PEM contains both cert and private key (no password).
// Use OpenSSL: SSL_CTX_use_certificate_file +
// SSL_CTX_use_PrivateKey_file.
// NO HTTP Authorization header required.
//
// PATIENT LIST (flat, no phone data):
// GET /patient?flach=true
// → JSON array, 15 421 records (confirmed 2026-04-11)
// Fields: ident, nachname, vorname, titel, geburtsDatum (epoch ms),
// ort, zuletztAufgerufen — phone NOT included.
//
// PATIENT FULL RECORD (includes phone fields):
// GET /patient/{id}
// Phone fields inside patientenDetails.kontaktdaten (confirmed names):
// telefon — main phone (may contain \n-separated entries)
// telefon2 — secondary phone
// handyNummer — mobile
// telefon3 — tertiary phone
// weitereTelefonummern[] — additional numbers
//
// PHONE-BASED CALLER LOOKUP:
// No server-side phone-search endpoint exists (confirmed).
// searchByAttributes?query={digits}&telefonNummern=true → {} (empty).
// → Build local phone_index SQLite table during background crawl.
// → Lookup at call time: query local SQLite by phone digits (LIKE match).
//
// PATIENT DETAILS WITH CLINICAL RELATIONS:
// GET /patient/{id}/patientenDetailsRelationen
// ?limitScheine=true&limitKartei=50&limitFormulare=10
// &limitVerordnungen=50&limitMedikamentenPlan=50
// &limitZeiterfassungen=true&limitBehandlungsfaelle=true
// → JSON object; key arrays:
// diagnosen[] — { freitext: "human-readable text", typ: "G"|"V"|null,
// icdKatalogEintrag.ident }
// (other arrays: karteiEintraege, behandlungsfaelle, ...)
//
// MEDICATIONS (separate endpoint — not in patientenDetailsRelationen body):
// GET /patient/{id}/patientenDetailsRelationen/medikamentenPlan
// → JSON array, e.g. 12 entries:
// { nameBeiVerordnung, wirkstaerkeBeiVerordnung,
// darreichungBeiVerordnung,
// dosierungFrueh, dosierungMittag, dosierungAbend, dosierungNacht }
//
// APPOINTMENTS:
// GET /patient/{id}/termine?flach=true
// → JSON array: { ident, beginn: epoch_ms, ende: epoch_ms, info }
//
// VISITS (Besuch):
// GET /besuch/{patient_id}/besucheForPatient
//
// SERVER HEALTH:
// GET /serverstatus → { status: "OK", softwareVersion, revision }
//
// NO BRIEFKOMMANDO API:
// Briefkommando ($[d:...]$, $[&p.name]$, etc.) is client-side only.
// Context documents are composed directly from the JSON fields above.
//
// NO STATISTICS SQL API:
// GET /statistik/ → "RESTEASY003210: Could not find resource"
// Custom SQL queries are not supported via REST.
//
// RAG CONTEXT DOCUMENT FORMAT (produced per patient):
// Patient: {vorname} {nachname} (ID {ident}), geb. {geburtsDatum}
// Diagnosen: {diagnosen[].freitext} [max 20 with non-null freitext]
// Medikamente: {nameBeiVerordnung} {dosierungFrueh}-{mittag}-{abend}
// Nächster Termin: {beginn_formatted} ({info})
// Telefon: {telefon}
//
// PAGINATION:
// Flat patient list returns all ~15k records in one HTTP response.
// No server-side pagination parameter found.
// Background crawl processes patients in batches of 100 with 10ms
// sleep between batches to avoid hammering the server.
//
// ============================================================
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <sstream>
#include <string>
#include <thread>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <memory>
#include <vector>
#include <algorithm>
#include <ctime>
#include <signal.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "mongoose.h"
#include "sqlite3.h"
#include "db_key.h"
#include "tls_cert.h"
#include "interconnect.h"
namespace {
std::atomic<bool> s_quit{false};
void sig_handler(int) { s_quit.store(true); }
// ============================================================
// Config — stored in SQLite config table (no INI files)
// ============================================================
//
// All configuration is persisted in the encrypted SQLite database (same file
// as the vector store) in a "config" table (key TEXT PRIMARY KEY, value TEXT).
// The frontend writes to this table via /api/rag/config; on every service
// start the binary reads the table and materialises the struct below.
//
// Defaults are safe for a fresh install: the service starts and exposes /health
// immediately, and the first crawl is deferred until Tomedo credentials are set.
struct TomedoConfig {
std::string tomedo_host = "192.168.10.9";
int tomedo_port = 8443;
std::string tomedo_db = "tomedo_live";
std::string tomedo_cert_pem = "/etc/tomedo-crawl/client.pem";
int crawl_interval_sec = 3600;
std::string ollama_url = "http://127.0.0.1:11434";
std::string ollama_model = "bge-small";
std::string api_host = "127.0.0.1";
int api_port = 13181;
int log_port = 22022;
std::string frontend_host = "127.0.0.1";
int frontend_port = 8081;
std::string db_path = "tomedo-crawl.db";
size_t hnsw_max_elements = 500000;
};
static int parse_int(const std::string& val, int fallback) {
try { return std::stoi(val); }
catch (...) { return fallback; }
}
static int parse_port(const std::string& val, int fallback) {
int v = parse_int(val, fallback);
return (v > 0 && v <= 65535) ? v : fallback;
}
static bool config_db_ensure(const std::string& db_path) {
sqlite3* db = nullptr;
if (prodigy_db::db_open_encrypted(db_path.c_str(), &db) != SQLITE_OK) {
std::fprintf(stderr, "tomedo-crawl: cannot open config db '%s': %s\n",
db_path.c_str(), db ? sqlite3_errmsg(db) : "unknown");
if (db) sqlite3_close(db);
return false;
}
sqlite3_exec(db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, nullptr);
sqlite3_exec(db, "PRAGMA busy_timeout=5000;", nullptr, nullptr, nullptr);
const char* sql =
"CREATE TABLE IF NOT EXISTS config ("
" key TEXT PRIMARY KEY NOT NULL,"
" value TEXT NOT NULL"
");";
char* errmsg = nullptr;
int rc = sqlite3_exec(db, sql, nullptr, nullptr, &errmsg);
if (rc != SQLITE_OK) {
std::fprintf(stderr, "tomedo-crawl: config table creation failed: %s\n",
errmsg ? errmsg : "unknown");
sqlite3_free(errmsg);
sqlite3_close(db);
return false;
}
sqlite3_close(db);
return true;
}
static std::string config_db_get(sqlite3* db, const std::string& key,
const std::string& fallback) {
if (!db) return fallback;
sqlite3_stmt* stmt = nullptr;
int rc = sqlite3_prepare_v2(db,
"SELECT value FROM config WHERE key=?", -1, &stmt, nullptr);
if (rc != SQLITE_OK) return fallback;
sqlite3_bind_text(stmt, 1, key.c_str(), -1, SQLITE_TRANSIENT);
std::string result = fallback;
if (sqlite3_step(stmt) == SQLITE_ROW) {
const char* v = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
if (v && v[0] != '\0') result = v;
}
sqlite3_finalize(stmt);
return result;
}
static TomedoConfig load_config_from_db(const std::string& db_path) {
TomedoConfig cfg;
cfg.db_path = db_path;
if (!config_db_ensure(db_path)) {
std::fprintf(stderr, "tomedo-crawl: config db init failed, using defaults\n");
return cfg;
}
sqlite3* db = nullptr;
if (prodigy_db::db_open_encrypted(db_path.c_str(), &db) != SQLITE_OK) {
std::fprintf(stderr, "tomedo-crawl: cannot open config db for reading, using defaults\n");
if (db) sqlite3_close(db);
return cfg;
}
sqlite3_exec(db, "PRAGMA busy_timeout=5000;", nullptr, nullptr, nullptr);
cfg.tomedo_host = config_db_get(db, "tomedo_host", cfg.tomedo_host);
cfg.tomedo_port = parse_port(config_db_get(db, "tomedo_port",
std::to_string(cfg.tomedo_port)), cfg.tomedo_port);
cfg.tomedo_db = config_db_get(db, "tomedo_db", cfg.tomedo_db);
cfg.tomedo_cert_pem = config_db_get(db, "tomedo_cert_pem", cfg.tomedo_cert_pem);
cfg.crawl_interval_sec = parse_int(config_db_get(db, "crawl_interval_sec",
std::to_string(cfg.crawl_interval_sec)), cfg.crawl_interval_sec);
if (cfg.crawl_interval_sec <= 0) cfg.crawl_interval_sec = 3600;
cfg.ollama_url = config_db_get(db, "ollama_url", cfg.ollama_url);
cfg.ollama_model = config_db_get(db, "ollama_model", cfg.ollama_model);
cfg.api_host = config_db_get(db, "api_host", cfg.api_host);
cfg.api_port = parse_port(config_db_get(db, "api_port",
std::to_string(cfg.api_port)), cfg.api_port);
cfg.log_port = parse_port(config_db_get(db, "log_port",
std::to_string(cfg.log_port)), cfg.log_port);
cfg.frontend_host = config_db_get(db, "frontend_host", cfg.frontend_host);
cfg.frontend_port = parse_port(config_db_get(db, "frontend_port",
std::to_string(cfg.frontend_port)), cfg.frontend_port);
std::string hnsw_str = config_db_get(db, "hnsw_max_elements",
std::to_string(cfg.hnsw_max_elements));
try {
size_t v = std::stoul(hnsw_str);
if (v > 0) cfg.hnsw_max_elements = v;
} catch (...) {}
sqlite3_close(db);
return cfg;
}
// ============================================================
// LogForwarder (re-use from interconnect.h via ServiceType)
// ============================================================
whispertalk::LogForwarder g_log;
#define LOG_INFO(fmt, ...) g_log.forward(whispertalk::LogLevel::INFO, 0, fmt, ##__VA_ARGS__)
#define LOG_WARN(fmt, ...) g_log.forward(whispertalk::LogLevel::WARN, 0, fmt, ##__VA_ARGS__)
#define LOG_ERROR(fmt, ...) g_log.forward(whispertalk::LogLevel::ERROR, 0, fmt, ##__VA_ARGS__)
#define LOG_DEBUG(fmt, ...) g_log.forward(whispertalk::LogLevel::DEBUG, 0, fmt, ##__VA_ARGS__)
// ============================================================
// Global service state
// ============================================================
//
// All atomics are written by background threads and read by the Mongoose
// event-loop thread (or vice-versa). Plain relaxed loads are sufficient for
// the status/health data; crawl_requested_ uses sequential consistency so the
// crawl thread observes the write promptly.
std::atomic<long> g_last_crawl_time{0};
std::atomic<bool> g_crawl_requested{false};
static int tcp_connect(const std::string& host, int port, int timeout_ms);
constexpr int MG_POLL_TIMEOUT_MS = 100;
constexpr int CHARS_PER_TOKEN_APPROX = 4;
constexpr int MIN_PHONE_DIGITS = 4;
constexpr int PHONE_SUFFIX_MATCH_LEN = 6;
constexpr int MAX_DIAGNOSEN = 20;
constexpr int MAX_MEDICATIONS = 20;
constexpr int CRAWL_PROGRESS_INTERVAL = 50;
constexpr int CRAWL_BATCH_SLEEP_MS = 10;
constexpr int EXPIRY_CHECK_INTERVAL_S = 300;
constexpr int RESOLVE_QUEUE_MAX_DEPTH = 200;
constexpr int TOMEDO_API_TIMEOUT_MS = 15000;
constexpr int TOMEDO_LIST_TIMEOUT_MS = 60000;
// ============================================================
// CallerStore — thread-safe in-memory caller identity tracking
// ============================================================
//
// Lifecycle per call:
// 1. sip-client-main detects an incoming call and POSTs /caller with the
// call_id and raw phone number string from the SIP From: header.
// 2. CallerStore::register_caller() creates a PENDING entry.
// 3. ResolveQueue dispatches a background lookup against the local
// phone_index SQLite table (populated by the crawl thread).
// 4. CallerStore::update() sets status to FOUND/NOT_FOUND/ERROR and fills
// name/patient_id when a match is found.
// 5. llama-service GETs /caller/{call_id} to retrieve the identity before
// building the dynamic system prompt.
// 6. sip-client-main DELETEs /caller/{call_id} on call tear-down.
//
// TTL: entries expire after 1 hour (TTL_SECONDS) regardless of DELETE, as a
// safety net for calls that did not send a DELETE (e.g. crash). expire_old()
// is called by the expiry_thread every EXPIRY_CHECK_INTERVAL_S seconds.
enum class LookupStatus { PENDING, FOUND, NOT_FOUND, ERROR };
static const char* lookup_status_str(LookupStatus s) {
switch (s) {
case LookupStatus::PENDING: return "pending";
case LookupStatus::FOUND: return "found";
case LookupStatus::NOT_FOUND: return "not_found";
case LookupStatus::ERROR: return "error";
}
return "error";
}
struct CallerPatient {
int patient_id = -1;
std::string name;
std::string vorname;
};
struct CallerRecord {
int call_id = 0;
std::string phone_number;
LookupStatus status = LookupStatus::PENDING;
int patient_id = -1;
std::string name;
std::string vorname;
std::vector<CallerPatient> all_patients;
std::chrono::steady_clock::time_point created_at;
};
class CallerStore {
mutable std::mutex mutex_;
std::unordered_map<int, CallerRecord> map_;
static constexpr int TTL_SECONDS = 3600;
public:
void register_caller(int call_id, const std::string& phone) {
CallerRecord rec;
rec.call_id = call_id;
rec.phone_number = phone;
rec.status = LookupStatus::PENDING;
rec.created_at = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lk(mutex_);
map_[call_id] = std::move(rec);
}
void update(int call_id, LookupStatus st, int patient_id,
const std::string& name, const std::string& vorname,
std::vector<CallerPatient> all = {}) {
std::lock_guard<std::mutex> lk(mutex_);
auto it = map_.find(call_id);
if (it == map_.end()) return;
it->second.status = st;
it->second.patient_id = patient_id;
it->second.name = name;
it->second.vorname = vorname;
it->second.all_patients = std::move(all);
}
bool get(int call_id, CallerRecord& out) const {
std::lock_guard<std::mutex> lk(mutex_);
auto it = map_.find(call_id);
if (it == map_.end()) return false;
out = it->second;
return true;
}
bool remove(int call_id) {
std::lock_guard<std::mutex> lk(mutex_);
return map_.erase(call_id) > 0;
}
void expire_old() {
auto now = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lk(mutex_);
for (auto it = map_.begin(); it != map_.end(); ) {
auto age = std::chrono::duration_cast<std::chrono::seconds>(
now - it->second.created_at).count();
if (age > TTL_SECONDS)
it = map_.erase(it);
else
++it;
}
}
};
CallerStore g_caller_store;
// ============================================================
// JSON helpers (hand-rolled, no external library)
// ============================================================
static std::string json_escape(const std::string& s) {
std::string out;
out.reserve(s.size() + 4);
for (char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if ((unsigned char)c < 0x20) {
char buf[7];
std::snprintf(buf, sizeof(buf), "\\u%04x", (unsigned char)c);
out += buf;
} else {
out += c;
}
break;
}
}
return out;
}
static bool is_json_key_position(const std::string& body, size_t pos) {
if (pos == 0) return true;
for (size_t i = pos; i > 0; --i) {
char ch = body[i - 1];
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') continue;
return ch == '{' || ch == ',';
}
return true;
}
static long long json_get_int64(const std::string& body, const std::string& key, long long fallback) {
std::string needle = "\"" + key + "\"";
size_t search_from = 0;
while (true) {
auto pos = body.find(needle, search_from);
if (pos == std::string::npos) return fallback;
if (!is_json_key_position(body, pos)) {
search_from = pos + 1;
continue;
}
pos += needle.size();
while (pos < body.size() && (body[pos] == ' ' || body[pos] == '\t')) ++pos;
if (pos >= body.size() || body[pos] != ':') {
search_from = pos;
continue;
}
++pos;
while (pos < body.size() && (body[pos] == ' ' || body[pos] == '\t')) ++pos;
if (pos >= body.size()) return fallback;
if (body[pos] != '-' && (body[pos] < '0' || body[pos] > '9')) return fallback;
return std::atoll(body.c_str() + pos);
}
}
static std::string json_get_string(const std::string& body, const std::string& key);
static std::string json_get_nested_string(const std::string& body,
const std::string& outer_key,
const std::string& inner_key) {
std::string needle = "\"" + outer_key + "\"";
size_t search_from = 0;
size_t pos;
while (true) {
pos = body.find(needle, search_from);
if (pos == std::string::npos) return {};
if (is_json_key_position(body, pos)) break;
search_from = pos + 1;
}
pos += needle.size();
while (pos < body.size() && body[pos] != '{') ++pos;
if (pos >= body.size()) return {};
int depth = 1;
size_t obj_start = pos;
++pos;
while (pos < body.size() && depth > 0) {
if (body[pos] == '{') ++depth;
else if (body[pos] == '}') --depth;
else if (body[pos] == '"') {
++pos;
while (pos < body.size() && body[pos] != '"') {
if (body[pos] == '\\') ++pos;
++pos;
}
}
++pos;
}
std::string sub = body.substr(obj_start, pos - obj_start);
return json_get_string(sub, inner_key);
}
static std::string json_get_deep_string(const std::string& body,
const std::string& k1,
const std::string& k2,
const std::string& k3) {
std::string needle = "\"" + k1 + "\"";
size_t search_from = 0;
size_t pos;
while (true) {
pos = body.find(needle, search_from);
if (pos == std::string::npos) return {};
if (is_json_key_position(body, pos)) break;
search_from = pos + 1;
}
pos += needle.size();
while (pos < body.size() && body[pos] != '{') ++pos;
if (pos >= body.size()) return {};
int depth = 1;
size_t obj_start = pos;
++pos;
while (pos < body.size() && depth > 0) {
if (body[pos] == '{') ++depth;
else if (body[pos] == '}') --depth;
else if (body[pos] == '"') {
++pos;
while (pos < body.size() && body[pos] != '"') {
if (body[pos] == '\\') ++pos;
++pos;
}
}
++pos;
}
std::string outer_sub = body.substr(obj_start, pos - obj_start);
return json_get_nested_string(outer_sub, k2, k3);
}
static std::string json_get_string(const std::string& body, const std::string& key) {
std::string needle = "\"" + key + "\"";
size_t search_from = 0;
while (true) {
auto pos = body.find(needle, search_from);
if (pos == std::string::npos) return {};
if (!is_json_key_position(body, pos)) {
search_from = pos + 1;
continue;
}
pos += needle.size();
while (pos < body.size() && (body[pos] == ' ' || body[pos] == '\t')) ++pos;
if (pos >= body.size() || body[pos] != ':') {
search_from = pos;
continue;
}
++pos;
while (pos < body.size() && (body[pos] == ' ' || body[pos] == '\t')) ++pos;
if (pos >= body.size() || body[pos] != '"') return {};
++pos;
std::string result;
while (pos < body.size() && body[pos] != '"') {
if (body[pos] == '\\' && pos + 1 < body.size()) {
++pos;
switch (body[pos]) {
case '"': result += '"'; break;
case '\\': result += '\\'; break;
case '/': result += '/'; break;
case 'n': result += '\n'; break;
case 'r': result += '\r'; break;
case 't': result += '\t'; break;
case 'b': result += '\b'; break;
case 'f': result += '\f'; break;
case 'u': {
if (pos + 4 < body.size()) {
unsigned cp = 0;
bool ok = true;
for (int d = 1; d <= 4 && ok; ++d) {
char h = body[pos + d];
cp <<= 4;
if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0');
else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10);
else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10);
else ok = false;
}
if (ok) {
pos += 4;
if (cp >= 0xD800 && cp <= 0xDBFF &&
pos + 6 < body.size() && body[pos + 1] == '\\' && body[pos + 2] == 'u') {
unsigned lo = 0;
bool ok2 = true;
for (int d = 3; d <= 6 && ok2; ++d) {
char h = body[pos + d];
lo <<= 4;
if (h >= '0' && h <= '9') lo |= (unsigned)(h - '0');
else if (h >= 'a' && h <= 'f') lo |= (unsigned)(h - 'a' + 10);
else if (h >= 'A' && h <= 'F') lo |= (unsigned)(h - 'A' + 10);
else ok2 = false;
}
if (ok2 && lo >= 0xDC00 && lo <= 0xDFFF) {
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
pos += 6;
}
}
if (cp < 0x80) {
result += (char)cp;
} else if (cp < 0x800) {
result += (char)(0xC0 | (cp >> 6));
result += (char)(0x80 | (cp & 0x3F));
} else if (cp < 0x10000) {
result += (char)(0xE0 | (cp >> 12));
result += (char)(0x80 | ((cp >> 6) & 0x3F));
result += (char)(0x80 | (cp & 0x3F));
} else {
result += (char)(0xF0 | (cp >> 18));
result += (char)(0x80 | ((cp >> 12) & 0x3F));
result += (char)(0x80 | ((cp >> 6) & 0x3F));
result += (char)(0x80 | (cp & 0x3F));
}
} else {
result += 'u';
}
} else {
result += 'u';
}
break;
}
default: result += body[pos]; break;
}
} else {
result += body[pos];
}
++pos;
}
return result;
}
}
static int json_get_int(const std::string& body, const std::string& key, int fallback) {
std::string needle = "\"" + key + "\"";
size_t search_from = 0;
while (true) {
auto pos = body.find(needle, search_from);
if (pos == std::string::npos) return fallback;
if (!is_json_key_position(body, pos)) {
search_from = pos + 1;
continue;
}
pos += needle.size();
while (pos < body.size() && (body[pos] == ' ' || body[pos] == '\t')) ++pos;
if (pos >= body.size() || body[pos] != ':') {
search_from = pos;
continue;
}
++pos;
while (pos < body.size() && (body[pos] == ' ' || body[pos] == '\t')) ++pos;
if (pos >= body.size()) return fallback;
if (body[pos] != '-' && (body[pos] < '0' || body[pos] > '9')) return fallback;
return std::atoi(body.c_str() + pos);
}
}
// ============================================================
// HTTPS client (OpenSSL, statically linked — no runtime dependency)
// ============================================================
struct HttpResponse {
int status = 0;
std::string body;
};
static int tcp_connect(const std::string& host, int port, int timeout_ms) {
struct sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(static_cast<uint16_t>(port));
if (inet_pton(AF_INET, host.c_str(), &addr.sin_addr) != 1) {
struct addrinfo hints{}, *res = nullptr;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host.c_str(), nullptr, &hints, &res) != 0 || !res)
return -1;
std::memcpy(&addr.sin_addr,
&reinterpret_cast<struct sockaddr_in*>(res->ai_addr)->sin_addr,
sizeof(addr.sin_addr));
freeaddrinfo(res);
}
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) return -1;
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
int rc = connect(fd, (struct sockaddr*)&addr, sizeof(addr));
if (rc < 0 && errno != EINPROGRESS) { close(fd); return -1; }
if (rc < 0) {
struct pollfd pfd{fd, POLLOUT, 0};
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
int pr;
do {
int rem = static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now()).count());
if (rem <= 0) { pr = 0; break; }
pr = poll(&pfd, 1, rem);
} while (pr < 0 && errno == EINTR);
if (pr <= 0) { close(fd); return -1; }
int err = 0; socklen_t len = sizeof(err);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len);
if (err != 0) { close(fd); return -1; }
}
fcntl(fd, F_SETFL, flags);
return fd;
}
static std::string ssl_read_all(SSL* ssl, int timeout_ms) {
std::string result;
char buf[8192];
int fd = SSL_get_fd(ssl);
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
while (true) {
auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now()).count();
if (remaining <= 0) break;
struct pollfd pfd{fd, POLLIN, 0};
int pr = poll(&pfd, 1, static_cast<int>(std::min(remaining, (long long)1000)));
if (pr < 0) {
if (errno == EINTR) continue;
break;
}
if (pr == 0) continue; // sub-poll timeout, check deadline and retry
int n = SSL_read(ssl, buf, sizeof(buf));
if (n <= 0) {
int err = SSL_get_error(ssl, n);
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) continue;
break;
}
result.append(buf, static_cast<size_t>(n));
}
return result;
}
static std::string decode_chunked(const std::string& body) {
std::string result;
size_t pos = 0;
while (pos < body.size()) {
auto crlf = body.find("\r\n", pos);
if (crlf == std::string::npos || crlf == pos) break;
size_t chunk_size = 0;
for (size_t i = pos; i < crlf; ++i) {
char c = body[i];
chunk_size <<= 4;
if (c >= '0' && c <= '9') chunk_size |= static_cast<size_t>(c - '0');
else if (c >= 'a' && c <= 'f') chunk_size |= static_cast<size_t>(c - 'a' + 10);
else if (c >= 'A' && c <= 'F') chunk_size |= static_cast<size_t>(c - 'A' + 10);
else if (c == ';') break;
else break;
}
if (chunk_size == 0) break;
pos = crlf + 2;
if (pos + chunk_size > body.size()) {
result.append(body, pos, body.size() - pos);
break;
}
result.append(body, pos, chunk_size);
pos += chunk_size + 2;
}
return result;
}
static bool header_contains(const std::string& headers, const std::string& name,
const std::string& value) {
std::string lname;
lname.reserve(name.size());
for (char c : name) lname += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
std::string lval;
lval.reserve(value.size());
for (char c : value) lval += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
size_t pos = 0;
while (pos < headers.size()) {
auto line_end = headers.find('\n', pos);
if (line_end == std::string::npos) line_end = headers.size();
auto colon = headers.find(':', pos);
if (colon != std::string::npos && colon < line_end) {
std::string hdr_name;
for (size_t i = pos; i < colon; ++i)
hdr_name += static_cast<char>(std::tolower(static_cast<unsigned char>(headers[i])));
while (!hdr_name.empty() && hdr_name.back() == ' ') hdr_name.pop_back();
if (hdr_name == lname) {
size_t vstart = colon + 1;
while (vstart < line_end && headers[vstart] == ' ') ++vstart;
std::string hdr_val;
for (size_t i = vstart; i < line_end; ++i) {
char c = headers[i];
if (c == '\r') continue;
hdr_val += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
if (hdr_val.find(lval) != std::string::npos) return true;
}
}
pos = line_end + 1;
}
return false;
}
static HttpResponse parse_http_response(const std::string& raw) {
HttpResponse resp;
if (raw.size() < 12 || raw.substr(0, 5) != "HTTP/") return resp;
auto sp = raw.find(' ', 5);
if (sp == std::string::npos) return resp;
resp.status = std::atoi(raw.c_str() + sp + 1);
auto hdr_end = raw.find("\r\n\r\n");
size_t body_start;
std::string headers;
if (hdr_end == std::string::npos) {
hdr_end = raw.find("\n\n");
if (hdr_end == std::string::npos) return resp;
headers = raw.substr(0, hdr_end);
body_start = hdr_end + 2;
} else {
headers = raw.substr(0, hdr_end);
body_start = hdr_end + 4;
}
resp.body = raw.substr(body_start);
if (header_contains(headers, "Transfer-Encoding", "chunked"))
resp.body = decode_chunked(resp.body);
return resp;
}
static SSL_CTX* g_ssl_ctx = nullptr;
static std::mutex g_ssl_ctx_mutex;
static std::string g_ssl_ctx_pem;
static SSL_CTX* get_shared_ssl_ctx(const std::string& pem_path) {
std::lock_guard<std::mutex> lk(g_ssl_ctx_mutex);
if (g_ssl_ctx && g_ssl_ctx_pem == pem_path) {
// g_ssl_ctx refcount reflects one "stored" ref + one "in-use" ref.
// Caller calls SSL_CTX_free() when done, leaving the stored ref intact.
// cleanup_shared_ssl_ctx() drops the stored ref on shutdown.
SSL_CTX_up_ref(g_ssl_ctx);
return g_ssl_ctx;
}
if (g_ssl_ctx) { SSL_CTX_free(g_ssl_ctx); g_ssl_ctx = nullptr; }
SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
if (!ctx) return nullptr;
if (!pem_path.empty()) {
if (SSL_CTX_use_certificate_file(ctx, pem_path.c_str(), SSL_FILETYPE_PEM) != 1 ||
SSL_CTX_use_PrivateKey_file(ctx, pem_path.c_str(), SSL_FILETYPE_PEM) != 1) {
unsigned long err = ERR_get_error();
char err_buf[256];
ERR_error_string_n(err, err_buf, sizeof(err_buf));
LOG_ERROR("HTTPS: failed to load client cert/key from %s: %s", pem_path.c_str(), err_buf);
SSL_CTX_free(ctx);
return nullptr;
}
// Try to load server CA from the same PEM (Tomedo client certs are
// typically signed by the same CA as the server cert).
// SSL_CTX_load_verify_locations silently ignores non-CA entries.
if (SSL_CTX_load_verify_locations(ctx, pem_path.c_str(), nullptr) == 1) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr);
LOG_INFO("HTTPS: server cert verification enabled (CA from %s)", pem_path.c_str());
} else {
// CA not in PEM — disable peer verification but warn prominently.
// Patient data is still encrypted in transit; only MITM on the
// local network segment could intercept. Pin the server cert by
// exporting the Tomedo server CA and setting tomedo_ca_pem in the
// config database to enable full verification.
ERR_clear_error();
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);
LOG_WARN("HTTPS: server cert verification DISABLED — "
"Tomedo CA not found in %s. "
"Set tomedo_ca_pem in config DB to enable VERIFY_PEER.",
pem_path.c_str());
}
} else {
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);
LOG_WARN("HTTPS: no client cert configured — Tomedo mTLS disabled, "
"server cert not verified");
}
g_ssl_ctx = ctx;
g_ssl_ctx_pem = pem_path;
SSL_CTX_up_ref(g_ssl_ctx);
return ctx;
}
static void cleanup_shared_ssl_ctx() {
std::lock_guard<std::mutex> lk(g_ssl_ctx_mutex);
if (g_ssl_ctx) { SSL_CTX_free(g_ssl_ctx); g_ssl_ctx = nullptr; }
}
static HttpResponse https_request(const std::string& method,
const std::string& host, int port,
const std::string& path,
const std::string& req_body,
const std::string& pem_path,
int timeout_ms) {
HttpResponse fail;
SSL_CTX* ctx = get_shared_ssl_ctx(pem_path);
if (!ctx) return fail;
int fd = tcp_connect(host, port, timeout_ms);
if (fd < 0) { SSL_CTX_free(ctx); return fail; }
SSL* ssl = SSL_new(ctx);
SSL_set_fd(ssl, fd);
SSL_set_tlsext_host_name(ssl, host.c_str());
if (SSL_connect(ssl) != 1) {
unsigned long err = ERR_get_error();
char err_buf[256];
ERR_error_string_n(err, err_buf, sizeof(err_buf));
LOG_ERROR("HTTPS: SSL_connect to %s:%d failed: %s", host.c_str(), port, err_buf);
SSL_free(ssl); close(fd); SSL_CTX_free(ctx);
return fail;
}
std::ostringstream req;
req << method << " " << path << " HTTP/1.1\r\n"
<< "Host: " << host << ":" << port << "\r\n"
<< "Connection: close\r\n";
if (!req_body.empty()) {
req << "Content-Type: application/json\r\n"
<< "Content-Length: " << req_body.size() << "\r\n";
}
req << "\r\n" << req_body;
std::string raw_req = req.str();
int written = SSL_write(ssl, raw_req.c_str(), static_cast<int>(raw_req.size()));
if (written <= 0) {
LOG_ERROR("HTTPS: SSL_write failed for %s %s", method.c_str(), path.c_str());