-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetmsg.cc
2677 lines (2206 loc) · 87.5 KB
/
netmsg.cc
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
/* -*- mode: C++; indent-tabs-mode: nil -*-
netmsg - Mach/Hurd Network Server / Translator
This is a GNU/Hurd network proxy for passing Mach messages across a
TCP/IP connection.
Copyright (C) 2016 Brent Baccala <[email protected]>
GNU General Public License version 2 or later (your option)
Basic usage:
SERVER: netmsg -s
CLIENT: settrans -a node netmsg SERVER-HOSTNAME
The protocol is very simple. There is no initialization, no
control packets, *** NO SECURITY ***, you just open the connection
and start passing Mach messages across it. Default TCP port number
is 2345.
Initially, the server presents a fsys_server on MACH_PORT_CONTROL,
a special port number (currently -2), and the only port available
when a connection starts. The first message is invariably
fsys_getroot, sent from the client/translator to server port
MACH_PORT_CONTROL.
Mach messages are transmitted almost unchanged. Out-of-line memory
areas are transmitted immediately after the Mach message, padded to
a multiple of sizeof(long), in the order they appeared in the Mach
message.
Mach port numbers, however, receive special handling. The port
number's high-order bit is used to flag whether it's in the
sender's port number space (0) or the receiver's (1). Initially,
all ports are in the sender's space, since each side knows nothing
about the other side's ports, but as the connection progresses, the
sender will sometimes transmit a port number in the receiver's
space, and will indicate this by inverting all the bits of the port
number.
This limits our port number space to 31 bits, instead of the usual
32, and implicitly relies on Mach to prefer low-numbered ports.
There are two cases when the sender will use the receiver's port
number. One case concerns looping send rights. If Alice transfers
a send right to Bob, and Bob then transfers the same send right
back to Alice, Bob uses Alice's port number space. This allows
Alice to detect the loop and transfer a local send right to the
recipient. Otherwise, messages would be looping around the network
connection. Not only is this inefficient, but it currently creates
problems with certain programs (libpager) that are limited in the
number of clients they can handle.
No attempt to made to detect loops involving more than two parties.
The other case when the receiver's port space might be used is the
destination port of the message itself. The destination port
number in a network message falls into one of two cases. It's
either the address of a RECEIVE right in the recipient's port
space, or it's the address of a SEND right in the sender's port
space. In the later case, the sender uses the receiver's port
number.
'netmsg' can be receiving a Mach message over IPC for one of two
reasons. Either a local process passed us a RECEIVE right, or the
remote peer passed us a SEND (or SEND ONCE) right. Either
situation will causes messages to be received via IPC, but the two
cases must be handled separately.
If the message came on a RECEIVE right that we got earlier via IPC,
then the remote peer knows about this port, because it saw its port
number in a RECEIVE right when the earlier message was relayed
across the network. In this case, the sender does nothing with the
port number and sends it on across the TCP stream.
On the other hand, if the message is targeted at a SEND right that
was received earlier over TCP, we created a local receive right,
produced a proxy send right, and that's what the message came in
on. Our network peer has never seen any of these port numbers, so
we need to translate the port number of the local RECEIVE right
into the port number of the remote SEND right, and we know its
remote port number because that's what came in earlier over the
network.
BUFFERING
In order to preserve ordering of Mach messages, each destination
port (either local or remote) has a run queue of messages waiting
for delivery to it. This queue can grow arbitrarily large, so a
string of messages sent to an unresponsive receive right will cause
netmsg's memory utilization to grow without bound. This is
obviously a problem, as it defeats Mach's queue limits.
XXX known issues XXX
- no byte order swapping
- can't detect three party loops
- no Hurd authentication (it runs with the server's permissions)
- no checks made if Mach produces ports with the highest bit set
- NO SENDERS notifications are sent to the port itself, not to a control port
- race condition: when a port is destroyed, there's an interval
of time when sends return success but the messages get dropped
- emacs over netmsg hangs; last RPC is io_reauthenticate
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <error.h>
#include <argp.h>
#include <assert.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <iostream>
#include <iomanip>
#include <iosfwd>
#include <sstream>
#include <thread>
#include <mutex>
#include <vector>
#include <map>
#include <deque>
#include <set>
#include <ext/stdio_filebuf.h>
#include "machMessage.h"
/* XXX For parse_opt(), we want constants from the error_t enum, and
* not preprocessor defines for ARGP_ERR_UNKNOWN (E2BIG) and EINVAL.
*/
#undef E2BIG
#undef EINVAL
#undef EOPNOTSUPP
#undef EIEIO
#undef ENOMEM
extern "C" {
#include <mach/notify.h>
#include <hurd.h>
#include <hurd/fsys.h>
#include <hurd/sigpreempt.h>
#include "fsys_S.h"
extern int fsys_server (mach_msg_header_t *, mach_msg_header_t *);
#include "msgids.h"
};
#include "version.h"
/* mach_error()'s first argument isn't declared const, and we usually pass it a string */
#pragma GCC diagnostic ignored "-Wwrite-strings"
#pragma GCC diagnostic warning "-Wold-style-cast"
const char * argp_program_version = STANDARD_HURD_VERSION (netmsg);
const char * const defaultPort = "2345";
const char * targetPort = defaultPort;
const char * targetHost; /* required argument */
const char * exportedPath = "/"; /* server presents this path to its clients */
bool serverMode = false;
/* Normally, we run multi threaded, with each port given a separate
* thread, to better handle slow operations (both IPC and network
* sends, and OOL data backed by slow memory managers).
*
* Also, some kernel RPCs block until other RPCs complete, for
* example, vm_map will block until memory manager RPCs complete, so
* we need to run multi threaded to handle the memory manager RPCs
* while one thread remains blocked on the vm_map.
*
* See http://lists.gnu.org/archive/html/bug-hurd/2016-09/msg00002.html
*
* Sometimes, for debugging purposes, we run single threaded.
*/
const bool multi_threaded = true;
unsigned int debugLevel = 0;
template<typename... Args>
void dprintf(Args... rest)
{
if (debugLevel >= 1) while (fprintf(stderr, rest...) == -1);
}
template<typename... Args>
void ddprintf(Args... rest)
{
if (debugLevel >= 2) while (fprintf(stderr, rest...) == -1);
}
/* wassert - like assert, but only print a warning. Used in server code
* where we don't want to terminate the process.
*/
void
__wassert_fail(const char *expr, const char *file, int line, const char *func)
{
while (fprintf(stderr, "%s:%d: Assertion '%s' failed\n", file, line, expr) == -1);
}
#define wassert(expr) \
((expr) \
? __ASSERT_VOID_CAST (0) \
: __wassert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION))
void
__wassert_equal_fail(const char *expr, const int value, const int expected, const char *file, int line, const char *func)
{
while (fprintf(stderr, "%s:%d: %s is %d not %d\n", file, line, expr, value, expected) == -1);
}
#define wassert_equal(expr, value) \
((expr == value) \
? __ASSERT_VOID_CAST (0) \
: __wassert_equal_fail (#expr, expr, value, __FILE__, __LINE__, __ASSERT_FUNCTION))
/* Java-like synchronized classes
*
* An object of type synchronized<Class> will be just like an object of type Class, except that it
* comes with a mutex and can be locked.
*/
template <class T>
class synchronized : public T, public std::mutex
{
using T::T; // this picks up T's constructors
};
static const struct argp_option options[] =
{
{ "port", 'p', "N", 0, "TCP port number" },
{ "server", 's', 0, 0, "server mode" },
{ "debug", 'd', 0, 0, "debug messages (can be specified twice for more verbosity)" },
{ 0 }
};
static const char args_doc[] = "HOSTNAME";
static const char doc[] = "Network message server."
"\n"
"\nThe network message server transfers Mach IPC messages across a TCP network connection."
"\vIn server mode, the program waits for incoming TCP connections."
"\n"
"\nWhen run as a translator, the program connects to a netmsg server at HOSTNAME.";
std::map<unsigned int, const char *> mach_port_type_to_str =
{{MACH_MSG_TYPE_PORT_SEND, "SEND"},
{MACH_MSG_TYPE_PORT_SEND_ONCE, "SEND ONCE"},
{MACH_MSG_TYPE_PORT_RECEIVE, "RECEIVE"},
{MACH_MSG_TYPE_PORT_NAME, "PORTNAME"}};
/* Parse a single option/argument. */
static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
switch (key)
{
case 'p':
targetPort = arg;
break;
case 's':
serverMode = true;
break;
case 'd':
debugLevel ++;
break;
case ARGP_KEY_ARG:
if (state->arg_num == 0)
{
if (serverMode)
{
exportedPath = arg;
}
else
{
targetHost = arg;
}
}
else
{
argp_usage (state);
return ARGP_ERR_UNKNOWN;
}
break;
case ARGP_KEY_NO_ARGS:
if (!serverMode)
{
argp_usage (state);
return EINVAL;
}
}
return ESUCCESS;
}
const struct argp_child children[] =
{
{ .argp=&msgid_argp, },
{ 0 }
};
static struct argp argp = { options, parse_opt, args_doc, doc, children };
// XXX should look this up dynamically, though it's not likely to change
#define MSGID_PORT_DELETED 65
#define MSGID_NO_SENDERS 70
#define MSGID_SEND_ONCE 71
#define MSGID_DEAD_NAME 72
static const char *
msgid_name (mach_msg_id_t msgid)
{
static char buffer[16]; // XXX static buffer can be overwritten if called twice
const struct msgid_info *info = msgid_info (msgid);
if (info)
{
return info->name;
}
else
{
sprintf(buffer, "%d", msgid);
return buffer;
}
}
/* We use this unused bit in the Mach message header to indicate that
* the receiver should translate the message's destination port.
*/
#define MACH_MSGH_BITS_REMOTE_TRANSLATE 0x04000000
#if (MACH_MSGH_BITS_UNUSED & MACH_MSGH_BITS_REMOTE_TRANSLATE) != MACH_MSGH_BITS_REMOTE_TRANSLATE
#error MACH_MSGH_BITS_REMOTE_TRANSLATE seems to be in use!
#endif
/* Reserved port used to identify the server's initial control port */
/* XXX reserved by us; not necessarily by Mach! */
const mach_port_t MACH_PORT_CONTROL = (~ 1);
/* translator (network client) sets 'control' to a receive right that
* it passes back on its bootstrap port in an fsys_startup call;
* server leaves it MACH_PORT_NULL
*/
mach_port_t control = MACH_PORT_NULL;
/* class netmsg - a single netmsg session
*
* translator/client will only have a single instance of this class
*
* servers will have an instance for every client that connects to them
*
* We need to define a few more things before we're ready to define
* class netmsg itself.
*/
class netmsg;
void auditPorts(void);
/* class RunQueues
*
* To ensure in-order delivery of messages, we keep run queues,
* organized by the original destination port number as it appeared in
* the network message (not the translated port number). Each
* RunQueues has a handler function, the same of all its run queues,
* set when it's constructed. When you push onto a run queue, if it's
* empty, the message you've pushed starts processing. As each
* message completes processing, if there's anything left in the run
* queue, the top item starts processing. It's all protected by a
* mutex lock.
*
* XXX could use a thread pool. Instead we create and destroy threads
* pretty liberally as we get work and run out of it.
*/
class RunQueues : synchronized<std::map<mach_port_t, std::deque<machMessage *>>>
{
netmsg * const parent;
typedef void (netmsg::* handlerType) (machMessage &);
handlerType handler;
void
run(mach_port_t port)
{
bool empty = false;
do
{
machMessage * netmsg;
{
std::unique_lock<std::mutex> lk;
assert(! at(port).empty());
netmsg = at(port).front();
}
ddprintf("%x processing\n", netmsg);
(parent->*handler)(*netmsg);
/* for debugging purposes - audit our ports to make sure all of our invariants are still satisfied */
auditPorts();
{
std::unique_lock<std::mutex> lk;
at(port).pop_front();
delete netmsg;
empty = at(port).empty();
}
}
while (! empty);
}
public:
void
push_back(mach_port_t port, machMessage * netmsg)
{
std::unique_lock<std::mutex> lk;
bool empty = (*this)[port].empty();
(*this)[port].push_back(netmsg);
if (empty)
{
// XXX nothing is done to reap this thread
new std::thread {&RunQueues::run, this, port};
}
}
RunQueues(netmsg * const parent, handlerType handler) : parent(parent), handler(handler) { }
};
class netmsg
{
friend void auditPorts(void);
mach_port_t first_port = MACH_PORT_NULL; /* server sets this to a send right on underlying node; client leaves it MACH_PORT_NULL */
mach_port_t portset = MACH_PORT_NULL;
mach_port_t notification_port = MACH_PORT_NULL;
/* These next two maps are used for RECEIVE and SEND rights, but not SEND ONCE rights. */
std::map<mach_port_t, mach_port_t> local_ports_by_remote;
std::map<mach_port_t, mach_port_t> remote_ports_by_local;
std::map<mach_port_t, unsigned int> local_port_type; /* MACH_MSG_TYPE_PORT_RECEIVE or MACH_MSG_TYPE_PORT_SEND */
std::map<mach_port_t, mach_port_t> send_once_ports_by_remote; /* map remote send-once port to local receive port */
std::map<mach_port_t, mach_port_t> send_once_ports_by_local; /* map local receive port to remote send once port */
/* Use a non-standard GNU extension to wrap the network socket in a
* C++ iostream that will provide buffering.
*
* XXX alternative to GNU - use boost?
*
* Error handling can be done with exception (upon request), or by
* testing fs to see if it's false.
*/
__gnu_cxx::stdio_filebuf<char> filebuf_in;
__gnu_cxx::stdio_filebuf<char> filebuf_out;
std::istream is;
synchronized<std::ostream> os;
std::thread * ipcThread;
std::thread * tcpThread;
std::thread * fsysThread;
void transmitOOLdata(machMessage & msg);
void receiveOOLdata(machMessage & msg);
void translateForTransmission(machMessage & msg, bool translatePortNames);
void ipcBufferHandler(machMessage & netmsg);
void ipcHandler(void);
mach_port_t translatePort2(const mach_port_t port, const unsigned int type);
mach_port_t translatePort(const mach_port_t port, const unsigned int type);
void swapHeader(machMessage & msg);
bool translateHeader(machMessage & msg);
void translateMessage(machMessage & msg, bool translatePortNames);
void tcpHandler(void);
void tcpBufferHandler(machMessage & netmsg);
RunQueues tcp_run_queue {this, &netmsg::tcpBufferHandler};
RunQueues ipc_run_queue {this, &netmsg::ipcBufferHandler};
public:
netmsg(int networkSocket);
~netmsg();
};
/* For debugging purposes, we keep a list of all netmsg instances and
* can use them to audit our ports to ensure that all ports are
* accounted for and all our invarients are maintained.
*/
std::set<netmsg *> active_netmsg_classes;
std::string porttype2str(mach_port_type_t type)
{
std::vector<std::pair<mach_port_t, std::string>> port_types
= {{MACH_PORT_TYPE_RECEIVE, "RECEIVE"},
{MACH_PORT_TYPE_SEND, "SEND"},
{MACH_PORT_TYPE_SEND_ONCE, "SEND-ONCE"},
{MACH_PORT_TYPE_PORT_SET, "PORTSET"},
{MACH_PORT_TYPE_DEAD_NAME, "DEADNAME"},
{MACH_PORT_TYPE_DNREQUEST, "DNREQUEST"},
{MACH_PORT_TYPE_MAREQUEST, "MAREQUEST"},
{MACH_PORT_TYPE_COMPAT, "COMPACT"}};
std::string result;
for (auto & t: port_types)
{
if (type & t.first) {
//fprintf(stderr, "%s ", t.second.c_str());
result += t.second + " ";
type &= ~(t.first);
}
}
if (type)
{
//fprintf(stderr, "UNDECODED(0x%x) ", type);
result += "UNDECODED";
}
return result;
}
/* auditPorts
*
* examine our ports to insure that our invariants are satisfied
*
* Specifically, for each active netmsg class, ensure that:
*
* - portset is actually a port set
* - every port in local_port_type exists and is of the correct type
*
* XXX add some locking here so this works multi-threaded
*/
void auditPorts(void)
{
if (multi_threaded) return;
mach_port_array_t names;
mach_port_type_array_t types;
mach_msg_type_number_t ncount;
mach_msg_type_number_t tcount;
mach_call (mach_port_names(mach_task_self(), &names, &ncount, &types, &tcount));
assert(ncount == tcount);
/* Convert to a C++ map; it's easier to handle */
std::map<mach_port_t, mach_port_type_t> ports;
for (unsigned int i = 0; i < ncount; i ++)
{
ports[names[i]] = types[i];
// fprintf(stderr, "auditPorts: %ld %s\n", names[i], porttype2str(types[i]).c_str());
}
for (auto & netmsgptr: active_netmsg_classes)
{
assert(ports[netmsgptr->portset] == MACH_PORT_TYPE_PORT_SET);
for (auto & pair: netmsgptr->local_port_type)
{
if (ports.count(pair.first) == 0)
{
fprintf(stderr, "auditPorts: port %ld doesn't exist, but is recorded as %s\n",
pair.first,
pair.second == MACH_MSG_TYPE_PORT_RECEIVE ? "RECEIVE" :
pair.second == MACH_MSG_TYPE_PORT_SEND ? "SEND" :
std::to_string(pair.second).c_str());
}
else if (pair.second == MACH_MSG_TYPE_PORT_RECEIVE)
{
if (ports[pair.first] != MACH_PORT_TYPE_RECEIVE)
{
fprintf(stderr, "auditPorts: port %ld is %s, not RECEIVE\n",
pair.first, porttype2str(ports[pair.first]).c_str());
}
/* check to make sure we've got a NO SENDERS notification outstanding */
#if 0
mach_port_t old;
mach_call (mach_port_request_notification (mach_task_self (), pair.first,
MACH_NOTIFY_NO_SENDERS, 0,
pair.first,
MACH_MSG_TYPE_MAKE_SEND_ONCE, &old));
/* this assert doesn't work because pair.first is a
* RECEIVE right, but old will give us back a SEND ONCE
* right
*/
// assert(old == pair.first);
#endif
}
else if (pair.first == netmsgptr->first_port)
{
if (ports[pair.first] != (MACH_PORT_TYPE_RECEIVE | MACH_PORT_TYPE_SEND))
{
fprintf(stderr, "auditPorts: first_port %ld is %s, not RECEIVE SEND\n",
pair.first, porttype2str(ports[pair.first]).c_str());
}
}
else
{
/* Two possibilities here, since a port recorded as SEND
* might have already died, but we haven't processed the
* dead name notification yet.
*/
if ((ports[pair.first] != (MACH_PORT_TYPE_SEND | MACH_PORT_TYPE_DNREQUEST))
&& (ports[pair.first] != MACH_PORT_TYPE_DEAD_NAME))
{
fprintf(stderr, "auditPorts: port %ld is %s, not SEND DNREQUEST (or DEADNAME)\n",
pair.first, porttype2str(ports[pair.first]).c_str());
}
}
}
}
mach_call (vm_deallocate(mach_task_self(), reinterpret_cast<vm_address_t>(names), ncount * sizeof(* names)));
mach_call (vm_deallocate(mach_task_self(), reinterpret_cast<vm_address_t>(types), tcount * sizeof(* types)));
}
// XXX should be const...
// dprintMessage(const machMessage & msg)
// ... but we need a const mach_msg_iterator to make that work
void
dprintMessage(std::string prefix, machMessage & msg)
{
if (debugLevel == 0) return;
/* Print everything to a buffer, then dump it to stderr, to avoid
* interspersed output if two threads are printing at once.
*/
std::stringstream buffer;
buffer << prefix;
buffer << msg->msgh_local_port;
if (msg->msgh_remote_port)
{
buffer << "(" << msg->msgh_remote_port << ")";
}
buffer << " " << msgid_name(msg->msgh_id);
for (auto ptr = msg.data(); ptr; ++ ptr)
{
buffer << " ";
/* MACH_MSG_TYPE_STRING is special. elemsize will be 1 byte and
* nelems() will be the size of the buffer, which might be bigger
* than the NUL-terminated string that starts it.
*/
if (ptr.name() == MACH_MSG_TYPE_STRING)
{
buffer << "\"" << ptr.data().operator char *() << "\" ";
continue;
}
if (ptr.name() == MACH_MSG_TYPE_BIT)
{
assert(ptr.nelems() <= 8 * sizeof(long));
buffer << std::hex << * reinterpret_cast<long *>(static_cast<vm_address_t>(ptr.data())) << std::dec;
continue;
}
if (ptr.nelems() > 32)
{
buffer << ptr.nelems();
}
switch (ptr.name())
{
case MACH_MSG_TYPE_PORT_NAME:
buffer << "pn";
break;
case MACH_MSG_TYPE_MOVE_RECEIVE:
buffer << "r";
break;
case MACH_MSG_TYPE_MOVE_SEND:
buffer << "s";
break;
case MACH_MSG_TYPE_MOVE_SEND_ONCE:
buffer << "so";
break;
case MACH_MSG_TYPE_COPY_SEND:
buffer << "cs";
break;
case MACH_MSG_TYPE_MAKE_SEND:
buffer << "ms";
break;
case MACH_MSG_TYPE_MAKE_SEND_ONCE:
buffer << "mso";
break;
default:
;
}
if (MACH_MSG_TYPE_PORT_ANY(ptr.name()) || (ptr.name() == MACH_MSG_TYPE_PORT_NAME) || (ptr.nelems() > 1))
{
buffer << "{";
}
/* Save stream format flags because we'll change it from decimal
* to hex if we're printing a character string, to handle
* non-printing characters.
*/
std::ios::fmtflags f( buffer.flags() );
if (ptr.name() == MACH_MSG_TYPE_CHAR)
{
/* I'd like to setw(2) here, but the width gets reset to
* zero everytime you print a string (like "\x"), so it's
* pointless...
*/
buffer << std::hex << std::setfill('0');
}
for (unsigned int i = 0; i < ptr.nelems() && i < 32; i ++)
{
if ((i > 0) && (ptr.name() != MACH_MSG_TYPE_CHAR))
{
buffer << " ";
}
switch (ptr.name())
{
case MACH_MSG_TYPE_BIT:
assert(0);
case MACH_MSG_TYPE_CHAR:
{
char c = ptr[i];
if (std::isprint(c))
{
buffer << c;
}
else
{
// XXX why is this AND needed?
buffer << "\\x" << std::setw(2) << (ptr[i] & 0xff);
}
}
break;
case MACH_MSG_TYPE_INTEGER_8:
case MACH_MSG_TYPE_INTEGER_16:
case MACH_MSG_TYPE_INTEGER_32:
case MACH_MSG_TYPE_INTEGER_64:
case MACH_MSG_TYPE_PORT_NAME:
case MACH_MSG_TYPE_MOVE_RECEIVE:
case MACH_MSG_TYPE_MOVE_SEND:
case MACH_MSG_TYPE_MOVE_SEND_ONCE:
case MACH_MSG_TYPE_COPY_SEND:
case MACH_MSG_TYPE_MAKE_SEND:
case MACH_MSG_TYPE_MAKE_SEND_ONCE:
buffer << ptr[i];
break;
case MACH_MSG_TYPE_STRING:
case MACH_MSG_TYPE_REAL:
assert(0);
}
}
buffer.flags(f);
if (ptr.nelems() > 32)
{
buffer << "...";
}
if (MACH_MSG_TYPE_PORT_ANY(ptr.name()) || (ptr.name() == MACH_MSG_TYPE_PORT_NAME) || (ptr.nelems() > 1))
{
buffer << "}";
}
}
buffer << "\n";
std::cerr << buffer.str();
}
void
netmsg::transmitOOLdata(machMessage & msg)
{
for (auto ptr = msg.data(); ptr; ++ ptr)
{
if ((! ptr.is_inline()) && (ptr.data_size() > 0))
{
os.write(ptr.data(), ptr.data_size());
vm_deallocate(mach_task_self(), ptr.data(), ptr.data_size());
}
}
}
void
netmsg::receiveOOLdata(machMessage & msg)
{
for (auto ptr = msg.data(); ptr; ++ ptr)
{
if (! ptr.is_inline() && (ptr.data_size() > 0))
{
mach_call (vm_allocate(mach_task_self(), ptr.OOLptr(), ptr.data_size(), 1));
is.read(ptr.data(), ptr.data_size());
}
}
}
/* OOL data can point to a memory region backed by an unreliable
* memory manager. In this case, we don't want to wait until we're
* trying to transmit over the network before finding this out, so we
* copy it now into our own address space.
*
* What should we do if this fails? Most precisely, we should mimic
* this behavior on the remote by arranging for it to have a faulting
* memory manager (presumably implemented by netmsg)! Instead, I just
* ignore the return value from hurd_safe_copyin, so we just get
* zero-filled memory from vm_allocate passed on to the recipient.
*/
void
copyOOLdata(machMessage & msg)
{
for (auto ptr = msg.data(); ptr; ++ ptr)
{
if (! ptr.is_inline() && (ptr.data_size() > 0))
{
vm_address_t new_location;
mach_call (vm_allocate(mach_task_self(), &new_location, ptr.data_size(), 1));
hurd_safe_copyin(reinterpret_cast<void *>(new_location), ptr.data().operator void *(), ptr.data_size());
mach_call (vm_deallocate(mach_task_self(), ptr.data(), ptr.data_size()));
/* XXX perhaps ptr.data() should return a reference to facilitate this step */
* ptr.OOLptr() = new_location;
}
}
}
void
netmsg::translateForTransmission(machMessage & msg, bool translatePortNames)
{
for (auto ptr = msg.data(); ptr; ++ ptr)
{
switch (ptr.name())
{
case MACH_MSG_TYPE_MOVE_SEND:
{
mach_port_t * ports = ptr.data();
for (unsigned int i = 0; i < ptr.nelems(); i ++)
{
if ((ports[i] == MACH_PORT_NULL) || (ports[i] == MACH_PORT_DEAD))
{
continue;
}
else if (remote_ports_by_local.count(ports[i]) == 1)
{
/* We're transmitting a send right that we earlier
* received over the network. Convert to the
* remote's name space, and indicate to the
* remote, by bit flipping the port number, that
* we're sending it a port number in its own name
* space. Also, destroy the send right we
* received with the message, which is a send
* right to ourself! If it's the port's last send
* right, then we'll get a no senders notification
* and deallocate the receive right then, so all
* we destroy here is the send right.
*/
assert(local_port_type.at(ports[i]) == MACH_MSG_TYPE_PORT_RECEIVE);
mach_call (mach_port_mod_refs (mach_task_self(), ports[i],
MACH_PORT_RIGHT_SEND, -1));
ports[i] = (~ remote_ports_by_local[ports[i]]);
}
else
{
/* We've got a send right (note it), but no
* mapping to a remote port (the remote takes care
* of that).
*/
local_port_type[ports[i]] = MACH_MSG_TYPE_PORT_SEND;
/* request a DEAD NAME notification */
mach_port_t old;
mach_call (mach_port_request_notification (mach_task_self (), ports[i],
MACH_NOTIFY_DEAD_NAME, 0,
notification_port,
MACH_MSG_TYPE_MAKE_SEND_ONCE, &old));
// If we've already seen this send right in an earlier message, 'old'
// will be an existing SEND ONCE right targeted at notification_port,
// so this assert might fail.
// assert(old == MACH_PORT_NULL);
}
}
}
break;
case MACH_MSG_TYPE_MOVE_RECEIVE:
{
mach_port_t * ports = ptr.data();
for (unsigned int i = 0; i < ptr.nelems(); i ++)
{
if ((ports[i] == MACH_PORT_NULL) || (ports[i] == MACH_PORT_DEAD))
{
continue;
}
/* We're transmitting a receive right over the
* network. Add it to our port set, and request a
* NO SENDERS notification on it.
*/
mach_call (mach_port_move_member (mach_task_self (), ports[i], portset));
mach_port_t old;
mach_call (mach_port_request_notification (mach_task_self (), ports[i],
MACH_NOTIFY_NO_SENDERS, 0,
ports[i],
MACH_MSG_TYPE_MAKE_SEND_ONCE, &old));
/* Mach 3 Kernel Interface, page 60:
*
* (Note: Currently, moving a receive right does not
* affect any extant no-senders notifications. It is
* currently planned to change this so that no-
* senders notifications are canceled, with a
* send-once notification sent to indicate the
* cancelation.)
*
* We're moving a receive right. To massively
* simplify this code, we implement the proposed
* change here, generating a send-once notification by
* simply destroying the send-once right.
*/