summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/SDLTCPTransport.m
blob: 91e693c8b28347dd8769911878b4dc24c96cc75d (plain)
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
//  SDLTCPTransport.m
//


#import "SDLTCPTransport.h"
#import "SDLLogConstants.h"
#import "SDLLogMacros.h"
#import "SDLLogManager.h"
#import "SDLHexUtility.h"
#import <errno.h>
#import <netdb.h>
#import <netinet/in.h>
#import <signal.h>
#import <stdio.h>
#import <sys/socket.h>
#import <sys/types.h>
#import <sys/wait.h>
#import <unistd.h>

NS_ASSUME_NONNULL_BEGIN

// C function forward declarations.
int call_socket(const char *hostname, const char *port);
static void TCPCallback(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info);

@interface SDLTCPTransport () {
    dispatch_queue_t _sendQueue;
}

@end


@implementation SDLTCPTransport

- (instancetype)init {
    if (self = [super init]) {
        _sendQueue = dispatch_queue_create("com.sdl.transport.tcp.transmit", DISPATCH_QUEUE_SERIAL);
        SDLLogD(@"TCP Transport initialization");
    }

    return self;
}

- (void)dealloc {
    [self disconnect];
}

- (void)connect {
    SDLLogD(@"Attemping to connect");

    int sock_fd = call_socket([self.hostName UTF8String], [self.portNumber UTF8String]);
    if (sock_fd < 0) {
        SDLLogE(@"Server not ready, connection failed");
        return;
    }

    CFSocketContext socketCtxt = {0, (__bridge void *)(self), NULL, NULL, NULL};
    socket = CFSocketCreateWithNative(kCFAllocatorDefault, sock_fd, kCFSocketDataCallBack | kCFSocketConnectCallBack, (CFSocketCallBack)&TCPCallback, &socketCtxt);
    CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
    CFRunLoopRef loop = CFRunLoopGetCurrent();
    CFRunLoopAddSource(loop, source, kCFRunLoopDefaultMode);
    CFRelease(source);
}

- (void)sendData:(NSData *)msgBytes {
    dispatch_async(_sendQueue, ^{
        @autoreleasepool {
            SDLLogBytes(msgBytes, SDLLogBytesDirectionTransmit);
            CFSocketError e = CFSocketSendData(socket, NULL, (__bridge CFDataRef)msgBytes, 10000);
            if (e != kCFSocketSuccess) {
                NSString *errorCause = nil;
                switch (e) {
                    case kCFSocketTimeout:
                        errorCause = @"Socket Timeout Error.";
                        break;

                    case kCFSocketError:
                    default:
                        errorCause = @"Socket Error.";
                        break;
                }

                SDLLogE(@"Socket send error: %@", errorCause);
            }
        }
    });
}

- (void)disconnect {
    SDLLogD(@"Disconnect connection");
    
    if (socket != nil) {
        CFSocketInvalidate(socket);
        CFRelease(socket);
        socket = nil;
    }
}

@end

// C functions
int call_socket(const char *hostname, const char *port) {
    int status, sock;
    struct addrinfo hints;
    struct addrinfo *servinfo;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    //no host name?, no problem, get local host
    if (hostname == nil) {
        char localhost[128];
        gethostname(localhost, sizeof localhost);
        hostname = (const char *)&localhost;
    }

    //getaddrinfo setup
    if ((status = getaddrinfo(hostname, port, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
        return (-1);
    }

    //get socket
    if ((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) < 0)
        return (-1);

    //connect
    if (connect(sock, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
        close(sock);
        return (-1);
    }

    freeaddrinfo(servinfo); // free the linked-list
    return (sock);
}

static void TCPCallback(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
    if (kCFSocketConnectCallBack == type) {
        SDLTCPTransport *transport = (__bridge SDLTCPTransport *)info;
        [transport.delegate onTransportConnected];
    } else if (kCFSocketDataCallBack == type) {
        SDLTCPTransport *transport = (__bridge SDLTCPTransport *)info;

        // Check if Core disconnected from us
        if (CFDataGetLength((CFDataRef)data) <= 0) {
            SDLLogW(@"Remote system terminated connection, data packet length 0");
            [transport.delegate onTransportDisconnected];

            return;
        }

        // Handle the data we received
        NSData *convertedData = [NSData dataWithBytes:(UInt8 *)CFDataGetBytePtr((CFDataRef)data) length:(int)CFDataGetLength((CFDataRef)data)];
        SDLLogBytes(convertedData, SDLLogBytesDirectionReceive);
        [transport.delegate onDataReceived:convertedData];
    } else {
        SDLLogW(@"Unhandled callback type: %lu", type);
    }
}

NS_ASSUME_NONNULL_END