Debian Codegraph @

src/vendor/azure-uamqp-c/deps/azure-c-shared-utility/pal/ios-osx/tlsio_appleios.c

raw
1 // Copyright (c) Microsoft. All rights reserved.
2 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4 #include <stdlib.h>
5
6 #include <stdio.h>
7 #include <stdint.h>
8 #include <stdbool.h>
9 #include <time.h>
10 #include "tlsio_appleios.h"
11 #include "azure_c_shared_utility/xio.h"
12 #include "azure_c_shared_utility/gballoc.h"
13 #include "azure_c_shared_utility/xlogging.h"
14 #include "azure_c_shared_utility/agenttime.h"
15 #include "azure_c_shared_utility/singlylinkedlist.h"
16 #include "azure_c_shared_utility/crt_abstractions.h"
17 #include "azure_c_shared_utility/tlsio_options.h"
18 #include "azure_c_shared_utility/safe_math.h"
19
20
21 #include <CoreFoundation/CoreFoundation.h>
22 #include <CoreFoundation/CFError.h>
23 #include <CFNetwork/CFSocketStream.h>
24 #include <Security/SecureTransport.h>
25
26 typedef struct
27 {
28 unsigned char* bytes;
29 size_t size;
30 size_t unsent_size;
31 ON_SEND_COMPLETE on_send_complete;
32 void* callback_context;
33 } PENDING_TRANSMISSION;
34
35 #define MAX_VALID_PORT 0xffff
36
37 const char WEBSOCKET_HEADER_START[] = "GET /$iothub/websocket";
38 const char WEBSOCKET_HEADER_NO_CERT_PARAM[] = "?iothub-no-client-cert=true";
39 const size_t WEBSOCKET_HEADER_START_SIZE = sizeof(WEBSOCKET_HEADER_START) - 1;
40 const size_t WEBSOCKET_HEADER_NO_CERT_PARAM_SIZE = sizeof(WEBSOCKET_HEADER_NO_CERT_PARAM) - 1;
41
42 // The TLSIO_RECEIVE_BUFFER_SIZE has very little effect on performance, and is kept small
43 // to minimize memory consumption.
44 #define TLSIO_RECEIVE_BUFFER_SIZE 64
45
46
47 typedef enum TLSIO_STATE_TAG
48 {
49 TLSIO_STATE_CLOSED,
50 TLSIO_STATE_OPENING_WAITING_DNS,
51 TLSIO_STATE_OPENING_WAITING_SOCKET,
52 TLSIO_STATE_OPENING_WAITING_SSL,
53 TLSIO_STATE_OPEN,
54 TLSIO_STATE_ERROR,
55 } TLSIO_STATE;
56
57 bool is_an_opening_state(TLSIO_STATE state)
58 {
59 return state == TLSIO_STATE_OPENING_WAITING_DNS ||
60 state == TLSIO_STATE_OPENING_WAITING_SOCKET ||
61 state == TLSIO_STATE_OPENING_WAITING_SSL;
62 }
63
64 typedef struct TLS_IO_INSTANCE_TAG
65 {
66 ON_BYTES_RECEIVED on_bytes_received;
67 ON_IO_ERROR on_io_error;
68 ON_IO_OPEN_COMPLETE on_open_complete;
69 void* on_bytes_received_context;
70 void* on_io_error_context;
71 void* on_open_complete_context;
72 TLSIO_STATE tlsio_state;
73 CFStringRef hostname;
74 uint16_t port;
75 bool no_messages_yet_sent;
76 CFReadStreamRef sockRead;
77 CFWriteStreamRef sockWrite;
78 SINGLYLINKEDLIST_HANDLE pending_transmission_list;
79 TLSIO_OPTIONS options;
80 } TLS_IO_INSTANCE;
81
82 /* Codes_SRS_TLSIO_30_005: [ The phrase "enter TLSIO_STATE_EXT_ERROR" means the adapter shall call the on_io_error function and pass the on_io_error_context that was supplied in tlsio_open_async. ]*/
83 static void enter_tlsio_error_state(TLS_IO_INSTANCE* tls_io_instance)
84 {
85 if (tls_io_instance->tlsio_state != TLSIO_STATE_ERROR)
86 {
87 tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
88 tls_io_instance->on_io_error(tls_io_instance->on_io_error_context);
89 }
90 }
91
92 /* Codes_SRS_TLSIO_30_005: [ When the adapter enters TLSIO_STATE_EXT_ERROR it shall call the on_io_error function and pass the on_io_error_context that were supplied in tlsio_open . ]*/
93 static void enter_open_error_state(TLS_IO_INSTANCE* tls_io_instance)
94 {
95 // save instance variables in case the framework destroys this object before we exit
96 ON_IO_OPEN_COMPLETE on_open_complete = tls_io_instance->on_open_complete;
97 void* on_open_complete_context = tls_io_instance->on_open_complete_context;
98 enter_tlsio_error_state(tls_io_instance);
99 on_open_complete(on_open_complete_context, IO_OPEN_ERROR);
100 }
101
102 // Return true if a message was available to remove
103 static bool process_and_destroy_head_message(TLS_IO_INSTANCE* tls_io_instance, IO_SEND_RESULT send_result)
104 {
105 bool result;
106 LIST_ITEM_HANDLE head_pending_io;
107 if (send_result == IO_SEND_ERROR)
108 {
109 /* Codes_SRS_TLSIO_30_095: [ If the send process fails before sending all of the bytes in an enqueued message, the tlsio_dowork shall call the message's on_send_complete along with its associated callback_context and IO_SEND_ERROR. ]*/
110 enter_tlsio_error_state(tls_io_instance);
111 }
112 head_pending_io = singlylinkedlist_get_head_item(tls_io_instance->pending_transmission_list);
113 if (head_pending_io != NULL)
114 {
115 PENDING_TRANSMISSION* head_message = (PENDING_TRANSMISSION*)singlylinkedlist_item_get_value(head_pending_io);
116
117 if (singlylinkedlist_remove(tls_io_instance->pending_transmission_list, head_pending_io) != 0)
118 {
119 // This particular situation is a bizarre and unrecoverable internal error
120 /* Codes_SRS_TLSIO_30_094: [ If the send process encounters an internal error or calls on_send_complete with IO_SEND_ERROR due to either failure or timeout, it shall also call on_io_error and pass in the associated on_io_error_context. ]*/
121 enter_tlsio_error_state(tls_io_instance);
122 LogError("Failed to remove message from list");
123 }
124
125 // on_send_complete is checked for NULL during PENDING_TRANSMISSION creation
126 /* Codes_SRS_TLSIO_30_095: [ If the send process fails before sending all of the bytes in an enqueued message, the tlsio_dowork shall call the message's on_send_complete along with its associated callback_context and IO_SEND_ERROR. ]*/
127 head_message->on_send_complete(head_message->callback_context, send_result);
128
129 free(head_message->bytes);
130 free(head_message);
131 result = true;
132 }
133 else
134 {
135 result = false;
136 }
137 return result;
138 }
139
140 static void internal_close(TLS_IO_INSTANCE* tls_io_instance)
141 {
142 /* Codes_SRS_TLSIO_30_009: [ The phrase "enter TLSIO_STATE_EXT_CLOSING" means the adapter shall iterate through any unsent messages in the queue and shall delete each message after calling its on_send_complete with the associated callback_context and IO_SEND_CANCELLED. ]*/
143 /* Codes_SRS_TLSIO_30_006: [ The phrase "enter TLSIO_STATE_EXT_CLOSED" means the adapter shall forcibly close any existing connections then call the on_io_close_complete function and pass the on_io_close_complete_context that was supplied in tlsio_close_async. ]*/
144 /* Codes_SRS_TLSIO_30_051: [ On success, if the underlying TLS does not support asynchronous closing, then the adapter shall enter TLSIO_STATE_EXT_CLOSED immediately after entering TLSIO_STATE_EX_CLOSING. ]*/
145 if (tls_io_instance->tlsio_state == TLSIO_STATE_OPEN)
146 {
147 if (tls_io_instance->sockRead != NULL)
148 {
149 CFReadStreamClose(tls_io_instance->sockRead);
150 }
151 if (tls_io_instance->sockWrite != NULL)
152 {
153 CFWriteStreamClose(tls_io_instance->sockWrite);
154 }
155 }
156
157 if (tls_io_instance->sockRead != NULL)
158 {
159 CFRelease(tls_io_instance->sockRead);
160 tls_io_instance->sockRead = NULL;
161 }
162
163 // If the reader is NULL then the writer should be too but let's be thorough
164 if (tls_io_instance->sockWrite != NULL)
165 {
166 CFRelease(tls_io_instance->sockWrite);
167 tls_io_instance->sockWrite = NULL;
168 }
169
170 while (process_and_destroy_head_message(tls_io_instance, IO_SEND_CANCELLED));
171 // singlylinkedlist_destroy gets called in the main destroy
172
173 tls_io_instance->on_bytes_received = NULL;
174 tls_io_instance->on_io_error = NULL;
175 tls_io_instance->on_bytes_received_context = NULL;
176 tls_io_instance->on_io_error_context = NULL;
177 tls_io_instance->tlsio_state = TLSIO_STATE_CLOSED;
178 tls_io_instance->on_open_complete = NULL;
179 tls_io_instance->on_open_complete_context = NULL;
180 }
181
182 static void tlsio_appleios_destroy(CONCRETE_IO_HANDLE tls_io)
183 {
184 if (tls_io == NULL)
185 {
186 /* Codes_SRS_TLSIO_30_020: [ If tlsio_handle is NULL, tlsio_destroy shall do nothing. ]*/
187 LogError("NULL tlsio");
188 }
189 else
190 {
191 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
192 if (tls_io_instance->tlsio_state != TLSIO_STATE_CLOSED)
193 {
194 /* Codes_SRS_TLSIO_30_022: [ If the adapter is in any state other than TLSIO_STATE_EX_CLOSED when tlsio_destroy is called, the adapter shall enter TLSIO_STATE_EX_CLOSING and then enter TLSIO_STATE_EX_CLOSED before completing the destroy process. ]*/
195 LogError("tlsio_appleios_destroy called while not in TLSIO_STATE_CLOSED.");
196 internal_close(tls_io_instance);
197 }
198 /* Codes_SRS_TLSIO_30_021: [ The tlsio_destroy shall release all allocated resources and then release tlsio_handle. ]*/
199 if (tls_io_instance->hostname != NULL)
200 {
201 CFRelease(tls_io_instance->hostname);
202 }
203
204 tlsio_options_release_resources(&tls_io_instance->options);
205
206 if (tls_io_instance->pending_transmission_list != NULL)
207 {
208 /* Pending messages were cleared in internal_close */
209 singlylinkedlist_destroy(tls_io_instance->pending_transmission_list);
210 }
211
212 free(tls_io_instance);
213 }
214 }
215
216 /* Codes_SRS_TLSIO_30_010: [ The tlsio_create shall allocate and initialize all necessary resources and return an instance of the tlsio_appleios_compact. ]*/
217 static CONCRETE_IO_HANDLE tlsio_appleios_create(void* io_create_parameters)
218 {
219 TLS_IO_INSTANCE* result;
220
221 if (io_create_parameters == NULL)
222 {
223 /* Codes_SRS_TLSIO_30_013: [ If the io_create_parameters value is NULL, tlsio_create shall log an error and return NULL. ]*/
224 LogError("NULL tls_io_config");
225 result = NULL;
226 }
227 else
228 {
229 /* Codes_SRS_TLSIO_30_012: [ The tlsio_create shall receive the connection configuration as a TLSIO_CONFIG* in io_create_parameters. ]*/
230 TLSIO_CONFIG* tls_io_config = (TLSIO_CONFIG*)io_create_parameters;
231 if (tls_io_config->hostname == NULL)
232 {
233 /* Codes_SRS_TLSIO_30_014: [ If the hostname member of io_create_parameters value is NULL, tlsio_create shall log an error and return NULL. ]*/
234 LogError("NULL tls_io_config->hostname");
235 result = NULL;
236 }
237 else
238 {
239 if (tls_io_config->port < 0 || tls_io_config->port > MAX_VALID_PORT)
240 {
241 /* Codes_SRS_TLSIO_30_015: [ If the port member of io_create_parameters value is less than 0 or greater than 0xffff, tlsio_create shall log an error and return NULL. ]*/
242 LogError("tls_io_config->port out of range");
243 result = NULL;
244 }
245 else
246 {
247 result = malloc(sizeof(TLS_IO_INSTANCE));
248 if (result == NULL)
249 {
250 /* Codes_SRS_TLSIO_30_011: [ If any resource allocation fails, tlsio_create shall return NULL. ]*/
251 LogError("malloc failed");
252 }
253 else
254 {
255 memset(result, 0, sizeof(TLS_IO_INSTANCE));
256 result->port = (uint16_t)tls_io_config->port;
257 result->tlsio_state = TLSIO_STATE_CLOSED;
258 result->sockRead = NULL;
259 result->sockWrite = NULL;
260 result->hostname = NULL;
261 result->pending_transmission_list = NULL;
262 tlsio_options_initialize(&result->options, TLSIO_OPTION_BIT_TRUSTED_CERTS);
263 /* Codes_SRS_TLSIO_30_016: [ tlsio_create shall make a copy of the hostname member of io_create_parameters to allow deletion of hostname immediately after the call. ]*/
264 if (NULL == (result->hostname = CFStringCreateWithCString(NULL, tls_io_config->hostname, kCFStringEncodingUTF8)))
265 {
266 /* Codes_SRS_TLSIO_30_011: [ If any resource allocation fails, tlsio_create shall return NULL. ]*/
267 LogError("CFStringCreateWithCString failed");
268 tlsio_appleios_destroy(result);
269 result = NULL;
270 }
271 else
272 {
273 // Create the message queue
274 result->pending_transmission_list = singlylinkedlist_create();
275 if (result->pending_transmission_list == NULL)
276 {
277 /* Codes_SRS_TLSIO_30_011: [ If any resource allocation fails, tlsio_create shall return NULL. ]*/
278 LogError("Failed singlylinkedlist_create");
279 tlsio_appleios_destroy(result);
280 result = NULL;
281 }
282 }
283 }
284 }
285 }
286 }
287
288 return (CONCRETE_IO_HANDLE)result;
289 }
290
291
292 static int tlsio_appleios_open_async(CONCRETE_IO_HANDLE tls_io,
293 ON_IO_OPEN_COMPLETE on_io_open_complete, void* on_io_open_complete_context,
294 ON_BYTES_RECEIVED on_bytes_received, void* on_bytes_received_context,
295 ON_IO_ERROR on_io_error, void* on_io_error_context)
296 {
297
298 int result;
299 if (on_io_open_complete == NULL)
300 {
301 /* Codes_SRS_TLSIO_30_031: [ If the on_io_open_complete parameter is NULL, tlsio_open shall log an error and return FAILURE. ]*/
302 LogError("Required parameter on_io_open_complete is NULL");
303 result = MU_FAILURE;
304 }
305 else
306 {
307 if (tls_io == NULL)
308 {
309 /* Codes_SRS_TLSIO_30_030: [ If the tlsio_handle parameter is NULL, tlsio_open shall log an error and return FAILURE. ]*/
310 result = MU_FAILURE;
311 LogError("NULL tlsio");
312 }
313 else
314 {
315 if (on_bytes_received == NULL)
316 {
317 /* Codes_SRS_TLSIO_30_032: [ If the on_bytes_received parameter is NULL, tlsio_open shall log an error and return FAILURE. ]*/
318 LogError("Required parameter on_bytes_received is NULL");
319 result = MU_FAILURE;
320 }
321 else
322 {
323 if (on_io_error == NULL)
324 {
325 /* Codes_SRS_TLSIO_30_033: [ If the on_io_error parameter is NULL, tlsio_open shall log an error and return FAILURE. ]*/
326 LogError("Required parameter on_io_error is NULL");
327 result = MU_FAILURE;
328 }
329 else
330 {
331 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
332
333 if (tls_io_instance->tlsio_state != TLSIO_STATE_CLOSED)
334 {
335 /* Codes_SRS_TLSIO_30_037: [ If the adapter is in any state other than TLSIO_STATE_EXT_CLOSED when tlsio_open is called, it shall log an error, and return FAILURE. ]*/
336 LogError("Invalid tlsio_state. Expected state is TLSIO_STATE_CLOSED.");
337 result = MU_FAILURE;
338 }
339 else
340 {
341 tls_io_instance->no_messages_yet_sent = true;
342 /* Codes_SRS_TLSIO_30_034: [ The tlsio_open shall store the provided on_bytes_received, on_bytes_received_context, on_io_error, on_io_error_context, on_io_open_complete, and on_io_open_complete_context parameters for later use as specified and tested per other line entries in this document. ]*/
343 tls_io_instance->on_bytes_received = on_bytes_received;
344 tls_io_instance->on_bytes_received_context = on_bytes_received_context;
345
346 tls_io_instance->on_io_error = on_io_error;
347 tls_io_instance->on_io_error_context = on_io_error_context;
348
349 tls_io_instance->on_open_complete = on_io_open_complete;
350 tls_io_instance->on_open_complete_context = on_io_open_complete_context;
351
352 /* Codes_SRS_TLSIO_30_035: [ On tlsio_open success the adapter shall enter TLSIO_STATE_EX_OPENING and return 0. ]*/
353 // All the real work happens in dowork
354 tls_io_instance->tlsio_state = TLSIO_STATE_OPENING_WAITING_DNS;
355 result = 0;
356 }
357 }
358 }
359 }
360 /* Codes_SRS_TLSIO_30_039: [ On failure, tlsio_open_async shall not call on_io_open_complete. ]*/
361 }
362
363 return result;
364 }
365
366 // This implementation does not have asynchronous close, but uses the _async name for consistencty with the spec
367 static int tlsio_appleios_close_async(CONCRETE_IO_HANDLE tls_io, ON_IO_CLOSE_COMPLETE on_io_close_complete, void* callback_context)
368 {
369 int result;
370
371 if (tls_io == NULL)
372 {
373 /* Codes_SRS_TLSIO_30_050: [ If the tlsio_handle parameter is NULL, tlsio_appleios_close_async shall log an error and return FAILURE. ]*/
374 LogError("NULL tlsio");
375 result = MU_FAILURE;
376 }
377 else
378 {
379 if (on_io_close_complete == NULL)
380 {
381 /* Codes_SRS_TLSIO_30_055: [ If the on_io_close_complete parameter is NULL, tlsio_appleios_close_async shall log an error and return FAILURE. ]*/
382 LogError("NULL on_io_close_complete");
383 result = MU_FAILURE;
384 }
385 else
386 {
387 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
388
389 if (tls_io_instance->tlsio_state != TLSIO_STATE_OPEN &&
390 tls_io_instance->tlsio_state != TLSIO_STATE_ERROR)
391 {
392 /* Codes_SRS_TLSIO_30_053: [ If the adapter is in any state other than TLSIO_STATE_EXT_OPEN or TLSIO_STATE_EXT_ERROR then tlsio_close_async shall log that tlsio_close_async has been called and then continue normally. ]*/
393 // LogInfo rather than LogError because this is an unusual but not erroneous situation
394 LogInfo("tlsio_appleios_close has been called when in neither TLSIO_STATE_OPEN nor TLSIO_STATE_ERROR.");
395 }
396
397 if (is_an_opening_state(tls_io_instance->tlsio_state))
398 {
399 /* Codes_SRS_TLSIO_30_057: [ On success, if the adapter is in TLSIO_STATE_EXT_OPENING, it shall call on_io_open_complete with the on_io_open_complete_context supplied in tlsio_open_async and IO_OPEN_CANCELLED. This callback shall be made before changing the internal state of the adapter. ]*/
400 tls_io_instance->on_open_complete(tls_io_instance->on_open_complete_context, IO_OPEN_CANCELLED);
401 }
402 // This adapter does not support asynchronous closing
403 /* Codes_SRS_TLSIO_30_056: [ On success the adapter shall enter TLSIO_STATE_EX_CLOSING. ]*/
404 /* Codes_SRS_TLSIO_30_051: [ On success, if the underlying TLS does not support asynchronous closing, then the adapter shall enter TLSIO_STATE_EX_CLOSED immediately after entering TLSIO_STATE_EX_CLOSING. ]*/
405 /* Codes_SRS_TLSIO_30_052: [ On success tlsio_close shall return 0. ]*/
406 internal_close(tls_io_instance);
407 on_io_close_complete(callback_context);
408 result = 0;
409 }
410 }
411 /* Codes_SRS_TLSIO_30_054: [ On failure, the adapter shall not call on_io_close_complete. ]*/
412
413 return result;
414 }
415
416 static void dowork_read(TLS_IO_INSTANCE* tls_io_instance)
417 {
418 // TRANSFER_BUFFER_SIZE is not very important because if the message is bigger
419 // then the framework just calls dowork repeatedly until it gets everything. So
420 // a bigger buffer would just use memory without buying anything.
421 // Putting this buffer in a small function also allows it to exist on the stack
422 // rather than adding to heap fragmentation.
423 uint8_t buffer[TLSIO_RECEIVE_BUFFER_SIZE];
424 CFIndex rcv_bytes;
425
426 if (tls_io_instance->tlsio_state == TLSIO_STATE_OPEN)
427 {
428 CFStreamStatus read_status = CFReadStreamGetStatus(tls_io_instance->sockRead);
429 if (read_status == kCFStreamStatusAtEnd || read_status == kCFStreamStatusError)
430 {
431 enter_tlsio_error_state(tls_io_instance);
432 }
433 else
434 {
435 while (tls_io_instance->tlsio_state == TLSIO_STATE_OPEN && CFReadStreamHasBytesAvailable(tls_io_instance->sockRead))
436 {
437 rcv_bytes = CFReadStreamRead(tls_io_instance->sockRead, buffer, (CFIndex)(sizeof(buffer)));
438
439 if (rcv_bytes > 0)
440 {
441 // tls_io_instance->on_bytes_received was already checked for NULL
442 // in the call to tlsio_appleios_open_async
443 /* Codes_SRS_TLSIO_30_100: [ As long as the TLS connection is able to provide received data, tlsio_dowork shall repeatedly read this data and call on_bytes_received with the pointer to the buffer containing the data, the number of bytes received, and the on_bytes_received_context. ]*/
444 tls_io_instance->on_bytes_received(tls_io_instance->on_bytes_received_context, buffer, rcv_bytes);
445 }
446 else if (rcv_bytes < 0)
447 {
448 LogError("Communications error while reading");
449 enter_tlsio_error_state(tls_io_instance);
450 }
451 /* Codes_SRS_TLSIO_30_102: [ If the TLS connection receives no data then tlsio_dowork shall not call the on_bytes_received callback. ]*/
452 }
453 }
454 }
455 }
456
457 static void dowork_send(TLS_IO_INSTANCE* tls_io_instance)
458 {
459 LIST_ITEM_HANDLE first_pending_io = singlylinkedlist_get_head_item(tls_io_instance->pending_transmission_list);
460 if (first_pending_io != NULL)
461 {
462 PENDING_TRANSMISSION* pending_message = (PENDING_TRANSMISSION*)singlylinkedlist_item_get_value(first_pending_io);
463 uint8_t* buffer = ((uint8_t*)pending_message->bytes) + pending_message->size - pending_message->unsent_size;
464
465 // Check to see if the socket will not block
466 if (CFWriteStreamCanAcceptBytes(tls_io_instance->sockWrite))
467 {
468 CFIndex write_result = CFWriteStreamWrite(tls_io_instance->sockWrite, buffer, pending_message->unsent_size);
469 if (write_result >= 0)
470 {
471 pending_message->unsent_size -= write_result;
472 if (pending_message->unsent_size == 0)
473 {
474 /* Codes_SRS_TLSIO_30_091: [ If tlsio_appleios_compact_dowork is able to send all the bytes in an enqueued message, it shall call the messages's on_send_complete along with its associated callback_context and IO_SEND_OK. ]*/
475 // The whole message has been sent successfully
476 process_and_destroy_head_message(tls_io_instance, IO_SEND_OK);
477 }
478 else
479 {
480 /* Codes_SRS_TLSIO_30_093: [ If the TLS connection was not able to send an entire enqueued message at once, subsequent calls to tlsio_dowork shall continue to send the remaining bytes. ]*/
481 // Repeat the send on the next pass with the rest of the message
482 // This empty else compiles to nothing but helps readability
483 }
484 }
485 else
486 {
487 // The write returned non-success. It may be busy, or it may be broken
488 CFErrorRef write_error = CFWriteStreamCopyError(tls_io_instance->sockWrite);
489 if (write_error != NULL && CFErrorGetCode(write_error) != errSSLWouldBlock)
490 {
491 /* Codes_SRS_TLSIO_30_002: [ The phrase "destroy the failed message" means that the adapter shall remove the message from the queue and destroy it after calling the message's on_send_complete along with its associated callback_context and IO_SEND_ERROR. ]*/
492 /* Codes_SRS_TLSIO_30_005: [ When the adapter enters TLSIO_STATE_EXT_ERROR it shall call the on_io_error function and pass the on_io_error_context that were supplied in tlsio_open . ]*/
493 /* Codes_SRS_TLSIO_30_095: [ If the send process fails before sending all of the bytes in an enqueued message, tlsio_dowork shall destroy the failed message and enter TLSIO_STATE_EX_ERROR. ]*/
494 // This is an unexpected error, and we need to bail out. Probably lost internet connection.
495 LogInfo("Hard error from CFWriteStreamWrite: %ld", CFErrorGetCode(write_error));
496 process_and_destroy_head_message(tls_io_instance, IO_SEND_ERROR);
497 CFRelease(write_error);
498 }
499 else
500 {
501 // The errSSLWouldBlock is defined as a recoverable error and should just be retried
502 LogInfo("errSSLWouldBlock on write");
503 if (write_error != NULL)
504 {
505 CFRelease(write_error);
506 }
507 }
508 }
509 }
510 }
511 else
512 {
513 /* Codes_SRS_TLSIO_30_096: [ If there are no enqueued messages available, tlsio_appleios_compact_dowork shall do nothing. ]*/
514 }
515 }
516
517 static void dowork_poll_dns(TLS_IO_INSTANCE* tls_io_instance)
518 {
519 // Sockets on iOS do DNS lookup during open - just change the status
520 tls_io_instance->tlsio_state = TLSIO_STATE_OPENING_WAITING_SOCKET;
521 }
522
523 static void dowork_poll_socket(TLS_IO_INSTANCE* tls_io_instance)
524 {
525 // This will pretty much only fail if we run out of memory
526 CFStreamCreatePairWithSocketToHost(NULL, tls_io_instance->hostname, tls_io_instance->port, &tls_io_instance->sockRead, &tls_io_instance->sockWrite);
527 if (tls_io_instance->sockRead != NULL && tls_io_instance->sockWrite != NULL)
528 {
529
530 CFStringRef keys[1] = {kCFStreamPropertySocketSecurityLevel};
531 CFStringRef values[1] = {kCFStreamSocketSecurityLevelNegotiatedSSL};
532
533 CFDictionaryRef tls_io_dictionary = CFDictionaryCreate(NULL , (void *)keys , (void *)values , 1, NULL , NULL);
534
535 if (CFReadStreamSetProperty(tls_io_instance->sockRead, kCFStreamPropertySSLSettings, tls_io_dictionary))
536
537 {
538 tls_io_instance->tlsio_state = TLSIO_STATE_OPENING_WAITING_SSL;
539 }
540 else
541 {
542 LogError("Failed to set socket properties");
543 enter_open_error_state(tls_io_instance);
544 }
545
546 CFRelease(tls_io_dictionary);
547 }
548 else
549 {
550 LogError("Unable to create socket pair");
551 enter_open_error_state(tls_io_instance);
552 }
553 }
554
555 static void dowork_poll_open_ssl(TLS_IO_INSTANCE* tls_io_instance)
556 {
557 if (CFReadStreamOpen(tls_io_instance->sockRead) && CFWriteStreamOpen(tls_io_instance->sockWrite))
558 {
559 /* Codes_SRS_TLSIO_30_080: [ The tlsio_dowork shall establish a TLS connection using the hostName and port provided during tlsio_open. ]*/
560 // Connect succeeded
561 tls_io_instance->tlsio_state = TLSIO_STATE_OPEN;
562 /* Codes_SRS_TLSIO_30_007: [ The phrase "enter TLSIO_STATE_EXT_OPEN" means the adapter shall call the on_io_open_complete function and pass IO_OPEN_OK and the on_io_open_complete_context that was supplied in tlsio_open . ]*/
563 /* Codes_SRS_TLSIO_30_083: [ If tlsio_dowork successfully opens the TLS connection it shall enter TLSIO_STATE_EX_OPEN. ]*/
564 tls_io_instance->on_open_complete(tls_io_instance->on_open_complete_context, IO_OPEN_OK);
565 }
566 else
567 {
568 CFErrorRef readError = CFReadStreamCopyError(tls_io_instance->sockRead);
569 if (readError != NULL)
570 {
571 CFErrorRef writeError = CFWriteStreamCopyError(tls_io_instance->sockWrite);
572 if (writeError != NULL)
573 {
574 LogInfo("Error opening streams - read error=%ld;write error=%ld", CFErrorGetCode(readError), CFErrorGetCode(writeError));
575 CFRelease(writeError);
576 }
577 else
578 {
579 LogInfo("Error opening streams - read error=%ld", CFErrorGetCode(readError));
580 }
581 CFRelease(readError);
582 }
583 enter_open_error_state(tls_io_instance);
584 }
585 }
586
587 static void tlsio_appleios_dowork(CONCRETE_IO_HANDLE tls_io)
588 {
589 if (tls_io == NULL)
590 {
591 /* Codes_SRS_TLSIO_30_070: [ If the tlsio_handle parameter is NULL, tlsio_dowork shall do nothing except log an error. ]*/
592 LogError("NULL tlsio");
593 }
594 else
595 {
596 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
597
598 // This switch statement handles all of the state transitions during the opening process
599 switch (tls_io_instance->tlsio_state)
600 {
601 case TLSIO_STATE_CLOSED:
602 /* Codes_SRS_TLSIO_30_075: [ If the adapter is in TLSIO_STATE_EXT_CLOSED then tlsio_dowork shall do nothing. ]*/
603 // Waiting to be opened, nothing to do
604 break;
605 case TLSIO_STATE_OPENING_WAITING_DNS:
606 dowork_poll_dns(tls_io_instance);
607 break;
608 case TLSIO_STATE_OPENING_WAITING_SOCKET:
609 dowork_poll_socket(tls_io_instance);
610 break;
611 case TLSIO_STATE_OPENING_WAITING_SSL:
612 dowork_poll_open_ssl(tls_io_instance);
613 break;
614 case TLSIO_STATE_OPEN:
615 dowork_read(tls_io_instance);
616 dowork_send(tls_io_instance);
617 break;
618 case TLSIO_STATE_ERROR:
619 /* Codes_SRS_TLSIO_30_071: [ If the adapter is in TLSIO_STATE_EXT_ERROR then tlsio_dowork shall do nothing. ]*/
620 // There's nothing valid to do here but wait to be retried
621 break;
622 default:
623 LogError("Unexpected internal tlsio state");
624 break;
625 }
626 }
627 }
628
629 static int tlsio_appleios_setoption(CONCRETE_IO_HANDLE tls_io, const char* optionName, const void* value)
630 {
631 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
632 /* Codes_SRS_TLSIO_30_120: [ If the tlsio_handle parameter is NULL, tlsio_appleios_setoption shall do nothing except log an error and return FAILURE. ]*/
633 int result;
634 if (tls_io_instance == NULL)
635 {
636 LogError("NULL tlsio");
637 result = MU_FAILURE;
638 }
639 else
640 {
641 /* Codes_SRS_TLSIO_30_121: [ If the optionName parameter is NULL, tlsio_appleios_setoption shall do nothing except log an error and return FAILURE. ]*/
642 /* Codes_SRS_TLSIO_30_122: [ If the value parameter is NULL, tlsio_appleios_setoption shall do nothing except log an error and return FAILURE. ]*/
643 /* Codes_SRS_TLSIO_OPENSSL_COMPACT_30_520 [ The tlsio_setoption shall do nothing and return FAILURE. ]*/
644 TLSIO_OPTIONS_RESULT options_result = tlsio_options_set(&tls_io_instance->options, optionName, value);
645 if (options_result != TLSIO_OPTIONS_RESULT_SUCCESS)
646 {
647 LogError("Failed tlsio_options_set");
648 result = MU_FAILURE;
649 }
650 else
651 {
652 result = 0;
653 }
654 }
655 return result;
656 }
657
658 static int tlsio_appleios_send_async(CONCRETE_IO_HANDLE tls_io, const void* buffer, size_t size, ON_SEND_COMPLETE on_send_complete, void* callback_context)
659 {
660 int result;
661 if (on_send_complete == NULL || tls_io == NULL || buffer == NULL || size == 0 || on_send_complete == NULL)
662 {
663 /* Codes_SRS_TLSIO_30_062: [ If the on_send_complete is NULL, tlsio_appleios_compact_send shall log the error and return FAILURE. ]*/
664 result = MU_FAILURE;
665 LogError("Invalid parameter specified: tls_io: %p, buffer: %p, size: %lu, on_send_complete: %p", tls_io, buffer, (unsigned long)size, on_send_complete);
666 }
667 else
668 {
669 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
670 if (tls_io_instance->tlsio_state != TLSIO_STATE_OPEN)
671 {
672 /* Codes_SRS_TLSIO_30_060: [ If the tlsio_handle parameter is NULL, tlsio_appleios_compact_send shall log an error and return FAILURE. ]*/
673 /* Codes_SRS_TLSIO_30_065: [ If tlsio_appleios_compact_open has not been called or the opening process has not been completed, tlsio_appleios_compact_send shall log an error and return FAILURE. ]*/
674 result = MU_FAILURE;
675 LogError("tlsio_appleios_send_async without a prior successful open");
676 }
677 else
678 {
679 PENDING_TRANSMISSION* pending_transmission = (PENDING_TRANSMISSION*)malloc(sizeof(PENDING_TRANSMISSION));
680 if (pending_transmission == NULL)
681 {
682 /* Codes_SRS_TLSIO_30_064: [ If the supplied message cannot be enqueued for transmission, tlsio_appleios_compact_send shall log an error and return FAILURE. ]*/
683 result = MU_FAILURE;
684 LogError("malloc failed");
685 }
686 else
687 {
688 // For AMQP and MQTT over websockets, the interaction of the IoT Hub and the
689 // Apple TLS requires hacking the websocket upgrade header with a
690 // "iothub-no-client-cert=true" parameter to avoid a TLS hang.
691 bool add_no_cert_url_parameter = false;
692 if (tls_io_instance->no_messages_yet_sent)
693 {
694 tls_io_instance->no_messages_yet_sent = false;
695 if (strncmp((const char*)buffer, WEBSOCKET_HEADER_START, WEBSOCKET_HEADER_START_SIZE) == 0)
696 {
697 add_no_cert_url_parameter = true;
698 size = safe_add_size_t(size, WEBSOCKET_HEADER_NO_CERT_PARAM_SIZE);
699 }
700 }
701
702 /* Codes_SRS_TLSIO_30_063: [ The tlsio_appleios_compact_send shall enqueue for transmission the on_send_complete, the callback_context, the size, and the contents of buffer. ]*/
703 if (size == SIZE_MAX ||
704 (pending_transmission->bytes = (unsigned char*)malloc(size)) == NULL)
705 {
706 /* Codes_SRS_TLSIO_30_064: [ If the supplied message cannot be enqueued for transmission, tlsio_appleios_compact_send shall log an error and return FAILURE. ]*/
707 LogError("malloc failed, size:%zu", size);
708 free(pending_transmission);
709 result = MU_FAILURE;
710 }
711 else
712 {
713 pending_transmission->size = size;
714 pending_transmission->unsent_size = size;
715 pending_transmission->on_send_complete = on_send_complete;
716 pending_transmission->callback_context = callback_context;
717 if (add_no_cert_url_parameter)
718 {
719 // Insert the WEBSOCKET_HEADER_NO_CERT_PARAM after the url
720 (void)memcpy(pending_transmission->bytes, WEBSOCKET_HEADER_START, WEBSOCKET_HEADER_START_SIZE);
721 (void)memcpy(pending_transmission->bytes + WEBSOCKET_HEADER_START_SIZE, WEBSOCKET_HEADER_NO_CERT_PARAM, WEBSOCKET_HEADER_NO_CERT_PARAM_SIZE);
722 (void)memcpy(pending_transmission->bytes + WEBSOCKET_HEADER_START_SIZE + WEBSOCKET_HEADER_NO_CERT_PARAM_SIZE, buffer + WEBSOCKET_HEADER_START_SIZE, size - WEBSOCKET_HEADER_START_SIZE - WEBSOCKET_HEADER_NO_CERT_PARAM_SIZE);
723 }
724 else
725 {
726 (void)memcpy(pending_transmission->bytes, buffer, size);
727 }
728
729 if (singlylinkedlist_add(tls_io_instance->pending_transmission_list, pending_transmission) == NULL)
730 {
731 /* Codes_SRS_TLSIO_30_064: [ If the supplied message cannot be enqueued for transmission, tlsio_appleios_compact_send shall log an error and return FAILURE. ]*/
732 LogError("Unable to add socket to pending list.");
733 free(pending_transmission->bytes);
734 free(pending_transmission);
735 result = MU_FAILURE;
736 }
737 else
738 {
739 /* Codes_SRS_TLSIO_30_063: [ On success, tlsio_send shall enqueue for transmission the on_send_complete , the callback_context , the size , and the contents of buffer and then return 0. ]*/
740 result = 0;
741 dowork_send(tls_io_instance);
742 }
743 }
744 }
745 }
746 /* Codes_SRS_TLSIO_30_066: [ On failure, on_send_complete shall not be called. ]*/
747 }
748 return result;
749 }
750
751 /* Codes_SRS_TLSIO_APPLEIOS_COMPACT_30_560: [ The tlsio_retrieveoptions shall do nothing and return NULL. ]*/
752 static OPTIONHANDLER_HANDLE tlsio_appleios_retrieveoptions(CONCRETE_IO_HANDLE tls_io)
753 {
754 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
755 /* Codes_SRS_TLSIO_30_160: [ If the tlsio_handle parameter is NULL, tlsio_appleios_retrieveoptions shall do nothing except log an error and return FAILURE. ]*/
756 OPTIONHANDLER_HANDLE result;
757 if (tls_io_instance == NULL)
758 {
759 LogError("NULL tlsio");
760 result = NULL;
761 }
762 else
763 {
764 result = tlsio_options_retrieve_options(&tls_io_instance->options, tlsio_appleios_setoption);
765 }
766 return result;
767 }
768
769 /* Codes_SRS_TLSIO_30_008: [ The tlsio_get_interface_description shall return the VTable IO_INTERFACE_DESCRIPTION. ]*/
770 static const IO_INTERFACE_DESCRIPTION tlsio_appleios_interface_description =
771 {
772 tlsio_appleios_retrieveoptions,
773 tlsio_appleios_create,
774 tlsio_appleios_destroy,
775 tlsio_appleios_open_async,
776 tlsio_appleios_close_async,
777 tlsio_appleios_send_async,
778 tlsio_appleios_dowork,
779 tlsio_appleios_setoption
780 };
781
782 /* Codes_SRS_TLSIO_30_001: [ The tlsio_appleios_compact shall implement and export all the Concrete functions in the VTable IO_INTERFACE_DESCRIPTION defined in the xio.h. ]*/
783 const IO_INTERFACE_DESCRIPTION* tlsio_appleios_get_interface_description(void)
784 {
785 return &tlsio_appleios_interface_description;
786 }
787
788 const IO_INTERFACE_DESCRIPTION* socketio_get_interface_description(void)
789 {
790 return NULL;
791 }
792