How to find last relay node of a data packet in-transit? - iot

I'm trying to implement a security mechanism in RPL. For this, I need to log where did a packet come from. For example, if a packet is transmitted from A-->B-->C-->D, I want to find out at C that the packet came through B, and similarly for D.
I've added some code in uip6.c file to pull up the sender address from packetbuffer, but it is always null.
I'm storing the last node address and the time when the complete packet was received. These are the data structures.
struct packet_time_entry {
linkaddr_t *source;
uint32_t time;
};
MEMB(packet_time_mem, struct packet_time_entry, 16);
LIST(packet_time);
The main code I've written so far is this, in uip_process(), below line 1108 (master branch).
struct packet_time_entry *p = memb_alloc(&packet_time_mem);
p->time = clock_time();
linkaddr_copy(p->source, packetbuf_addr(PACKETBUF_ADDR_SENDER));
struct packet_time_entry *i;
for (i = list_head(packet_time); i != NULL; i = list_item_next(i)) {
if (linkaddr_cmp(i->source, p->source))
list_remove(packet_time, i);
}
list_add(packet_time, p);
PRINTF("Entry ");
PRINTLLADDR((uip_lladdr_t*) p->source); // always NULL
PRINTF("| %lu", p->time);
PRINTF("\n");
I expect it to give me the address from packetbuf, but it's always NULL. Also, I suspect it is run only at the destination node, but not at the intermediate nodes.

You can DEBUG the execution. For that just set DEBUG_NONE TO DEBUG_PRINT in uip6.c and then parse the serial log for finding the path taken by the packet.

Related

Dart TCP socket concatenates all 'write' sync calls as a single packet

I'm trying to send multiple packets at once to a server, but the socket keeps "merging" all sync calls to write as a single call, I did a minimal reproducible example:
import 'dart:io';
void main() async {
// <Server-side> Create server in the local network at port <any available port>.
final ServerSocket server =
await ServerSocket.bind(InternetAddress.anyIPv4, 0);
server.listen((Socket client) {
int i = 1;
client.map(String.fromCharCodes).listen((String message) {
print('Got a new message (${i++}): $message');
});
});
// <Client-side> Connects to the server.
final Socket socket = await Socket.connect('localhost', server.port);
socket.write('Hi World');
socket.write('Hello World');
}
The result is:
> dart example.dart
> Got a new message (1): Hi WorldHello World
What I expect is:
> dart example.dart
> Got a new message (1): Hi World
> Got a new message (2): Hello World
Unfortunately dart.dev doesn't support dart:io library, so you need to run in your machine to see it working.
But in summary:
It creates a new tcp server at a random port.
Then creates a socket that connects to the previous created server.
The socket makes 2 synchronous calls to the write method.
The server only receives 1 call, which is the 2 messages concatenated.
Do we have some way to receive each synchronous write call in the server as separated packets instead buffering all sync calls into a single packet?
What I've already tried:
Using socket.setOption(SocketOption.tcpNoDelay, true); right after Socket.connect instantiation, this does modify the result:
final Socket socket = await Socket.connect('localhost', server.port);
socket.setOption(SocketOption.tcpNoDelay, true);
// ...
Using socket.add('Hi World'.codeUnits); instead of socket.write(...), also does not modify the result as expected, because write(...) seems to be just a short version add(...):
socket.add('Hi World'.codeUnits);
socket.add('Hello World'.codeUnits);
Side note:
Adding an async delay to avoid calling write synchronously:
socket.add('Hi World'.codeUnits);
await Future<void>.delayed(const Duration(milliseconds: 100));
socket.add('Hello World'.codeUnits);
make it works, but I am pretty sure this is not the right solution, and this isn't what I wanted.
Environment:
Dart SDK version: 2.18.4 (stable) (Tue Nov 1 15:15:07 2022 +0000) on "windows_x64"
This is a Dart-only environment, there is no Flutter attached to the workspace.
As Jeremy said:
Programmers coding directly to the TCP API have to implement this logic themselves (e.g. by prepending a fixed-length message-byte-count field to each of their application-level messages, and adding logic to the receiving program to parse these byte-count fields, read in that many additional bytes, and then present those bytes together to the next level of logic).
So I chose to:
Prefix each message with a - and suffix with ..
Use base64 to encode the real message to avoid conflict between the message and the previously defined separators.
And using this approach, I got this implementation:
// Send packets:
socket.write('-${base64Encode("Hi World".codeUnits)}.');
socket.write('-${base64Encode("Hello World".codeUnits)}.');
And to parse the packets:
// Cache the previous parsed packet data.
String parsed = '';
void _handleCompletePacket(String rawPacket) {
// Decode the original message from base64 using [base64Decode].
// And convert the [List<int>] to [String].
final String message = String.fromCharCodes(base64Decode(rawPacket));
print(message);
}
void _handleServerPacket(List<int> rawPacket) {
final String packet = String.fromCharCodes(rawPacket);
final String next = parsed + packet;
final List<String> items = <String>[];
final List<String> tokens = next.split('');
for (int i = 0; i < tokens.length; i++) {
final String char = tokens[i];
if (char == '-') {
if (items.isNotEmpty) {
// malformatted packet.
items.clear();
continue;
}
items.add('');
continue;
} else if (char == '.') {
if (items.isEmpty) {
// malformatted packet.
items.clear();
continue;
}
_handleCompletePacket(items.removeLast());
continue;
} else {
if (items.isEmpty) {
// malformatted packet.
items.clear();
continue;
}
items.last = items.last + char;
continue;
}
}
if (items.isNotEmpty) {
// the last data of this packet was left incomplete.
// cache it to complete with the next packet.
parsed = items.last;
}
}
client.listen(_handleServerPacket);
There are certainly more optimized solutions/approaches, but I got this just for chatting messages within [100-500] characters, so that's fine for now.

Is there a way to make separate DNS requests for IPv4 and IPv6 in swift or ObjC

What I have so far is:
void startQueryIPv4(const char *hostName){
printf("startQueryIPv4");
DNSServiceRef serviceRef;
DNSServiceGetAddrInfo(&serviceRef, kDNSServiceFlagsForceMulticast, 0, kDNSServiceProtocol_IPv4, hostName, queryIPv4Callback, NULL);
DNSServiceProcessResult(serviceRef);
DNSServiceRefDeallocate(serviceRef);
}
static void queryIPv4Callback(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *hostname, const struct sockaddr *address, uint32_t ttl, void *context){
printf("queryIPv4Callback");
if (errorCode == kDNSServiceErr_NoError) {
printf("no error");
char *theAddress = NULL;
switch(address->sa_family) {
case AF_INET: {
struct sockaddr_in *addr_in = (struct sockaddr_in *)address;
theAddress = malloc(INET_ADDRSTRLEN);
inet_ntop(AF_INET, &(addr_in->sin_addr), theAddress, INET_ADDRSTRLEN);
break;
}
case AF_INET6: {
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)address;
theAddress = malloc(INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, &(addr_in6->sin6_addr), theAddress, INET6_ADDRSTRLEN);
break;
}
default:
break;
}
printf("IP address: %s\n", theAddress);
free(theAddress);
} else {
printf("%d", errorCode);
}
}
But the callback is never called.
In the console I get this error: TIC Read Status [9:0x0]: 1:57
ObjectiveC is not my power but I had to mess with it. Any help will be appreciated.
Inasmuch as Objective-C is a true superset of C and Darwin is certified compatible with SUS 3, your Objective-C program for iOS should be able to use the C interface to the system's name resolver: getaddrinfo(). You can use the third argument to this function to specify that you want only IPv4 results (or only IPv6 results).
Things of which you should be aware:
this is of course a synchronous interface; if you want asynchronous then you'll need to arrange for that yourself.
getaddrinfo() allocates and returns a linked list of addresses, so
in principle, you might need to check more than one
you need to free the list after you're done with it via freeaddrinfo()
The reason you aren't getting a callback is that you aren't using a dispatch queue. The DNSServiceGetAddrInfo API is asynchronous. If you are doing this on an Apple device, you want something more like this:
void startQueryIPv4(const char *hostName) {
printf("startQueryIPv4");
DNSServiceRef serviceRef;
DNSServiceGetAddrInfo(&serviceRef, kDNSServiceFlagsForceMulticast, 0, kDNSServiceProtocol_IPv4, hostName, queryIPv4Callback, NULL);
main_queue = dispatch_get_main_queue();
DNSServiceSetDispatchQueue(sdref, main_queue);
dispatch_main();
}
Note that dispatch_main() is the main event loop for libdispatch: if you want to do other stuff, you need to schedule it in the dispatch loop, because dispatch_main() will not return.
In your original code you called DNSServiceRefDeallocate(), but you can't do that until you want to stop the query. If you call it right after you start the query, it will cancel the query. So e.g. you could call it from the callback.
However, a better flow would be to do a long-lived query (kDNSServiceFlagsLongLivedQuery) so that you get an update whenever the information changes. Of course you'd then need to change the host you're connecting to, so only do this if your application will be connected for an extended period.
Additionally, you may get more than one answer. If you do, it may be that some answers work to connect, and others don't. So you might like to accumulate answers and try each one, rather than giving up if the first answer you get doesn't work. The callback will include the kDNSServiceFlagsMoreComing flag if there is more data coming immediately. Each time the callback is called, it will get one answer (or an indication that the query has failed in some way).
Of course, this is a fairly low-level API. If you want to make your life a bit easier, you should use Network Framework. Network Framework does the "happy eyeballs" part for you—trying each response until it gets a connection, and returning you the connection it gets, canceling the others.
But you didn't ask about that, so I won't go into details here.

http response got truncated in docker

I've built a http server using netty. Everything is fine when it's running in my mac, but when I run it in a docker image, the http response always get truncated when great than 460k.
What's the problem will be? Please help.
Do you use aggregator to aggregate the http response or not? Take a look at the source code of HttpObjectDecoder. It will chunk bigger http response no matter if the http message itself is transfer coding or not.
The default maxChunk size is 8k.And even readable bytes is enough, it will chunk it. see the code below:
` case READ_FIXED_LENGTH_CONTENT: {
int readLimit = actualReadableBytes();
// Check if the buffer is readable first as we use the readable byte count
// to create the HttpChunk. This is needed as otherwise we may end up with
// create a HttpChunk instance that contains an empty buffer and so is
// handled like it is the last HttpChunk.
//
// See https://github.com/netty/netty/issues/433
if (readLimit == 0) {
return;
}
int toRead = Math.min(readLimit, maxChunkSize);
if (toRead > chunkSize) {
toRead = (int) chunkSize;
}
ByteBuf content = readBytes(ctx.alloc(), buffer, toRead);
chunkSize -= toRead;
`

New Command 2 Apple Push Notification Not sending multiple alerts

I am trying to implement the new 'Command 2' push notification in Java and cannot have it push multiple alerts. First alert is pushed successfully. Please help if you can spot any issue on this code
Apple specs
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW1
for (DeviceApps deviceApps : deviceAppsList) {
outputStream.write(getByteArray(deviceApps, pushAlert));
}
private byte[] getByteArray(DeviceApps deviceApps, PushAlert pushAlert) {
ByteArrayOutputStream dataBao = new ByteArrayOutputStream();
// Write the TokenLength as a 16bits unsigned int, in big endian
dataBao.write((byte)1);
dataBao.write(intTo2ByteArray(32));
dataBao.write(deviceTokenAsBytes);
// Write the PayloadLength as a 16bits unsigned int, in big endian
dataBao.write((byte)2);
dataBao.write(intTo2ByteArray(payLoadAsBytes.length));
dataBao.write(payLoadAsBytes);
// 4 bytes. Notification identifier
dataBao.write((byte)3);
dataBao.write(intTo2ByteArray(4));
dataBao.write(intTo4ByteArray(random.nextInt()));
// 4 bytes Expiration date
dataBao.write((byte)4);
dataBao.write(intTo2ByteArray(4));
dataBao.write(intTo4ByteArray(pushAlert.getUtcExpireTime()));
LOG.error("UtcExpireTime="+ pushAlert.getUtcExpireTime());
// 1 bytes Priority
dataBao.write((byte)5);
dataBao.write(intTo2ByteArray(1));
dataBao.write((byte)10);
//Frame Info
bao = new ByteArrayOutputStream();
bao.write((byte)2);
byte [] data = dataBao.toByteArray();
bao.write(intTo4ByteArray(data.length));
LOG.error(" data.length "+data.length);
bao.write(data);
return bao.toByteArray();
}
Support Methods
private static final byte[] intTo4ByteArray(int value) {
return ByteBuffer.allocate(4).putInt(value).array();
}
private static final byte[] intTo2ByteArray(int value) {
int s1 = (value & 0xFF00) >> 8;
int s2 = value & 0xFF;
return new byte[] { (byte) s1, (byte) s2 };
}
It looks like you are writing a single notification to bao, so why do you expect it to push multiple alerts? If you want to push multiple alerts, you have to repeat that sequence of bytes that you write into bao multiple times.
The command 2 and the frame data length applies to each message. If you send multiple messages in one connection, then for each message: send command 2, the message's frame data length, and the 5 parts (token, payload, id, expiry, priority)
Since you are getting back a an error code from APNS, the connection should be dropped at that point and APNS will ignore everything after the error. When you receive an error back, the identifier is the identifier you are currently using a random number for.
There's no easy solution here -- you have to rearchitect what you have so that when you receive the error, you can figure out everything after that point and resend -- I'd recommend using a sequential number for the Identifier and then storing the packets in a queue that you purge periodically (you have to keep them around for say 30 seconds to guarantee that Apple Accepted them).

bytesWritten, but other device never receives NSStreamEventHasBytesAvailable event

I have set up a Bonjour network between an iPhone and a Mac.
The user chooses the iPhone’s net service in a table presented in the Mac, and a pair of streams are created and opened on both sides.
The iPhone starts by sending a code (an integer) to the Mac. The Mac successfully receives it.
After a pause for user input and processing, the Mac initiates sending a code to the iPhone:
NSInteger bytesWritten = [self.streamOut write:buffer maxLength:sizeof(uint8_t)];
// bytesWritten is 1.
But the iPhone never gets an NSStreamEventHasBytesAvailable event. I double-checked just before this point, and streamStatus on the iPhone’s NSInputStream is 2, which is NSStreamStatusOpen, as it should be.
Any ideas what could be wrong?
Update: I ran a test in which the Mac was the first to send an integer to the iPhone. Again, I got a bytesWritten of 1 from the Mac’s output stream, but the iPhone never got a NSStreamEventHasBytesAvailable event.
So there must be something wrong with the iPhone’s input stream. But I doublechecked:
iPhone’s self.streamIn is correctly typed as NSInputStream in the h file
iPhone receives 2 NSStreamEventOpenCompleted events, and I check the class of the stream arg. One isKindOfClass:[NSOutputStream class], the other isn’t.
iPhone never receives NSStreamEventEndEncountered, NSStreamEventErrorOccurred, or NSStreamEventNone.
As noted above, following the Mac’s write to output stream, iPhone’s input stream status is 2, NSStreamStatusOpen.
Here is the code used to create the iPhone's input stream. It uses CF types because it's done in the C-style socket callback function:
CFReadStreamRef readStream = NULL;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, NULL);
if (readStream) {
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
server.streamIn = (NSInputStream *)readStream;
server.streamIn.delegate = server;
[server.streamIn scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
if ([server.streamIn streamStatus] == NSStreamStatusNotOpen)
[server.streamIn open];
CFRelease(readStream);
}
Update2: Info responsive to alastair’s comment:
Socket Options
The retain, release, and copyDescription callbacks are set to NULL. The optionFlags are set to acceptCallback.
Socket Creation
Here’s the method used to set up the socket on both the iPhone and the Mac, complete with my commented attempts to figure out what is actually going on in this code, which was adapted from various tutorials and experiments (which worked):
/**
Socket creation, port assignment, socket scheduled in run loop.
The socket represents the port on this app's end of the connection.
*/
- (BOOL) makeSocket {
// Make a socket context, with which to configure the socket.
// It's a struct, but doesn't require "struct" prefix -- because typedef'd?
CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL}; // 2nd arg is pointer for callback function
// Make socket.
// Sock stream goes with TCP protocol, the safe method used for most data transmissions.
// kCFSocketAcceptCallBack accepts connections automatically and presents them to the callback function supplied in this class ("acceptSocketCallback").
// CFSocketCallBack, the callback function itself.
// And note that the socket context is passed in at the end.
self.socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)&acceptSocketCallback, &socketCtxt);
// Do socket-creation error checking.
if (self.socket == NULL) {
// alert omitted
return NO;
}
// Prepare an int to pass to setsockopt function, telling it whether to use the option specified in arg 3.
int iSocketOption = 1; // 1 means, yes, use the option
// Set socket options.
// arg 1 is an int. C-style method returns native socket.
// arg 2, int for "level." SOL_SOCKET is standard.
// arg 3, int for "option name," which is "uninterpreted." SO_REUSEADDR enables local address reuse. This allows a new connection even when a port is in wait state.
// arg 4, void (wildcard type) pointer to iSocketOption, which has been set to 1, meaning, yes, use the SO_REUSEADDR option specified in arg 3.
// args 5, the size of iSocketOption, which can now be recycled as a buffer to report "the size of the value returned," whatever that is.
setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, (void *)&iSocketOption, sizeof(iSocketOption));
// Set up a struct to take the port assignment.
// The identifier "addr4" is an allusion to IP version 4, the older protocol with fewer addresses, which is fine for a LAN.
struct sockaddr_in addr4;
memset(&addr4, 0, sizeof(addr4));
addr4.sin_len = sizeof(addr4);
addr4.sin_family = AF_INET;
addr4.sin_port = 0; // this is where the socket will assign the port number
addr4.sin_addr.s_addr = htonl(INADDR_ANY);
// Convert to NSData so struct can be sent to CFSocketSetAddress.
NSData *address4 = [NSData dataWithBytes:&addr4 length:sizeof(addr4)];
// Set the port number.
// Struct still needs more processing. CFDataRef is a pointer to CFData, which is toll-free-bridged to NSData.
if (CFSocketSetAddress(socket, (CFDataRef)address4) != kCFSocketSuccess) {
// If unsuccessful, advise user of error (omitted)…
// ... and discard the useless socket.
if (self.socket)
CFRelease(socket);
self.socket = NULL;
return NO;
}
// The socket now has the port address. Extract it.
NSData *addr = [(NSData *)CFSocketCopyAddress(socket) autorelease];
// Assign the extracted port address to the original struct.
memcpy(&addr4, [addr bytes], [addr length]);
// Use "network to host short" to convert port number to host computer's endian order, in case network's is reversed.
self.port = ntohs(addr4.sin_port);
printf("\nUpon makeSocket, the port is %d.", self.port);// !!!:testing - always prints a 5-digit number
// Get reference to main run loop.
CFRunLoopRef cfrl = CFRunLoopGetCurrent();
// Schedule socket with run loop, by roundabout means.
CFRunLoopSourceRef source4 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
CFRunLoopAddSource(cfrl, source4, kCFRunLoopCommonModes);
CFRelease(source4);
// Socket made
return YES;
}
Runloop Scheduling
Yes, all 4 streams are scheduled in the runloop, all using code equivalent to what I posted in the first update above.
Runloop Blocking:
I’m not doing anything fancy with synchronization, multiple threads, NSLocks, or the like. And if I set a button action to print something to the console, it works throughout — the runloop seems to be running normally.
Update4, Stream Ports?
Noa's debugging suggestion gave me the idea to examine the stream properties further:
NSNumber *nTest = [self.streamIn propertyForKey:NSStreamSOCKSProxyPortKey]; // always null!
I had assumed that the streams were hanging onto their ports, but surprisingly, nTest is always null. It's null in my apps, which would seem to point to a problem -- but it's also null in a tutorial app that works. If a stream doesn't need to hang onto its port assignment once created, what is the purpose of the port property?
Maybe the port property is not accessible directly? But nTest is always null in the following, too:
NSDictionary *dTest = [theInStream propertyForKey:NSStreamSOCKSProxyConfigurationKey];
NSNumber *nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
NSLog(#"\tInstream port is %#.", nTest); // (null)
nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
NSLog(#"\tOutstream port is %#.", nTest); // (null)
The trouble was this line:
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, NULL);
This would have been OK if I were only receiving data on the iPhone end. But I was creating a pair of streams, not just an input stream, so below this code I was creating a write stream:
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, NULL, &writeStream);
The CFStream Reference says, “If you pass NULL [for readStream], this function will not create a readable stream.” It doesn’t say that if you pass NULL, you’ll render a previously created stream inoperable. But that is apparently what happens.
One strange artifact of this setup was that if I opened the streamIn first, I would have the opposite problem: The iPhone would get hasByteAvailable events, but never a hasSpaceAvailable event. And as noted in the question, if I queried the streams for their status, both would return NSStreamStatusOpen. So it took a long time to figure out where the real mistake was.
(This sequential stream creation was an artifact of a test project I had set up months before, in which I tested data moving in only one direction or the other.)
SOLUTION
Both streams should be created as a pair, in one line:
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, &writeStream);

Resources