static int test_GetSupportedCiphers(SSLContextRef ssl) { size_t max_ciphers = 0; int fail=1; SSLCipherSuite *ciphers = NULL; require_noerr(SSLGetNumberSupportedCiphers(ssl, &max_ciphers), out); size_t size = max_ciphers * sizeof (SSLCipherSuite); ciphers = (SSLCipherSuite *) malloc(size); require_string(ciphers, out, "out of memory"); memset(ciphers, 0xff, size); size_t num_ciphers = max_ciphers; require_noerr(SSLGetSupportedCiphers(ssl, ciphers, &num_ciphers), out); for (size_t i = 0; i < num_ciphers; i++) { require(ciphers[i]!=(SSLCipherSuite)(-1), out); } /* Success! */ fail=0; out: if(ciphers) free(ciphers); return fail; }
//============================================================================== //! //============================================================================== inline optional<lang_id> get_locale(cref value, string_ref const expected_type) { auto const type = require_string(value[field_stringtype]); if (type != expected_type) { return optional<lang_id> {}; } return get_locale(value); }
inline string_ref get_id_string(cref json) { auto const str = require_string(json[field_id]); if (str.length() < 1) { BK_TODO_FAIL(); } return str; }
//============================================================================== //! //============================================================================== inline optional<lang_id> get_locale(cref value) { auto const lang = require_string(value[field_language]); auto const size = lang.size(); if (size == 2) { return BK_MAKE_LANG_CODE2(lang[0], lang[1]); } else if (size == 3) { return BK_MAKE_LANG_CODE3(lang[0], lang[1], lang[2]); } return optional<lang_id> {}; }
int read_edit_spec(void) { // // I wanted to do just // // int count = fscanf( edits, "%d: `%[^`]` -> `%[^`]`\n", &edit_offset, from_string, to_string ); // // but fscanf has some weird prohibition against accepting // zero-length fields :( so we just do it by hand: /// char buf[ 4096 ]; char* p = buf; int i = fgetc( edits ); if (i == EOF) return FALSE; do { *p++ = i; } while (isdigit( i = fgetc( edits ))); *p = '\0'; edit_offset = atoi( buf ); require_char( ':', i ); require_string( " `" ); p = from_string; while (( i = fgetc( edits )) != '`') { require_char(i,i); *p++ = i; } *p = '\0'; require_string( " -> `" ); p = to_string; while (( i = fgetc( edits )) != '`') { require_char(i,i); *p++ = i; } *p = '\0'; require_string( "\n" ); return TRUE; }
static int test_GetEnabledCiphers(SSLContextRef ssl) { size_t max_ciphers = 0; int fail=1; SSLCipherSuite *ciphers = NULL; OSStatus err; err=SSLSetIOFuncs(ssl, &SocketRead, &SocketWrite); err=SSLSetConnection(ssl, NULL); err=SSLHandshake(ssl); require_noerr(SSLGetNumberEnabledCiphers(ssl, &max_ciphers), out); size_t size = max_ciphers * sizeof (SSLCipherSuite); ciphers = (SSLCipherSuite *) malloc(size); require_string(ciphers, out, "out of memory"); memset(ciphers, 0xff, size); size_t num_ciphers = max_ciphers; require_noerr(SSLGetEnabledCiphers(ssl, ciphers, &num_ciphers), out); for (size_t i = 0; i < num_ciphers; i++) { char csname[256]; snprintf(csname, 256, "(%04x) %s", ciphers[i], ciphersuite_name(ciphers[i])); /* Uncomment the next line if you want to list the default enabled ciphers */ //printf("%s\n", csname); require_string(allowed_default_ciphers(ciphers[i]), out, csname); } /* Success! */ fail=0; out: if(ciphers) free(ciphers); return fail; }
int HKSecureSocketSend( int sockfd, void *buf, size_t len, security_session_t *session) { OSStatus err = kNoErr; uint8_t* encryptedData = NULL; ssize_t sentLength = 0; uint64_t encryptedDataLen; encryptedData = malloc(len + crypto_aead_chacha20poly1305_ABYTES + 4); require_action(encryptedData, exit, err = kNoMemoryErr); *(int *)encryptedData = len; err = crypto_aead_chacha20poly1305_encrypt(encryptedData+4, &encryptedDataLen, (uint8_t *)buf, len, (const uint8_t *)encryptedData, 4, NULL, (uint8_t *)(&session->outputSeqNo), (const unsigned char *)session->OutputKey); session->outputSeqNo++; require_noerr_string(err, exit, "crypto_aead_chacha20poly1305_encrypt failed"); require_string(encryptedDataLen - crypto_aead_chacha20poly1305_ABYTES == len, exit, "encryptedDataLen is not properly set"); err = SocketSend( sockfd, encryptedData, encryptedDataLen + 4 ); require_noerr( err, exit ); exit: if(encryptedData) free(encryptedData); return sentLength; }
int tool_cmd_reset(int argc, char *argv[]) { int ret = 0; int c; int timeout = 10 * 1000; DBusConnection* connection = NULL; DBusMessage *message = NULL; DBusMessage *reply = NULL; DBusError error; dbus_error_init(&error); while (1) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"timeout", required_argument, 0, 't'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long(argc, argv, "ht:", long_options, &option_index); if (c == -1) break; switch (c) { case 'h': print_arg_list_help(reset_option_list, argv[0], reset_cmd_syntax); ret = ERRORCODE_HELP; goto bail; case 't': timeout = strtol(optarg, NULL, 0); break; } } if (optind < argc) { fprintf(stderr, "%s: error: Unexpected extra argument: \"%s\"\n", argv[0], argv[optind]); ret = ERRORCODE_BADARG; goto bail; } if (gInterfaceName[0] == 0) { fprintf(stderr, "%s: error: No WPAN interface set (use the `cd` command, or the `-I` argument for `wpanctl`).\n", argv[0]); ret = ERRORCODE_BADARG; goto bail; } connection = dbus_bus_get(DBUS_BUS_STARTER, &error); if (!connection) { dbus_error_free(&error); dbus_error_init(&error); connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); } require_string(connection != NULL, bail, error.message); { DBusMessageIter iter; DBusMessageIter list_iter; char path[DBUS_MAXIMUM_NAME_LENGTH+1]; char interface_dbus_name[DBUS_MAXIMUM_NAME_LENGTH+1]; ret = lookup_dbus_name_from_interface(interface_dbus_name, gInterfaceName); if (ret != 0) { goto bail; } snprintf(path, sizeof(path), "%s/%s", WPANTUND_DBUS_PATH, gInterfaceName); message = dbus_message_new_method_call( interface_dbus_name, path, WPANTUND_DBUS_APIv1_INTERFACE, WPANTUND_IF_CMD_RESET ); fprintf(stderr, "Resetting NCP. . .\n"); reply = dbus_connection_send_with_reply_and_block( connection, message, timeout, &error ); if (!reply) { fprintf(stderr, "%s: error: %s\n", argv[0], error.message); ret = ERRORCODE_TIMEOUT; goto bail; } dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID ); if (ret == 6) ret = 0; } bail: if (connection) dbus_connection_unref(connection); if (message) dbus_message_unref(message); if (reply) dbus_message_unref(reply); dbus_error_free(&error); return ret; }
void init_platform_bootloader( void ) { uint32_t BootNvmInfo; OSStatus err; MicoGpioInitialize( BOOT_SEL, INPUT_PULL_UP ); MicoGpioInitialize( MFG_SEL, INPUT_PULL_UP ); #ifdef MICO_ATE_START_ADDRESS MicoGpioInitialize( EasyLink_BUTTON, INPUT_PULL_UP ); #endif /* Check USB-HOST is inserted */ err = MicoGpioInitialize( (mico_gpio_t)USB_DETECT, INPUT_PULL_DOWN ); require_noerr(err, exit); mico_thread_msleep_no_os(2); require_string( MicoGpioInputGet( (mico_gpio_t)USB_DETECT ) == true, exit, "USB device is not inserted" ); //platform_log("USB device inserted"); if( HardwareInit(DEV_ID_USB) ){ FolderOpenByNum(&RootFolder, NULL, 1); FileBrowse(RootFolder.FsContext); } /* Check last firmware update is success or not. */ NvmRead(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4); if(false == UpgradeFileFound) { if(BootNvmInfo == UPGRADE_SUCC_MAGIC) { /* * boot up check for the last time */ platform_log("[UPGRADE]:upgrade successful completely"); } else if(BootNvmInfo == (uint32_t)UPGRADE_ERRNO_NOERR) { platform_log("[UPGRADE]:no upgrade, boot normallly"); } else if(BootNvmInfo == (uint32_t)UPGRADE_ERRNO_CODBUFDAT) { platform_log("[UPGRADE]:upgrade successful partly, data fail"); } else { platform_log("[UPGRADE]:upgrade error, errno = %d", (int32_t)BootNvmInfo); } } else { if(BootNvmInfo == (uint32_t)UPGRADE_ERRNO_NOERR) { platform_log("[UPGRADE]:found upgrade ball, prepare to boot upgrade"); BootNvmInfo = UPGRADE_REQT_MAGIC; NvmWrite(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4); //if you want PORRESET to reset GPIO only,uncomment it //GpioPorSysReset(GPIO_RSTSRC_PORREST); NVIC_SystemReset(); while(1);;; } else if(BootNvmInfo == UPGRADE_SUCC_MAGIC) { BootNvmInfo = (uint32_t)UPGRADE_ERRNO_NOERR; NvmWrite(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4); platform_log("[UPGRADE]:found upgrade ball file for the last time, re-plugin/out, if you want to upgrade again"); } else { platform_log("[UPGRADE]:upgrade error, errno = %d", (int32_t)BootNvmInfo); if( BootNvmInfo == -9 ) { platform_log("[UPGRADE]:Same file, no need to update"); goto exit; } BootNvmInfo = (uint32_t)UPGRADE_ERRNO_NOERR; NvmWrite(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4); BootNvmInfo = UPGRADE_REQT_MAGIC; NvmWrite(UPGRADE_NVM_ADDR, (uint8_t*)&BootNvmInfo, 4); //if you want PORRESET to reset GPIO only,uncomment it //GpioPorSysReset(GPIO_RSTSRC_PORREST); NVIC_SystemReset(); } } exit: return; }
static OSStatus securetransport(ssl_test_handle * ssl) { OSStatus ortn; SSLContextRef ctx = ssl->st; SecTrustRef trust = NULL; bool got_server_auth = false, got_client_cert_req = false; ortn = SSLHandshake(ctx); //fprintf(stderr, "Fell out of SSLHandshake with error: %ld\n", (long)ortn); size_t sent, received; const char *r=request; size_t l=sizeof(request); do { ortn = SSLWrite(ctx, r, l, &sent); if(ortn == errSSLWouldBlock) { r+=sent; l-=sent; } if (ortn == errSSLServerAuthCompleted) { require_string(!got_server_auth, out, "second server auth"); require_string(!got_client_cert_req, out, "got client cert req before server auth"); got_server_auth = true; require_string(!trust, out, "Got errSSLServerAuthCompleted twice?"); /* verify peer cert chain */ require_noerr(SSLCopyPeerTrust(ctx, &trust), out); SecTrustResultType trust_result = 0; /* this won't verify without setting up a trusted anchor */ require_noerr(SecTrustEvaluate(trust, &trust_result), out); } } while(ortn == errSSLWouldBlock || ortn == errSSLServerAuthCompleted); //fprintf(stderr, "\nHTTP Request Sent\n"); require_noerr_action_quiet(ortn, out, printf("SSLWrite failed with err %ld\n", (long)ortn)); require_string(got_server_auth, out, "never got server auth"); do { ortn = SSLRead(ctx, reply, sizeof(reply)-1, &received); //fprintf(stderr, "r"); usleep(1000); } while(ortn == errSSLWouldBlock); //fprintf(stderr, "\n"); require_noerr_action_quiet(ortn, out, printf("SSLRead failed with err %ld\n", (long)ortn)); reply[received]=0; //fprintf(stderr, "HTTP reply:\n"); //fprintf(stderr, "%s\n",reply); out: SSLClose(ctx); SSLDisposeContext(ctx); if (trust) CFRelease(trust); return ortn; }
int main(int argc, char **argv) { safe_mem_init(); xmpp_ctx_t *ctx; xmpp_conn_t *conn; xmpp_log_t *log; char *jid = NULL, *pass = NULL, *host = NULL; if (argc > 1) { jid = argv[1]; } if (argc > 2) { pass = argv[2]; } if (argc > 3) { host = argv[3]; } jid = require_string("输入账号", 64, jid); pass = require_string("输入密码", 64, pass); host = require_string("输入主机", 128, host); xmpp_initialize(); if (test_thread(argc, argv)) { printf("test thread ok.\n"); } else { printf("test thread fail.\n"); } log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG); ctx = xmpp_ctx_new(NULL, log); conn = xmpp_conn_new(ctx); xmpp_conn_set_jid(conn, jid); xmpp_conn_set_pass(conn, pass); //// 连接服务器 xmpp_connect_client(conn, host, 0, conn_handler, ctx); int err = pthread_create(&xmpp_thread, NULL, xmpp_routine, ctx); if (err != 0) { printf("can't create xmpp thread: %s\n", strerror(err)); return 1; } pthread_join(xmpp_thread, NULL); pthread_join(console_thread, NULL); xmpp_conn_release(conn); xmpp_ctx_free(ctx); xmpp_shutdown(); safe_mem_free(jid); safe_mem_free(pass); if (host) { safe_mem_free(host); } safe_mem_check(memcb, NULL); _CrtDumpMemoryLeaks(); printf("按任意按键关闭.."); getchar(); return 0; };
int tool_cmd_begin_net_wake(int argc, char *argv[]) { int ret = 0; int c; int timeout = DEFAULT_TIMEOUT_IN_SECONDS * 1000; DBusConnection* connection = NULL; DBusMessage *message = NULL; DBusMessage *reply = NULL; DBusError error; bool has_net_wake_data = false; uint8_t net_wake_data = 0; uint32_t net_wake_flags = -1; dbus_error_init(&error); while (1) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"timeout", required_argument, 0, 't'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long(argc, argv, "ht:", long_options, &option_index); if (c == -1) break; switch (c) { case 'h': print_arg_list_help(begin_net_wake_option_list, argv[0], begin_net_wake_cmd_syntax); ret = ERRORCODE_HELP; goto bail; case 't': timeout = strtol(optarg, NULL, 0); break; } } if (optind < argc) { if (!has_net_wake_data) { net_wake_data = strtol(argv[optind], NULL, 0); has_net_wake_data = true; optind++; } } if (optind < argc) { fprintf(stderr, "%s: error: Unexpected extra argument: \"%s\"\n", argv[0], argv[optind]); ret = ERRORCODE_BADARG; goto bail; } if (gInterfaceName[0] == 0) { fprintf(stderr, "%s: error: No WPAN interface set (use the `cd` command, or the `-I` argument for `wpanctl`).\n", argv[0]); ret = ERRORCODE_BADARG; goto bail; } connection = dbus_bus_get(DBUS_BUS_STARTER, &error); if (!connection) { dbus_error_free(&error); dbus_error_init(&error); connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); } require_string(connection != NULL, bail, error.message); { DBusMessageIter iter; DBusMessageIter list_iter; char path[DBUS_MAXIMUM_NAME_LENGTH+1]; char interface_dbus_name[DBUS_MAXIMUM_NAME_LENGTH+1]; ret = lookup_dbus_name_from_interface(interface_dbus_name, gInterfaceName); if (ret != 0) { goto bail; } snprintf(path, sizeof(path), "%s/%s", WPAN_TUNNEL_DBUS_PATH, gInterfaceName); message = dbus_message_new_method_call( interface_dbus_name, path, WPAN_TUNNEL_DBUS_INTERFACE, WPAN_IFACE_CMD_BEGIN_NET_WAKE ); dbus_message_append_args( message, DBUS_TYPE_BYTE, &net_wake_data, DBUS_TYPE_UINT32, &net_wake_flags, DBUS_TYPE_INVALID ); fprintf(stderr, "Begin Net Wake, data = 0x%02X\n", net_wake_data); reply = dbus_connection_send_with_reply_and_block( connection, message, timeout, &error ); if (!reply) { fprintf(stderr, "%s: error: %s\n", argv[0], error.message); ret = ERRORCODE_TIMEOUT; goto bail; } dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID ); if (ret) { fprintf(stderr, "%s failed with error %d. %s\n", argv[0], ret, (ret<0)?strerror(-ret):""); print_error_diagnosis(ret); } } bail: if (connection) dbus_connection_unref(connection); if (message) dbus_message_unref(message); if (reply) dbus_message_unref(reply); dbus_error_free(&error); return ret; }
int tool_cmd_form(int argc, char* argv[]) { int ret = 0; int c; int timeout = DEFAULT_TIMEOUT_IN_SECONDS * 1000; DBusConnection* connection = NULL; DBusMessage *message = NULL; DBusMessage *reply = NULL; DBusError error; const char* network_name = NULL; const char* ula_prefix = NULL; uint16_t node_type = WPAN_IFACE_ROLE_ROUTER; // Default to router for form uint32_t channel_mask = 0; dbus_error_init(&error); while (1) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"timeout", required_argument, 0, 't'}, {"channel", required_argument, 0, 'c'}, {"ula-prefix", required_argument, 0, 'u'}, {"mesh-local-prefix", required_argument, 0, 'M'}, {"legacy-prefix", required_argument, 0, 'L'}, {"type", required_argument, 0, 'T'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long(argc, argv, "hc:t:T:u:", long_options, &option_index); if (c == -1) break; switch (c) { case 'h': print_arg_list_help(form_option_list, argv[0], form_cmd_syntax); ret = ERRORCODE_HELP; goto bail; case 't': timeout = strtol(optarg, NULL, 0); break; case 'c': channel_mask = (1 << strtol(optarg, NULL, 0)); break; case 'M': fprintf(stderr, "%s: error: Setting the mesh local address at the command line isn't yet implemented. Set it as a property instead.\n", argv[0]); ret = ERRORCODE_BADARG; goto bail; break; case 'L': case 'u': ula_prefix = optarg; break; case 'T': node_type = node_type_str2int(optarg); break; } } if (optind < argc) { if (!network_name) { network_name = argv[optind]; optind++; } } if (optind < argc) { fprintf(stderr, "%s: error: Unexpected extra argument: \"%s\"\n", argv[0], argv[optind]); ret = ERRORCODE_BADARG; goto bail; } if (!network_name) { fprintf(stderr, "%s: error: Missing network name.\n", argv[0]); ret = ERRORCODE_BADARG; goto bail; } if (gInterfaceName[0] == 0) { fprintf(stderr, "%s: error: No WPAN interface set (use the `cd` command, or the `-I` argument for `wpanctl`).\n", argv[0]); ret = ERRORCODE_BADARG; goto bail; } connection = dbus_bus_get(DBUS_BUS_STARTER, &error); if (!connection) { dbus_error_free(&error); dbus_error_init(&error); connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); } require_string(connection != NULL, bail, error.message); { DBusMessageIter iter; DBusMessageIter list_iter; char path[DBUS_MAXIMUM_NAME_LENGTH+1]; char interface_dbus_name[DBUS_MAXIMUM_NAME_LENGTH+1]; ret = lookup_dbus_name_from_interface(interface_dbus_name, gInterfaceName); if (ret != 0) { goto bail; } snprintf(path, sizeof(path), "%s/%s", WPAN_TUNNEL_DBUS_PATH, gInterfaceName); message = dbus_message_new_method_call( interface_dbus_name, path, WPAN_TUNNEL_DBUS_INTERFACE, WPAN_IFACE_CMD_FORM ); dbus_message_append_args( message, DBUS_TYPE_STRING, &network_name, DBUS_TYPE_INT16, &node_type, DBUS_TYPE_UINT32, &channel_mask, DBUS_TYPE_INVALID ); if(ula_prefix) { uint8_t ula_bytes[16] = {}; // So the ULA prefix could either be // specified like an IPv6 address, or // specified as a bunch of hex numbers. // We use the presence of a colon (':') // to differentiate. if(strstr(ula_prefix,":")) { // Address-style int bits = inet_pton(AF_INET6,ula_prefix,ula_bytes); if(bits<0) { fprintf(stderr, "Bad ULA \"%s\", errno=%d (%s)\n", ula_prefix, errno, strerror(errno)); goto bail; } else if(!bits) { fprintf(stderr, "Bad ULA \"%s\"\n", ula_prefix); goto bail; } } else { // DATA-style int length = parse_string_into_data(ula_bytes, 8, ula_prefix); if(length<=0) { fprintf(stderr, "Bad ULA \"%s\"\n", ula_prefix); goto bail; } } fprintf(stderr, "Using ULA prefix \"%s\"\n", ula_prefix); uint8_t *addr = ula_bytes; dbus_message_append_args( message, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &addr, 8, DBUS_TYPE_INVALID ); } fprintf(stderr, "Forming WPAN \"%s\" as node type %d\n", network_name, node_type); reply = dbus_connection_send_with_reply_and_block( connection, message, timeout, &error ); if (!reply) { fprintf(stderr, "%s: error: %s\n", argv[0], error.message); ret = ERRORCODE_TIMEOUT; goto bail; } dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID ); if (!ret) { fprintf(stderr, "Successfully formed!\n"); } else { fprintf(stderr, "%s failed with error %d. %s\n", argv[0], ret, wpantund_status_to_cstr(ret)); print_error_diagnosis(ret); } } bail: if (connection) dbus_connection_unref(connection); if (message) dbus_message_unref(message); if (reply) dbus_message_unref(reply); dbus_error_free(&error); return ret; }
int tool_cmd_scan(int argc, char *argv[]) { int ret = 0; int c; int timeout = DEFAULT_TIMEOUT_IN_SECONDS * 1000; DBusConnection* connection = NULL; DBusMessage *message = NULL; DBusMessage *reply = NULL; DBusPendingCall *pending = NULL; DBusError error; int32_t scan_period = 0; uint32_t channel_mask = 0; dbus_error_init(&error); while (1) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"timeout", required_argument, 0, 't'}, {"channel", required_argument, 0, 'c'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long(argc, argv, "hc:t:", long_options, &option_index); if (c == -1) break; switch (c) { case 'h': print_arg_list_help(scan_option_list, argv[0], scan_cmd_syntax); ret = ERRORCODE_HELP; goto bail; case 't': timeout = strtol(optarg, NULL, 0); break; case 'c': channel_mask = strtomask_uint32(optarg); break; } } if (optind < argc) { if (scan_period == 0) { scan_period = strtol(argv[optind], NULL, 0); optind++; } } if (optind < argc) { fprintf(stderr, "%s: error: Unexpected extra argument: \"%s\"\n", argv[0], argv[optind]); ret = ERRORCODE_BADARG; goto bail; } if (gInterfaceName[0] == 0) { fprintf(stderr, "%s: error: No WPAN interface set (use the `cd` command, or the `-I` argument for `wpanctl`).\n", argv[0]); ret = ERRORCODE_BADARG; goto bail; } connection = dbus_bus_get(DBUS_BUS_STARTER, &error); if (!connection) { dbus_error_free(&error); dbus_error_init(&error); connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); } require_string(connection != NULL, bail, error.message); dbus_bus_add_match(connection, gDBusObjectManagerMatchString, &error); require_string(error.name == NULL, bail, error.message); dbus_connection_add_filter(connection, &dbus_beacon_handler, NULL, NULL); { char path[DBUS_MAXIMUM_NAME_LENGTH+1]; char interface_dbus_name[DBUS_MAXIMUM_NAME_LENGTH+1]; DBusMessageIter iter; ret = lookup_dbus_name_from_interface(interface_dbus_name, gInterfaceName); if (ret != 0) { goto bail; } snprintf( path, sizeof(path), "%s/%s", WPANTUND_DBUS_PATH, gInterfaceName ); message = dbus_message_new_method_call( interface_dbus_name, path, WPANTUND_DBUS_APIv1_INTERFACE, WPANTUND_IF_CMD_NET_SCAN_START ); dbus_message_append_args( message, DBUS_TYPE_UINT32, &channel_mask, DBUS_TYPE_INVALID ); print_scan_header(); gScannedNetworkCount = 0; if(!dbus_connection_send_with_reply( connection, message, &pending, timeout )) { fprintf(stderr, "%s: error: IPC failure\n", argv[0]); ret = ERRORCODE_UNKNOWN; goto bail; } while ((dbus_connection_get_dispatch_status(connection) == DBUS_DISPATCH_DATA_REMAINS) || dbus_connection_has_messages_to_send(connection) || !dbus_pending_call_get_completed(pending) ) { dbus_connection_read_write_dispatch(connection, 5000 /*ms*/); } reply = dbus_pending_call_steal_reply(pending); require(reply!=NULL, bail); dbus_message_iter_init(reply, &iter); if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INT32) { fprintf(stderr, "%s: error: Server returned a bad response ('%c')\n", argv[0], dbus_message_iter_get_arg_type(&iter)); ret = ERRORCODE_UNKNOWN; goto bail; } // Get return code dbus_message_iter_get_basic(&iter, &ret); if (ret) { fprintf(stderr, "%s failed with error %d. %s\n", argv[0], ret, wpantund_status_to_cstr(ret)); print_error_diagnosis(ret); goto bail; } } bail: if (reply) { dbus_message_unref(reply); } if (pending != NULL) { dbus_pending_call_unref(pending); } if (message) { dbus_message_unref(message); } if (connection) { dbus_bus_remove_match(connection, gDBusObjectManagerMatchString, NULL); dbus_connection_remove_filter(connection,&dbus_beacon_handler,NULL); dbus_connection_unref(connection); } dbus_error_free(&error); return ret; }
int tool_cmd_peek(int argc, char* argv[]) { int ret = 0; int c; int timeout = DEFAULT_TIMEOUT_IN_SECONDS * 1000; DBusConnection* connection = NULL; DBusMessage *message = NULL; DBusMessage *reply = NULL; DBusError error; uint32_t address = 0; uint16_t count = 32; bool simple_data_format = false; dbus_error_init(&error); while (1) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"timeout", required_argument, 0, 't'}, {"count", required_argument, 0, 'c'}, {"data", no_argument, 0, 'd'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long(argc, argv, "ht:c:d", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'h': print_arg_list_help(peek_option_list, argv[0], peek_cmd_syntax); ret = ERRORCODE_HELP; goto bail; case 't': timeout = strtol(optarg, NULL, 0); break; case 'c': count = strtol(optarg, NULL, 0); break; case 'd': simple_data_format = true; break; } } if (optind < argc) { address = strtol(argv[optind], NULL, 0); optind++; } else { fprintf(stderr, "%s: error: Missing required address parameter\n", argv[0]); ret = ERRORCODE_BADARG; goto bail; } if (optind < argc) { fprintf(stderr, "%s: error: Unexpected extra argument: \"%s\"\n", argv[0], argv[optind]); ret = ERRORCODE_BADARG; goto bail; } if (gInterfaceName[0] == 0) { fprintf( stderr, "%s: error: No WPAN interface set (use the `cd` command, or the `-I` argument for `wpanctl`).\n", argv[0] ); ret = ERRORCODE_BADARG; goto bail; } connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); require_string(connection != NULL, bail, error.message); { char path[DBUS_MAXIMUM_NAME_LENGTH+1]; char interface_dbus_name[DBUS_MAXIMUM_NAME_LENGTH+1]; bool did_succeed; uint8_t *data_ptr = NULL; int data_len = 0; uint16_t i; ret = lookup_dbus_name_from_interface(interface_dbus_name, gInterfaceName); if (ret != 0) { print_error_diagnosis(ret); goto bail; } snprintf(path, sizeof(path), "%s/%s", WPANTUND_DBUS_PATH, gInterfaceName); message = dbus_message_new_method_call( interface_dbus_name, path, WPANTUND_DBUS_APIv1_INTERFACE, WPANTUND_IF_CMD_PEEK ); fprintf(stdout, "Peeking at address 0x%x (%d) for %d bytes\n", address, address, count); dbus_message_append_args( message, DBUS_TYPE_UINT32, &address, DBUS_TYPE_UINT16, &count, DBUS_TYPE_INVALID ); reply = dbus_connection_send_with_reply_and_block( connection, message, timeout, &error ); if (!reply) { fprintf(stderr, "%s: error: %s\n", argv[0], error.message); ret = ERRORCODE_TIMEOUT; goto bail; } did_succeed = dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &ret, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &data_ptr, &data_len, DBUS_TYPE_INVALID ); if (!did_succeed) { did_succeed = dbus_message_get_args(reply, NULL, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID ); } if (!did_succeed || ret != 0) { fprintf(stderr, "%s failed with error %d. %s\n", argv[0], ret, wpantund_status_to_cstr(ret)); print_error_diagnosis(ret); goto bail; } if (simple_data_format) { for (i = 0; i < data_len; i++) { fprintf(stdout, "%02X ", *data_ptr++); if (i % 32 == 31) { fprintf(stdout, "\n"); } } fprintf(stdout, "\n"); } else { dump_data(data_ptr, data_len); } } bail: if (connection) { dbus_connection_unref(connection); } if (message) { dbus_message_unref(message); } if (reply) { dbus_message_unref(reply); } dbus_error_free(&error); return ret; }
int tool_cmd_joiner(int argc, char* argv[]) { int ret = 0; int c; int timeout = DEFAULT_TIMEOUT_IN_SECONDS * 1000; DBusConnection* connection = NULL; DBusMessage *message = NULL; DBusMessage *reply = NULL; DBusMessageIter iter; DBusMessageIter dict_iter; DBusError error; const char *empty_string = ""; const char *psk = NULL; const char *provisioning_url = NULL; const char *vendor_name = NULL; const char *vendor_model = NULL; const char *vendor_sw_version = NULL; const char *vendor_data = NULL; const char *property_joiner_state = kWPANTUNDProperty_ThreadJoinerState; dbus_bool_t action = false; dbus_error_init(&error); if (argc == 1) { fprintf(stderr, "%s: error: Missing command.\n", argv[0]); print_arg_list_help(joiner_option_list, argv[0], joiner_cmd_syntax); goto bail; } while (1) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"timeout", required_argument, 0, 't'}, {"start", no_argument, 0, 'e'}, {"stop", no_argument, 0, 'd'}, {"attach", no_argument, 0, 'a'}, {"state", no_argument, 0, 's'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long(argc, argv, "hst:eda", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'h': print_arg_list_help(joiner_option_list, argv[0], joiner_cmd_syntax); ret = ERRORCODE_HELP; goto bail; case 't': //timeout timeout = strtol(optarg, NULL, 0); break; case 's': // state if (optind < argc) { fprintf(stderr, "%s: error: Unexpected extra argument: \"%s\"\n", argv[0], argv[optind]); ret = ERRORCODE_BADARG; goto bail; } connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); ret = create_new_wpan_dbus_message(&message, WPANTUND_IF_CMD_PROP_GET); require_action(ret == 0, bail, print_error_diagnosis(ret)); dbus_message_append_args( message, DBUS_TYPE_STRING, &property_joiner_state, DBUS_TYPE_INVALID ); reply = dbus_connection_send_with_reply_and_block( connection, message, timeout, &error ); if (!reply) { fprintf(stderr, "%s: error: %s\n", argv[0], error.message); ret = ERRORCODE_TIMEOUT; goto bail; } dbus_message_iter_init(reply, &iter); // Get return code dbus_message_iter_get_basic(&iter, &ret); if (ret) { const char* error_cstr = NULL; // Try to see if there is an error explanation we can extract dbus_message_iter_next(&iter); if (dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_STRING) { dbus_message_iter_get_basic(&iter, &error_cstr); } if(!error_cstr || error_cstr[0] == 0) { error_cstr = (ret<0)?strerror(-ret):"Get failed"; } fprintf(stderr, "%s: %s (%d)\n", property_joiner_state, error_cstr, ret); goto bail; } // Move to the property dbus_message_iter_next(&iter); uint8_t state; dbus_message_iter_get_basic(&iter, &state); fprintf(stdout, "%d (%s)\n", state, joiner_state_int2str(state)); goto bail; case 'a': // joiner attaches to commissioned thread network connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); ret = create_new_wpan_dbus_message(&message, WPANTUND_IF_CMD_JOINER_ATTACH); require_action(ret == 0, bail, print_error_diagnosis(ret)); reply = dbus_connection_send_with_reply_and_block( connection, message, timeout, &error ); if (!reply) { fprintf(stderr, "%s: error: %s\n", argv[0], error.message); ret = ERRORCODE_TIMEOUT; goto bail; } dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID ); if (!ret) { fprintf(stderr, "Successfully Attached!\n"); } else { fprintf(stderr, "%s failed with error %d. %s\n", argv[0], ret, wpantund_status_to_cstr(ret)); print_error_diagnosis(ret); } goto bail; case 'e': // start commissioning if (optind < argc) { psk = argv[optind]; optind++; } if (!psk) { fprintf(stderr, "%s: error: Missing PSK value.\n", argv[0]); ret = ERRORCODE_BADARG; goto bail; } ret = check_psk_format(psk); if (ret != 0) { fprintf(stderr, "%s: error: Invalid PSKd %d\n", argv[0], ret); goto bail; } if (optind < argc) { size_t len; provisioning_url = argv[optind++]; len = strnlen(provisioning_url, (COMMR_PROVIISIONING_URL_MAX_LENGTH + 1)); if (len > COMMR_PROVIISIONING_URL_MAX_LENGTH) { fprintf(stderr, "%s: error: Provisioning URL is too long, must be maximum %d characters\n", argv[0], COMMR_PROVIISIONING_URL_MAX_LENGTH); ret = ERRORCODE_BADARG; goto bail; } } if (optind < argc) { vendor_name = argv[optind++]; } if (optind < argc) { vendor_model = argv[optind++]; } if (optind < argc) { vendor_sw_version = argv[optind++]; } if (optind < argc) { vendor_data = argv[optind++]; } if (optind < argc) { fprintf(stderr, "%s: error: Unexpected extra argument: \"%s\"\n", argv[0], argv[optind]); ret = ERRORCODE_BADARG; goto bail; } connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); require_string(connection != NULL, bail, error.message); ret = create_new_wpan_dbus_message(&message, WPANTUND_IF_CMD_JOINER_START); require_action(ret == 0, bail, print_error_diagnosis(ret)); dbus_message_iter_init_append(message, &iter); // Open a container as "Array of Dictionary entries from String to Variants" (dbus type "a{sv}") dbus_message_iter_open_container( &iter, DBUS_TYPE_ARRAY, DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict_iter ); // Append dictionary entries append_dbus_dict_entry_basic( &dict_iter, kWPANTUNDValueMapKey_Joiner_PSKd, DBUS_TYPE_STRING, &psk ); if (provisioning_url) { append_dbus_dict_entry_basic( &dict_iter, kWPANTUNDValueMapKey_Joiner_ProvisioningUrl, DBUS_TYPE_STRING, &provisioning_url ); } if (vendor_name) { append_dbus_dict_entry_basic( &dict_iter, kWPANTUNDValueMapKey_Joiner_VendorName, DBUS_TYPE_STRING, &vendor_name ); } if (vendor_model) { append_dbus_dict_entry_basic( &dict_iter, kWPANTUNDValueMapKey_Joiner_VendorModel, DBUS_TYPE_STRING, &vendor_model ); } if (vendor_sw_version) { append_dbus_dict_entry_basic( &dict_iter, kWPANTUNDValueMapKey_Joiner_VendorSwVersion, DBUS_TYPE_STRING, &vendor_sw_version ); } if (vendor_data) { append_dbus_dict_entry_basic( &dict_iter, kWPANTUNDValueMapKey_Joiner_VendorData, DBUS_TYPE_STRING, &vendor_data ); } dbus_message_iter_close_container(&iter, &dict_iter); // Send DBus message and parse the DBus reply reply = dbus_connection_send_with_reply_and_block(connection, message, timeout, &error); if (!reply) { fprintf(stderr, "%s: error: %s\n", argv[0], error.message); ret = ERRORCODE_TIMEOUT; goto bail; } dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID); if (ret) { fprintf(stderr, "Failed to start Joiner Commissioning - error %d. %s\n", ret, wpantund_status_to_cstr(ret)); print_error_diagnosis(ret); goto bail; } fprintf(stdout, "Started joiner commissioning, PSKd:\"%s\"", psk); if (provisioning_url) { fprintf(stdout, ", ProvisioningURL:\"%s\"", provisioning_url); } if (vendor_name) { fprintf(stdout, ", VendorName:\"%s\"", vendor_name); } if (vendor_model) { fprintf(stdout, ", VendorModel:\"%s\"", vendor_model); } if (vendor_sw_version) { fprintf(stdout, ", VendorSwVersion:\"%s\"", vendor_sw_version); } if (vendor_data) { fprintf(stdout, ", VendorData:\"%s\"", vendor_data); } fprintf(stdout, "\n", psk); goto bail; case 'd': // stop commissioning if (optind < argc) { fprintf(stderr, "%s: error: Unexpected extra argument: \"%s\"\n", argv[0], argv[optind]); ret = ERRORCODE_BADARG; goto bail; } connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); require_string(connection != NULL, bail, error.message); ret = create_new_wpan_dbus_message(&message, WPANTUND_IF_CMD_JOINER_STOP); require_action(ret == 0, bail, print_error_diagnosis(ret)); reply = dbus_connection_send_with_reply_and_block(connection, message, timeout, &error); if (!reply) { fprintf(stderr, "%s: error: %s\n", argv[0], error.message); ret = ERRORCODE_TIMEOUT; goto bail; } dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID); if (ret) { fprintf(stderr, "Failed to stop joiner commissioning - error %d. %s\n", ret, wpantund_status_to_cstr(ret)); print_error_diagnosis(ret); goto bail; } fprintf(stdout, "Stopped joiner commissioning\n"); goto bail; } } bail: if (connection) { dbus_connection_unref(connection); } if (message) { dbus_message_unref(message); } if (reply) { dbus_message_unref(reply); } dbus_error_free(&error); return ret; }
OSStatus host_platform_sdio_transfer( bus_transfer_direction_t direction, sdio_command_t command, sdio_transfer_mode_t mode, sdio_block_size_t block_size, uint32_t argument, /*@null@*/ uint32_t* data, uint16_t data_size, sdio_response_needed_t response_expected, /*@out@*/ /*@null@*/ uint32_t* response ) { uint32_t loop_count = 0; OSStatus result; uint16_t attempts = 0; check_string(!((command == SDIO_CMD_53) && (data == NULL)), "Bad args" ); if ( response != NULL ) { *response = 0; } platform_mcu_powersave_disable(); /* Ensure the bus isn't stuck half way through transfer */ DMA2_Stream3->CR = 0; restart: SDIO->ICR = (uint32_t) 0xFFFFFFFF; sdio_transfer_failed = false; ++attempts; /* Check if we've tried too many times */ if (attempts >= (uint16_t) BUS_LEVEL_MAX_RETRIES) { result = kGeneralErr; goto exit; } /* Prepare the data transfer register */ current_command = command; if ( command == SDIO_CMD_53 ) { sdio_enable_bus_irq(); /* Dodgy STM32 hack to set the CMD53 byte mode size to be the same as the block size */ if ( mode == SDIO_BYTE_MODE ) { block_size = find_optimal_block_size( data_size ); if ( block_size < SDIO_512B_BLOCK ) { argument = ( argument & (uint32_t) ( ~0x1FF ) ) | block_size; } else { argument = ( argument & (uint32_t) ( ~0x1FF ) ); } } /* Prepare the SDIO for a data transfer */ current_transfer_direction = direction; sdio_prepare_data_transfer( direction, block_size, (uint8_t*) data, data_size ); /* Send the command */ SDIO->ARG = argument; SDIO->CMD = (uint32_t) ( command | SDIO_Response_Short | SDIO_Wait_No | SDIO_CPSM_Enable ); /* Wait for the whole transfer to complete */ result = mico_rtos_get_semaphore( &sdio_transfer_finished_semaphore, (uint32_t) 50 ); if ( result != kNoErr ) { goto exit; } if ( sdio_transfer_failed == true ) { goto restart; } /* Check if there were any SDIO errors */ require(( SDIO->STA & ( SDIO_STA_DTIMEOUT | SDIO_STA_CTIMEOUT ) ) == 0, restart); require_string(( SDIO->STA & ( SDIO_STA_CCRCFAIL | SDIO_STA_DCRCFAIL | SDIO_STA_TXUNDERR | SDIO_STA_RXOVERR ) ) == 0, restart, "SDIO communication failure"); /* Wait till complete */ loop_count = (uint32_t) SDIO_TX_RX_COMPLETE_TIMEOUT_LOOPS; do { loop_count--; if ( loop_count == 0 || ( ( SDIO->STA & SDIO_ERROR_MASK ) != 0 ) ) { goto restart; } } while ( ( SDIO->STA & ( SDIO_STA_TXACT | SDIO_STA_RXACT ) ) != 0 ); if ( direction == BUS_READ ) { memcpy( user_data, dma_data_source, (size_t) user_data_size ); } } else { uint32_t temp_sta; /* Send the command */ SDIO->ARG = argument; SDIO->CMD = (uint32_t) ( command | SDIO_Response_Short | SDIO_Wait_No | SDIO_CPSM_Enable ); loop_count = (uint32_t) COMMAND_FINISHED_CMD52_TIMEOUT_LOOPS; do { temp_sta = SDIO->STA; loop_count--; if ( loop_count == 0 || ( ( response_expected == RESPONSE_NEEDED ) && ( ( temp_sta & SDIO_ERROR_MASK ) != 0 ) ) ) { goto restart; } } while ( ( temp_sta & SDIO_FLAG_CMDACT ) != 0 ); } if ( response != NULL ) { *response = SDIO->RESP1; } result = kNoErr; exit: platform_mcu_powersave_enable(); #ifndef SDIO_1_BIT SDIO->MASK = SDIO_MASK_SDIOITIE; #endif return result; }
int url_parse( char* uri, struct url_components_s* components ) { int bytes_parsed = 0; char tmp; if(!url_is_absolute(uri)) goto skip_absolute_url_stuff; check_string(uri, "NULL URI parameter"); components->protocol = uri; while(*uri != ':') { require_string(*uri, bail, "unexpected end of string"); uri++; bytes_parsed++; } // Zero terminate the protocol; *uri++ = 0; bytes_parsed++; require_string(*uri, bail, "unexpected end of string"); if(uri[0] == '/' && uri[1] == '/') { char* addr_end; char* addr_begin; bool got_port = false; // Contains a hostname. Parse it. uri += 2; bytes_parsed += 2; addr_begin = uri; while( (tmp=*uri) != '/' && ( isurlchar(tmp) || (tmp == '[') || (tmp == ']') || (tmp == ':') || (tmp == '%') // Necessary for scoped addresses || (tmp == '@') ) ) { uri++; bytes_parsed++; } addr_end = uri - 1; if(*uri) { *uri++ = 0; bytes_parsed++; } for(; (addr_end >= addr_begin) && (*addr_end != '@') && (*addr_end != '['); addr_end-- ) { if(*addr_end == ']') { *addr_end = 0; got_port = true; } else if(!got_port && (*addr_end == ':')) { components->port = addr_end + 1; *addr_end = 0; got_port = true; } } components->host = addr_end + 1; if(*addr_end=='@') { *addr_end = 0; for(; (addr_end >= addr_begin) && (*addr_end != '/'); addr_end-- ) { if(*addr_end==':') { *addr_end = 0; components->password = addr_end + 1; } } if(*addr_end=='/') { components->username = addr_end + 1; } } } skip_absolute_url_stuff: components->path = uri; // Move to the end of the path. while( ((tmp=*uri) != '#') && (tmp != '?') && ( isurlchar(tmp) || (tmp == '[') || (tmp == ']') || (tmp == ':') || (tmp == '/') || (tmp == '=') || (tmp == '&') || (tmp == '%') ) ) { uri++; bytes_parsed++; } // Handle query component if(*uri == '?') { *uri++ = 0; bytes_parsed++; components->query = uri; // Move to the end of the query. while( ((tmp=*uri) != '#') && ( isurlchar(tmp) || (tmp == '[') || (tmp == ']') || (tmp == ':') || (tmp == '/') || (tmp == '=') || (tmp == '&') || (tmp == '%') || (tmp == ';') ) ) { uri++; bytes_parsed++; } } // Zero terminate if(*uri) { *uri = 0; bytes_parsed++; } bail: return bytes_parsed; }
//============================================================================== //! //============================================================================== inline string_ref get_filetype(cref value) { return require_string(value[field_filetype]); }
IOReturn PrintSMARTData ( io_service_t service ) { IOCFPlugInInterface ** cfPlugInInterface = NULL; IOATASMARTInterface ** smartInterface = NULL; HRESULT herr = S_OK; IOReturn err = kIOReturnSuccess; SInt32 score = 0; Boolean conditionExceeded = false; CFStringRef description = NULL; UInt8 buffer[512]; UInt32 bytesRead; ATASMARTLogDirectory logData; err = IOCreatePlugInInterfaceForService ( service, kIOATASMARTUserClientTypeID, kIOCFPlugInInterfaceID, &cfPlugInInterface, &score ); require_string ( ( err == kIOReturnSuccess ), ErrorExit, "IOCreatePlugInInterfaceForService" ); herr = ( *cfPlugInInterface )->QueryInterface ( cfPlugInInterface, CFUUIDGetUUIDBytes ( kIOATASMARTInterfaceID ), ( LPVOID ) &smartInterface ); require_string ( ( herr == S_OK ), ReleasePlugIn, "QueryInterface" ); require_string ( ( smartInterface != NULL ), ReleasePlugIn, "smartInterface" ); description = GetDriveDescription ( service ); printf ( "SAT Drive: " ); fflush ( stdout ); CFShow ( description ); CFRelease ( description ); err = ( *smartInterface )->SMARTEnableDisableOperations ( smartInterface, true ); require_string ( ( err == kIOReturnSuccess ), ReleaseInterface, "SMARTEnableDisableOperations" ); err = ( *smartInterface )->SMARTEnableDisableAutosave ( smartInterface, true ); require ( ( err == kIOReturnSuccess ), ReleaseInterface ); err = ( *smartInterface )->SMARTReturnStatus ( smartInterface, &conditionExceeded ); require ( ( err == kIOReturnSuccess ), ReleaseInterface ); if ( conditionExceeded ) { printf ( "SMART condition exceeded, drive will fail soon\n" ); } else { printf ( "SMART condition not exceeded, drive OK\n" ); } err = ( *smartInterface )->GetATAIdentifyData (smartInterface, &buffer, sizeof buffer, &bytesRead ); require ( ( err == kIOReturnSuccess ), ReleaseInterface ); require ( ( bytesRead == sizeof buffer ), ReleaseInterface ); printf ( "Model: %s\n", buffer + 2 * kATAIdentifyModelNumber ); // FIXME not null terminated err = ( *smartInterface )->SMARTReadLogDirectory (smartInterface, &logData ); require ( ( err == kIOReturnSuccess ), ReleaseInterface ); for (int i = 0; i < 255; i++) { if (logData.entries[i].numberOfSectors > 0) printf ( "entry[%d]: %d\n", i, logData.entries[i].numberOfSectors); } err = ( *smartInterface )->SMARTReadLogAtAddress ( smartInterface, 224, buffer, sizeof buffer); require ( ( err == kIOReturnSuccess ), ReleaseInterface ); for (int i = 0; i < 512; i++) { if (buffer[i]) printf ( "buffer[%d]: %d\n", i, buffer[i]); } #if 0 err = ( *smartInterface )->SMARTWriteLogAtAddress ( smartInterface, 224, buffer, sizeof buffer); require ( ( err == kIOReturnSuccess ), ReleaseInterface ); #endif ReleaseInterface: printf ("status %s\n", getStatus(err)); ( *smartInterface )->Release ( smartInterface ); smartInterface = NULL; ReleasePlugIn: err = IODestroyPlugInInterface ( cfPlugInInterface ); require ( ( err == kIOReturnSuccess ), ErrorExit ); ErrorExit: return err; }
static CFMutableDictionaryRef lc_code_sig(uint8_t *lc_code_signature, size_t lc_code_signature_len) { CFMutableDictionaryRef code_signature = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); require(code_signature, out); CS_SuperBlob *sb = (CS_SuperBlob*)lc_code_signature; require(ntohl(sb->magic) == CSMAGIC_EMBEDDED_SIGNATURE, out); uint32_t count; for (count = 0; count < ntohl(sb->count); count++) { //uint32_t type = ntohl(sb->index[count].type); uint32_t offset = ntohl(sb->index[count].offset); uint8_t *bytes = lc_code_signature + offset; //fprintf(stderr, "blob[%d]: (type: 0x%.08x, offset: %p)\n", count, type, (void*)offset); uint32_t magic = ntohl(*(uint32_t*)bytes); uint32_t length = ntohl(*(uint32_t*)(bytes+4)); //fprintf(stderr, " magic: 0x%.08x length: %d\n", magic, length); switch(magic) { case 0xfade0c01: //write_data("requirements", bytes, length); break; case 0xfade0c02: //write_data("codedir", bytes, length); { const CS_CodeDirectory *cd = (const CS_CodeDirectory *)bytes; CFDataRef codedir = CFDataCreate(kCFAllocatorDefault, bytes, length); require(codedir, out); CFDictionarySetValue(code_signature, CFSTR("CodeDirectory"), codedir); CFRelease(codedir); require_string(ntohl(cd->version) >= 0x20001, out, "incompatible version"); require_string(ntohl(cd->version) <= 0x2F000, out, "incompatible version"); require_string(cd->hashSize == 20, out, "unexpected hash size"); require_string(cd->hashType == 1, out, "unexpected hash type"); uint32_t hash_offset = ntohl(cd->hashOffset); uint32_t entitlement_slot = 5; if (ntohl(cd->nSpecialSlots) >= entitlement_slot) { CFDataRef message = CFDataCreate(kCFAllocatorDefault, bytes+hash_offset-entitlement_slot*cd->hashSize, cd->hashSize); require(message, out); CFDictionarySetValue(code_signature, CFSTR("EntitlementsCDHash"), message); CFRelease(message); } else fprintf(stderr, "no entitlements slot yet\n"); } break; case 0xfade0b01: //write_data("signed", lc_code_signature, bytes-lc_code_signature); if (length != 8) { CFDataRef message = CFDataCreate(kCFAllocatorDefault, bytes+8, length-8); require(message, out); CFDictionarySetValue(code_signature, CFSTR("SignedData"), message); CFRelease(message); } break; case 0xfade7171: { unsigned char digest[CC_SHA1_DIGEST_LENGTH]; CCDigest(kCCDigestSHA1, bytes, length, digest); CFDataRef message = CFDataCreate(kCFAllocatorDefault, digest, sizeof(digest)); require(message, out); CFDictionarySetValue(code_signature, CFSTR("EntitlementsHash"), message); CFRelease(message); message = CFDataCreate(kCFAllocatorDefault, bytes+8, length-8); require(message, out); CFDictionarySetValue(code_signature, CFSTR("Entitlements"), message); CFRelease(message); break; } default: fprintf(stderr, "Skipping block with magic: 0x%x\n", magic); break; } } return code_signature; out: if (code_signature) CFRelease(code_signature); return NULL; }