/** * DHCP: Sends DHCP-Release message. Releases occupied IP. */ void dhcp_send_release(void) { uint32_t packetsize = sizeof(struct iphdr) + sizeof(struct udphdr) + sizeof(struct btphdr); struct btphdr *btph; dhcp_options_t opt; btph = (struct btphdr *) (ðer_packet[ sizeof(struct iphdr) + sizeof(struct udphdr)]); memset(ether_packet, 0, packetsize); btph -> op = 1; btph -> htype = 1; btph -> hlen = 6; strcpy((char *) btph -> file, ""); memcpy(btph -> chaddr, get_mac_address(), 6); btph -> ciaddr = htonl(dhcp_own_ip); memset(&opt, 0, sizeof(dhcp_options_t)); opt.msg_type = DHCPRELEASE; opt.server_ID = dhcp_server_ip; opt.flag[DHCP_SERVER_ID] = 1; dhcp_encode_options(btph -> vend, &opt); fill_udphdr(ðer_packet[sizeof(struct iphdr)], sizeof(struct btphdr) + sizeof(struct udphdr), UDPPORT_BOOTPC, UDPPORT_BOOTPS); fill_iphdr(ether_packet, sizeof(struct btphdr) + sizeof(struct udphdr) + sizeof(struct iphdr), IPTYPE_UDP, dhcp_own_ip, dhcp_server_ip); send_ipv4(ether_packet, packetsize); }
/* Get a sort of unique machine identifier. Prefer the MAC address; if that fails, fall back to the hostname; if that fails, pick something. */ static std::string get_machine_identifier(void) { std::string result; unsigned char mac_addr[MAC_ADDRESS_MAX_LEN] = {}; if (get_mac_address(mac_addr)) { result.reserve(2 * MAC_ADDRESS_MAX_LEN); for (size_t i=0; i < MAC_ADDRESS_MAX_LEN; i++) { char buff[3]; snprintf(buff, sizeof buff, "%02x", mac_addr[i]); result.append(buff); } } else if (get_hostname_identifier(&result)) { /* Hooray */ } else { /* Fallback */ result.assign("nohost"); } return result; }
//128bit; template<> MurmurHash<128>::result_type MurmurHash<128>::salt(bool fixed) { if (fixed) { result_type ret; uint32_t* p = (uint32_t*)&ret; (*p++) = 0x58132134; (*p++) = 0x94827513; (*p++) = 0x16574893; (*p) = 0x17932864; return ret; } result_type h; uint32_t* p0 = (uint32_t*)&h; std::time_t now = std::time(nullptr); char* nowstr = std::ctime(&now); MurmurHash3_x86_32((void*)nowstr, (int)std::strlen(nowstr), 0, (void*)p0); std::vector<zks::u8string> mac_addrs = get_mac_address(); for (size_t i = 0; i < mac_addrs.size(); ++i) { #ifdef _ZKS64 MurmurHash3_x64_128((void*)mac_addrs[i].data(), (int)mac_addrs[i].size(), *p0, (void*)&h); #else MurmurHash3_x86_128((void*)mac_addrs[i].data(), (int)mac_addrs[i].size(), *p0, (void*)&h); #endif } return h; }
void get_addresses(WCHAR* ip_address, WCHAR* mac_address) { HKEY hkey_adapters, hkey_adapter, hkey_ip, hkey_ipg; DWORD i = 0; WCHAR net_key[] = L"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}"; WCHAR tcpip_key[] = L"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces"; WCHAR subkey_name[128]; WCHAR component_id[128]; WCHAR guid[39]; DWORD subkey_size = 128; DWORD component_size = 128 * sizeof(WCHAR); DWORD guid_size = 39 * sizeof(WCHAR); bool adapter_found = false; // Clear the addresses wsprintf(ip_address, L"<unknown>"); wsprintf(mac_address, L"<unknown>"); // First we need to find the TAP-Win32 adapter (identified by 'tap0901') and get its GUID RegOpenKeyEx(HKEY_LOCAL_MACHINE, net_key, NULL, KEY_READ, &hkey_adapters); while (RegEnumKeyEx(hkey_adapters, i, subkey_name, &subkey_size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { RegOpenKeyEx(hkey_adapters, subkey_name, NULL, KEY_READ, &hkey_adapter); RegQueryValueEx(hkey_adapter, L"ComponentId", NULL, NULL, (LPBYTE)component_id, &component_size); RegQueryValueEx(hkey_adapter, L"NetCfgInstanceId", NULL, NULL, (LPBYTE)guid, &guid_size); RegCloseKey(hkey_adapter); if (!wcscmp(component_id, L"tap0901")) { adapter_found = true; break; } i++; subkey_size = 128; } RegCloseKey(hkey_adapters); // If we have the guid, fetch the IP address from the registry if (adapter_found) { DWORD dhcp_enabled = 0; DWORD buf_size = sizeof(DWORD); DWORD ip_size = 16 * sizeof(WCHAR); RegOpenKeyEx(HKEY_LOCAL_MACHINE, tcpip_key, NULL, KEY_READ, &hkey_ip); RegOpenKeyEx(hkey_ip, guid, NULL, KEY_READ, &hkey_ipg); RegQueryValueEx(hkey_ipg, L"EnableDHCP", NULL, NULL, (LPBYTE)&dhcp_enabled, &buf_size); if (dhcp_enabled) { RegQueryValueEx(hkey_ipg, L"DhcpIPAddress", NULL, NULL, (LPBYTE)ip_address, &ip_size); } else { RegQueryValueEx(hkey_ipg, L"IPAddress", NULL, NULL, (LPBYTE)ip_address, &ip_size); } RegCloseKey(hkey_ipg); RegCloseKey(hkey_ip); get_mac_address(mac_address, guid); } }
static gboolean get_address (GcIfaceAddress *gc, int *timestamp, GHashTable **address, GeoclueAccuracy **accuracy, GError **error) { GeoclueLocalnet *localnet; int i, ret_val; char *mac = NULL; Gateway *gw; localnet = GEOCLUE_LOCALNET (gc); /* we may be trying to read /proc/net/arp right after network connection. * It's sometimes not up yet, try a couple of times */ for (i = 0; i < 5; i++) { ret_val = get_mac_address (&mac); if (ret_val < 0) return FALSE; else if (ret_val == 1) break; usleep (200); } if (!mac) { g_warning ("Couldn't get current gateway mac address"); if (error) { g_set_error (error, GEOCLUE_ERROR, GEOCLUE_ERROR_NOT_AVAILABLE, "Could not get current gateway mac address"); } return FALSE; } gw = geoclue_localnet_find_gateway (localnet, mac); g_free (mac); if (timestamp) { *timestamp = time(NULL); } if (address) { if (gw) { *address = geoclue_address_details_copy (gw->address); } else { *address = geoclue_address_details_new (); } } if (accuracy) { if (gw) { *accuracy = geoclue_accuracy_copy (gw->accuracy); } else { *accuracy = geoclue_accuracy_new (GEOCLUE_ACCURACY_LEVEL_NONE, 0, 0); } } return TRUE; }
int rtems_minimac_driver_attach(struct rtems_bsdnet_ifconfig *config, int attaching) { struct ifnet *ifp; rtems_isr_entry dummy; int i; static int registered; uint8_t *tx_buffer = (uint8_t *)MINIMAC_TX_BASE; if(!attaching) { printk("Minimac driver cannot be detached.\n"); return 0; } ifp = &(arpcom.ac_if); if(registered) { printk("Minimac driver already in use.\n"); return 0; } registered = 1; memcpy(arpcom.ac_enaddr, get_mac_address(), 6); ifp->if_mtu = ETHERMTU; ifp->if_unit = 0; ifp->if_name = "minimac"; ifp->if_init = minimac_init; ifp->if_ioctl = minimac_ioctl; ifp->if_start = minimac_start; ifp->if_output = ether_output; ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX; ifp->if_snd.ifq_maxlen = ifqmaxlen; if_attach(ifp); ether_ifattach(ifp); rx_daemon_id = rtems_bsdnet_newproc("mrxd", 4096, rx_daemon, NULL); tx_daemon_id = rtems_bsdnet_newproc("mtxd", 4096, tx_daemon, NULL); rtems_interrupt_catch(rx_interrupt_handler, MM_IRQ_ETHRX, &dummy); rtems_interrupt_catch(tx_interrupt_handler, MM_IRQ_ETHTX, &dummy); MM_WRITE(MM_MINIMAC_STATE0, MINIMAC_STATE_LOADED); MM_WRITE(MM_MINIMAC_STATE1, MINIMAC_STATE_LOADED); for(i=0;i<7; i++) tx_buffer[i] = 0x55; tx_buffer[7] = 0xd5; MM_WRITE(MM_MINIMAC_SETUP, 0); rtems_bsdnet_event_send(tx_daemon_id, CTS_EVENT); bsp_interrupt_vector_enable(MM_IRQ_ETHRX); bsp_interrupt_vector_enable(MM_IRQ_ETHTX); return 1; }
//32bits template<> MurmurHash<32>::result_type MurmurHash<32>::salt(bool fixed) { if (fixed) { return result_type(0x58132134); } result_type h = 0; std::vector<zks::u8string> mac_addrs = get_mac_address(); for (size_t i = 0; i < mac_addrs.size(); ++i) { MurmurHash3_x86_32((void*) mac_addrs[i].data(), (int)mac_addrs[i].size(), h, (void*) &h); } std::time_t now = std::time(nullptr); char* nowstr = std::ctime(&now); MurmurHash3_x86_32((void*) nowstr, (int)std::strlen(nowstr), h, (void*) &h); return h; }
/* * Init routine which accepts the variables from PMON */ __init prom_init(int argc, char **arg, char **env, struct callvectors *cv) { int i = 0; /* Callbacks for halt, restart */ _machine_restart = (void (*)(char *))prom_exit; _machine_halt = prom_halt; _machine_power_off = prom_halt; #ifdef CONFIG_MIPS64 /* Do nothing for the 64-bit for now. Just implement for the 32-bit */ #else /* CONFIG_MIPS64 */ debug_vectors = cv; arcs_cmdline[0] = '\0'; /* Get the boot parameters */ for (i = 1; i < argc; i++) { if (strlen(arcs_cmdline) + strlen(arg[i] + 1) >= sizeof(arcs_cmdline)) break; strcat(arcs_cmdline, arg[i]); strcat(arcs_cmdline, " "); } while (*env) { if (strncmp("ocd_base", *env, strlen("ocd_base")) == 0) yosemite_base = simple_strtol(*env + strlen("ocd_base="), NULL, 16); if (strncmp("cpuclock", *env, strlen("cpuclock")) == 0) cpu_clock = simple_strtol(*env + strlen("cpuclock="), NULL, 10); env++; } #endif /* CONFIG_MIPS64 */ mips_machgroup = MACH_GROUP_TITAN; mips_machtype = MACH_TITAN_YOSEMITE; get_mac_address(titan_ge_mac_addr_base); debug_vectors->printf("Booting Linux kernel...\n"); }
static void program_mac_address(u16 io_base) { void *search_address = NULL; size_t search_length = -1; /* Default MAC Address of A0:00:BA:D0:0B:AD */ u32 high_dword = 0xD0BA00A0; /* high dword of mac address */ u32 low_dword = 0x0000AD0B; /* low word of mac address as a dword */ if (IS_ENABLED(CONFIG_CHROMEOS)) { struct region_device rdev; if (fmap_locate_area_as_rdev("RO_VPD", &rdev) == 0) { search_address = rdev_mmap_full(&rdev); if (search_address != NULL) search_length = region_device_sz(&rdev); } } else { search_address = cbfs_boot_map_with_leak("vpd.bin", CBFS_TYPE_RAW, &search_length); } if (search_address == NULL) printk(BIOS_ERR, "LAN: VPD not found.\n"); else get_mac_address(&high_dword, &low_dword, search_address, search_length); if (io_base) { printk(BIOS_DEBUG, "Realtek NIC io_base = 0x%04x\n", io_base); printk(BIOS_DEBUG, "Programming MAC Address\n"); /* Disable register protection */ outb(0xc0, io_base + 0x50); outl(high_dword, io_base); outl(low_dword, io_base + 0x04); outb(0x60, io_base + 54); /* Enable register protection again */ outb(0x00, io_base + 0x50); } }
/** * DHCP: Sends DHCP-Request message. Asks for acknowledgment to occupy IP. */ static void dhcp_send_request(void) { uint32_t packetsize = sizeof(struct iphdr) + sizeof(struct udphdr) + sizeof(struct btphdr); struct btphdr *btph; dhcp_options_t opt; memset(ether_packet, 0, packetsize); btph = (struct btphdr *) (ðer_packet[ sizeof(struct iphdr) + sizeof(struct udphdr)]); btph -> op = 1; btph -> htype = 1; btph -> hlen = 6; memcpy(btph -> chaddr, get_mac_address(), 6); memset(&opt, 0, sizeof(dhcp_options_t)); opt.msg_type = DHCPREQUEST; memcpy(&(opt.requested_IP), &dhcp_own_ip, 4); opt.flag[DHCP_REQUESTED_IP] = 1; memcpy(&(opt.server_ID), &dhcp_server_ip, 4); opt.flag[DHCP_SERVER_ID] = 1; opt.request_list[DHCP_MASK] = 1; opt.request_list[DHCP_DNS] = 1; opt.request_list[DHCP_ROUTER] = 1; opt.request_list[DHCP_TFTP_SERVER] = 1; opt.request_list[DHCP_BOOTFILE] = 1; dhcp_encode_options(btph -> vend, &opt); fill_udphdr(ðer_packet[sizeof(struct iphdr)], sizeof(struct btphdr) + sizeof(struct udphdr), UDPPORT_BOOTPC, UDPPORT_BOOTPS); fill_iphdr(ether_packet, sizeof(struct btphdr) + sizeof(struct udphdr) + sizeof(struct iphdr), IPTYPE_UDP, 0, 0xFFFFFFFF); send_ipv4(ether_packet, packetsize); }
DHCPClient::DHCPClient(BMessenger target, const char* device) : AutoconfigClient("dhcp", target, device), fConfiguration(kMsgConfigureInterface), fRunner(NULL), fLeaseTime(0) { fStartTime = system_time(); fTransactionID = (uint32)fStartTime; fStatus = get_mac_address(device, fMAC); if (fStatus < B_OK) return; memset(&fServer, 0, sizeof(struct sockaddr_in)); fServer.sin_family = AF_INET; fServer.sin_len = sizeof(struct sockaddr_in); fServer.sin_port = htons(DHCP_SERVER_PORT); openlog_thread("DHCP", 0, LOG_DAEMON); }
static void program_mac_address(u16 io_base, u32 search_address, u32 search_length) { /* Default MAC Address of A0:00:BA:D0:0B:AD */ u32 high_dword = 0xD0BA00A0; /* high dword of mac address */ u32 low_dword = 0x0000AD0B; /* low word of mac address as a dword */ if (search_length != -1) get_mac_address(&high_dword, &low_dword, search_address, search_length); if (io_base) { printk(BIOS_DEBUG, "Realtek NIC io_base = 0x%04x\n", io_base); printk(BIOS_DEBUG, "Programming MAC Address\n"); outb(0xc0, io_base + 0x50); /* Disable register protection */ outl(high_dword, io_base); outl(low_dword, io_base + 0x04); outb(0x60, io_base + 54); outb(0x00, io_base + 0x50); /* Enable register protection again */ } }
static gboolean geoclue_localnet_set_address (GeoclueLocalnet *localnet, GHashTable *details, GError **error) { char *str, *mac = NULL; GKeyFile *keyfile; GError *int_err = NULL; localnet_keyfile_group *keyfile_group; Gateway *gw; if (!details) { /* TODO set error */ return FALSE; } if (get_mac_address (&mac) < 0) return FALSE; if (!mac) { g_warning ("Couldn't get current gateway mac address"); /* TODO set error */ return FALSE; } /* reload keyfile just in case it's changed */ keyfile = g_key_file_new (); if (!g_key_file_load_from_file (keyfile, localnet->keyfile_name, G_KEY_FILE_NONE, &int_err)) { g_warning ("Could not load keyfile %s: %s", localnet->keyfile_name, int_err->message); g_error_free (int_err); int_err = NULL; } /* remove old group (if exists) and add new to GKeyFile */ g_key_file_remove_group (keyfile, mac, NULL); keyfile_group = g_new0 (localnet_keyfile_group, 1); keyfile_group->keyfile = keyfile; keyfile_group->group_name = mac; g_hash_table_foreach (details, (GHFunc) add_address_detail_to_keyfile, keyfile_group); g_free (keyfile_group); /* save keyfile*/ str = g_key_file_to_data (keyfile, NULL, &int_err); if (int_err) { g_warning ("Failed to get keyfile data as string: %s", int_err->message); g_error_free (int_err); g_key_file_free (keyfile); g_free (mac); /* TODO set error */ return FALSE; } g_file_set_contents (localnet->keyfile_name, str, -1, &int_err); g_free (str); if (int_err) { g_warning ("Failed to save keyfile: %s", int_err->message); g_error_free (int_err); g_key_file_free (keyfile); g_free (mac); /* TODO set error */ return FALSE; } /* re-parse keyfile */ free_gateway_list (localnet->gateways); localnet->gateways = NULL; geoclue_localnet_load_gateways_from_keyfile (localnet, keyfile); g_key_file_free (keyfile); gw = geoclue_localnet_find_gateway (localnet, mac); g_free (mac); if (gw) { gc_iface_address_emit_address_changed (GC_IFACE_ADDRESS (localnet), time (NULL), gw->address, gw->accuracy); } else { /* empty address -- should emit anyway? */ } return TRUE; }
/* * injection_write_ip * * Description: * - Write an IP packet into the wire. It can use either raw sockets * or the wire * * Inputs: * - ip_packet: the IP packet * * Outputs: * - return: 0 if ok, <0 if there were problems * */ int injection_write_ip (u_char *ip_packet) { #if defined(INJECT_USING_RAW_SOCKETS) || defined(INJECT_USING_LINK_LAYER) int i; u_int16_t packet_size = ntohs(*(u_int16_t*)(ip_packet+2)); #endif #if defined(INJECT_USING_RAW_SOCKETS) int network; /* network initialization */ if ((network = libnet_open_raw_sock(IPPROTO_RAW)) < 0) { return WIRE_ERR_PKTD_INJECTION_OPEN; /* packet injection */ } else if ((i = libnet_write_ip (network, ip_packet, packet_size)) < packet_size) { return WIRE_ERR_PKTD_INJECTION_WRITE_IP; /* shut down the interface */ } else if (libnet_close_raw_sock (network) < 0) { return WIRE_ERR_PKTD_INJECTION_CLOSE; } return WIRE_ERR_NONE; #elif defined(INJECT_USING_LINK_LAYER) char buffer[LIBNET_ETH_H+IP_MAXPACKET]; struct in_addr in; int size = 1024; struct libnet_link_int *network; /* pointer to link interface struct */ char *interface = NULL; /* pointer to the device to use */ struct sockaddr_in sin; char errbuf[1024]; struct ether_addr remote_eth, *tmp_eth; /* network initialization */ if (libnet_select_device(&sin, &interface, errbuf) == -1) { return WIRE_ERR_PKTD_NO_WRITE_DEVICE_ACCESS; } if ((network = libnet_open_link_interface(interface, errbuf)) == NULL) { return WIRE_ERR_PKTD_INJECTION_OPEN; } /* get local ethernet address */ if ((tmp_eth = libnet_get_hwaddr(network, interface, errbuf)) == NULL) { (void)libnet_close_link_interface(network); return WIRE_ERR_PKTD_INJECTION_OPEN; } memcpy (&local_eth, tmp_eth, 6); debug3 ("injection_write_ip: the local ethernet address is %s\n", ether_ntoa(&local_eth)); /* get remote ethernet address (the packet is already in network order) */ in.s_addr = *(u_int32_t*)(ip_packet+16); /* try to get the remote MAC address from the ARP cache */ if (get_mac_address (in, buffer, size) < 0) { /* MAC address of the IP address not in ARP cache */ /* get the gateway needed to reach the destination */ struct in_addr gw; if (get_gateway (in, &gw) < 0) { debug3 ("injection_write_ip: can't find MAC nor gateway for %s\n", inet_ntoa(in)); (void)libnet_close_link_interface(network); return WIRE_ERR_PKTD_INJECTION_WRITE_IP; } /* get the gateway's ethernet address */ if (get_mac_address (gw, buffer, size) < 0) { debug3 ("injection_write_ip: can't find MAC for %s's ", inet_ntoa(in)); debug3 ("gateway (%s)\n", inet_ntoa(gw)); /* XXX: This case means typically the destination host is in * the same network than the source, but the destination MAC * address is not in the local ARP cache. Getting a local * MAC address requires implementing ARP, which we won't do * at this moment */ (void)libnet_close_link_interface(network); return WIRE_ERR_PKTD_INJECTION_WRITE_IP; } debug3 ("injection_write_ip: IP address %s can be reached ", inet_ntoa(in)); debug3 ("through gateway %s (%s)\n", inet_ntoa(gw), buffer); } else { debug3 ("injection_write_ip: IP address %s corresponds to %s\n", inet_ntoa(in), buffer); } if ((tmp_eth = ether_aton (buffer)) == NULL) { (void)libnet_close_link_interface(network); return WIRE_ERR_PKTD_INJECTION_WRITE_IP; } memcpy (&remote_eth, tmp_eth, 6); /* build ethernet header and use IP packet as payload */ #if (defined(bsdi) || defined(__NetBSD__) || defined(__OpenBSD__) ||\ defined(__FreeBSD__)) libnet_build_ethernet(&(remote_eth.octet[0]), &(local_eth.octet[0]), ETHERTYPE_IP, NULL, 0, buffer); #else libnet_build_ethernet(&(remote_eth.ether_addr_octet[0]), &(local_eth.ether_addr_octet[0]), ETHERTYPE_IP, NULL, 0, buffer); #endif memcpy (buffer+LIBNET_ETH_H, ip_packet, packet_size); packet_size += LIBNET_ETH_H; /* inject the packet */ if ((i = libnet_write_link_layer (network, interface, buffer, packet_size)) < packet_size) { (void)libnet_close_link_interface(network); return WIRE_ERR_PKTD_INJECTION_WRITE_IP; } /* shut down the interface */ (void)libnet_close_link_interface(network); return WIRE_ERR_NONE; #else /* INJECT_USING_LINK_LAYER */ return(0); #endif /* INJECT_USING_LINK_LAYER */ }
int main(int argc, char** argv) { uint8_t *payload_buffer; uint32_t num_packets = 0; uint32_t packet_size = 0; uint32_t payload_size = 0; char *file_path; struct lorcon_packet *packet; uint32_t i; int32_t ret; uint32_t mode; uint32_t delay_us; struct timespec start, now; int32_t diff; /* Parse arguments */ if (argc > 4) { printf("Usage: random_packets <file_name> <mode: 0=my MAC, 1=injection MAC> <delay in us>\n"); return 1; } if (argc < 4 || (1 != sscanf(argv[3], "%u", &delay_us))) { delay_us = 0; } if (argc < 3 || (1 != sscanf(argv[2], "%u", &mode))) { mode = 0; } else if (mode > 1) { printf("Usage: random_packets <file_name> <mode: 0=my MAC, 1=injection MAC> <delay in us>\n"); return 1; } if (argc < 2 || strlen(argv[1]) == 0) { printf("Usage: random_packets <file_name> <mode: 0=my MAC, 1=injection MAC> <delay in us>\n"); return 1; } else { file_path = argv[1]; } /* Generate packet payloads */ printf("Generating packet payload from file: %s \n", file_path); generate_payload_from_file(file_path, &payload_buffer, &payload_size); printf("Read payload, size is: %d\n", payload_size); // Set packet size and number of packets if (payload_size > MAX_PACKET_SIZE) { packet_size = MAX_PACKET_SIZE; num_packets = ceil((float) payload_size / (float) MAX_PACKET_SIZE); } else { packet_size = payload_size; num_packets = 1; } /* Setup the interface for lorcon */ printf("Initializing LORCON\n"); init_lorcon(); /* Allocate packet */ packet = malloc(sizeof(*packet) + packet_size); if (!packet) { perror("malloc packet"); exit(1); } packet->fc = (0x08 /* Data frame */ | (0x0 << 8) /* Not To-DS */); packet->dur = 0xffff; if (mode == 0) { memcpy(packet->addr1, "\x00\x16\xea\x12\x34\x56", 6); get_mac_address(packet->addr2, "mon0"); memcpy(packet->addr3, "\x00\x16\xea\x12\x34\x56", 6); } else if (mode == 1) { memcpy(packet->addr1, "\x00\x16\xea\x12\x34\x56", 6); memcpy(packet->addr2, "\x00\x16\xea\x12\x34\x56", 6); memcpy(packet->addr3, "\xff\xff\xff\xff\xff\xff", 6); } packet->seq = 0; tx_packet.packet = (uint8_t *)packet; tx_packet.plen = sizeof(*packet) + packet_size; /* Send packets */ printf("Sending %u packets of size %u (. every thousand)\n", num_packets, packet_size); if (delay_us) { /* Get start time */ clock_gettime(CLOCK_MONOTONIC, &start); } for (i = 0; i < num_packets; ++i) { if (i == (num_packets - 1)) { printf("final packet size: %d\n", (payload_size - i * packet_size)); memcpy(packet->payload, (payload_buffer + (i * packet_size)), (payload_size - i * packet_size)); tx_packet.plen = sizeof(*packet) + (payload_size - i * packet_size); } else { memcpy(packet->payload, (payload_buffer + (i * packet_size)), packet_size); } if (delay_us) { clock_gettime(CLOCK_MONOTONIC, &now); diff = (now.tv_sec - start.tv_sec) * 1000000 + (now.tv_nsec - start.tv_nsec + 500) / 1000; diff = delay_us*i - diff; if (diff > 0 && diff < delay_us) usleep(diff); } ret = tx80211_txpacket(&tx, &tx_packet); if (ret < 0) { fprintf(stderr, "Unable to transmit packet: %s\n", tx.errstr); exit(1); } if (((i+1) % 1000) == 0) { printf("."); fflush(stdout); } if (((i+1) % 50000) == 0) { printf("%dk\n", (i+1)/1000); fflush(stdout); } } return 0; }
/* init_ll_socket */ ll_socket_t *init_ll_socket ( const bool is_transmitter, const int tx_delay, const char *ll_if_name, const int ll_sap, const int frame_type ) { #ifdef KERNEL_RING int tx_socket_fd = -1, rx_socket_fd = -1; #else int socket_fd = -1; #endif int ll_if_index = -1; ll_socket_t *s = new_ll_socket(); s->state = LL_SOCKET_STATE_UNDEF; // 1) create RAW socket(s) #ifdef KERNEL_RING if ( ( tx_socket_fd = socket(AF_PACKET, SOCK_RAW, ll_sap) ) < 0 ) { handle_sys_error("Could not open TX socket"); } if ( ( rx_socket_fd = socket(AF_PACKET, SOCK_RAW, ll_sap) ) < 0 ) { handle_sys_error("Could not open RX socket"); } #else if ( ( socket_fd = socket(AF_PACKET, SOCK_RAW, ll_sap) ) < 0 ) { handle_sys_error("Could not open socket"); } #endif /* int so_broadcast=1; int z = setsockopt(socket_fd,SOL_SOCKET,SO_BROADCAST,&so_broadcast,sizeof so_broadcast); printf("nome socket %d \n",socket_fd); if ( z )perror("setsockopt(2)");//If the setsockopt(2) function returns zero, the socket s has been enabled to perform broadcasting //printf(socket_fd); */ // 2) initialize fields #ifdef KERNEL_RING s->tx_socket_fd = tx_socket_fd; s->rx_socket_fd = rx_socket_fd; #else s->socket_fd = socket_fd; s->buffer = new_ll_framebuffer(); #endif s->ll_sap = ll_sap; s->frame_type = frame_type; s->tx_delay = tx_delay; #ifdef KERNEL_RING log_app_msg("Socket created, TX_FD = %d, RX_FD = %d, ll_sap = %d\n", tx_socket_fd, rx_socket_fd, ll_sap); #else log_app_msg("Socket created, FD = %d, ll_sap = %d\n", socket_fd, ll_sap); #endif // 3) get interface index from interface name #ifdef KERNEL_RING int socket_fd = tx_socket_fd; #endif //if ( ( ll_if_index = if_name_2_if_index(socket_fd, ll_if_name) ) < 0 ) //cambio if ((ll_if_index=if_nametoindex(ll_if_name))<0) { handle_app_error("Could not get index, if_name = %s\n", ll_if_name); } // strncpy(s->if_name, ll_if_name, strlen(ll_if_name)); s->if_index = ll_if_index; //printf("%s %d\n", ll_if_name,s->if_index); //int j=1; //printf(ll_if_index); // 4) get interface MAC address from interface name //if (is_transmitter){ if ( get_mac_address (socket_fd, ll_if_name, (unsigned char *)s->if_mac) < 0 ) { handle_app_error( "Could not get MAC address, if_name = %s\n" , ll_if_name ); }//} log_app_msg("IF: name = %s, index = %d, MAC = ", ll_if_name, ll_if_index); print_eth_address((unsigned char *)s->if_mac); log_app_msg("\n"); // 5) initialize events if ( init_events(is_transmitter, s) < 0 ) { handle_app_error("Could not initialize event manager!"); } printf("volvo de init_events\n"); print_eth_address(s->if_mac); // Ready is socket's final state s->state = LL_SOCKET_STATE_READY; return(s); }
int main(int argc, char** argv) { uint32_t send_sec; uint32_t packet_size; struct lorcon_packet *packet; uint32_t i; int32_t ret; uint32_t mode; uint32_t delay_us; struct timespec start, now; int32_t diff; /* Parse arguments */ if (argc > 5) { printf("Usage: random_packets <number> <length> <mode: 0=my MAC, 1=injection MAC> <delay in us>\n"); return 1; } if (argc < 5 || (1 != sscanf(argv[4], "%u", &delay_us))) { delay_us = 0; } if (argc < 4 || (1 != sscanf(argv[3], "%u", &mode))) { mode = 0; printf("Usage: random_packets <number> <length> <mode: 0=my MAC, 1=injection MAC> <delay in us>\n"); } else if (mode > 1) { printf("Usage: random_packets <number> <length> <mode: 0=my MAC, 1=injection MAC> <delay in us>\n"); return 1; } if (argc < 3 || (1 != sscanf(argv[2], "%u", &packet_size))) packet_size = 2200; if (argc < 2 || (1 != sscanf(argv[1], "%u", &send_sec))) send_sec = 10000; /* Generate packet payloads */ //printf("Generating packet payloads \n"); payload_buffer = malloc(PAYLOAD_SIZE); if (payload_buffer == NULL) { perror("malloc payload buffer"); exit(1); } generate_payloads(payload_buffer, PAYLOAD_SIZE); /* Setup the interface for lorcon */ //printf("Initializing LORCON\n"); init_lorcon(); /* Allocate packet */ packet = malloc(sizeof(*packet) + packet_size); if (!packet) { perror("malloc packet"); exit(1); } packet->fc = (0x08 /* Data frame */ | (0x0 << 8) /* Not To-DS */); packet->dur = 0xffff; if (mode == 0) { memcpy(packet->addr1, "\x00\x16\xea\x12\x34\x56", 6); get_mac_address(packet->addr2, "mon1"); memcpy(packet->addr3, "\x00\x16\xea\x12\x34\x56", 6); } else if (mode == 1) { memcpy(packet->addr1, "\x00\x16\xea\x12\x34\x56", 6); memcpy(packet->addr2, "\x00\x16\xea\x12\x34\x56", 6); memcpy(packet->addr3, "\xff\xff\xff\xff\xff\xff", 6); } packet->seq = 0; tx_packet.packet = (uint8_t *)packet; tx_packet.plen = sizeof(*packet) + packet_size; /* Send packets */ //printf("Sending packets of size %u for %d sec...\n", packet_size, send_sec); if (delay_us) { /* Get start time */ clock_gettime(CLOCK_MONOTONIC, &start); } i = 0; int cur_sec = 0; double cur_pkt_msec = 0; clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &now); //for (i = 0; i < send_sec; ++i) { while(cur_sec < send_sec) { payload_memcpy(packet->payload, packet_size, (i*packet_size) % PAYLOAD_SIZE); clock_gettime(CLOCK_MONOTONIC, &now); int sub_time = (int)(now.tv_nsec * 1e-9 + now.tv_sec - start.tv_nsec * 1e-9 - start.tv_sec); if (sub_time > cur_sec) { cur_sec = sub_time; //printf("time: %d\n", (now.tv_nsec - start.tv_nsec) * 1e-9); printf("time now: %d\n", cur_sec); } /* double sub_pkt_msec = (now.tv_nsec - start.tv_nsec) / 1e6 + (now.tv_sec - start.tv_sec) * 1e3; if (sub_pkt_msec > cur_pkt_msec + 0.25) { cur_pkt_msec = sub_pkt_msec; } else { continue; } */ if (delay_us) { clock_gettime(CLOCK_MONOTONIC, &now); diff = (now.tv_sec - start.tv_sec) * 1000000 + (now.tv_nsec - start.tv_nsec + 500) / 1000; diff = delay_us*i - diff; if (diff > 0 && diff < delay_us) usleep(diff); } ret = tx80211_txpacket(&tx, &tx_packet); if (ret < 0) { fprintf(stderr, "Unable to transmit packet: %s\n", tx.errstr); exit(1); } i++; if (((i+1) % 1000) == 0) { //printf("."); fflush(stdout); } if (((i+1) % 50000) == 0) { //printf("%dk\n", (i+1)/1000); fflush(stdout); } } printf("total packet sent: %d\n", i); return 0; }
int main(int argc, char * argv[]) { int a_flag = 0; struct ether_addr AP_mac; int ch; boolean_t disassociate = FALSE; const char * if_name = NULL; boolean_t has_wireless; const char * key_str = NULL; const char * network = NULL; int scan_current_ssid = FALSE; struct sockaddr_dl w; wireless_t wref; while ((ch = getopt(argc, argv, "adhHi:k:sx:")) != EOF) { switch ((char)ch) { case 'a': a_flag = 1; break; case 'h': case 'H': EAPLOG(LOG_ERR, "usage: wireless [ -i <interface> ] ( -d | -k | -x <ssid> | -s [ -a ])\n"); exit(0); break; case 'x': /* join network */ network = optarg; break; case 'k': /* set the wireless key */ key_str = optarg; break; case 'd': disassociate = TRUE; break; case 'i': /* specify the interface */ if_name = optarg; break; case 's': scan_current_ssid = TRUE; break; default: break; } } if (if_name != NULL) { if (wireless_bind(if_name, &wref) == FALSE) { printf("interface '%s' is not present or not AirPort\n", if_name); exit(1); } } else if ((if_name = wireless_first(&wref)) == NULL) { printf("no AirPort card\n"); exit(0); } get_mac_address(if_name, &w); printf("AirPort: %s %s\n", if_name, ether_ntoa((struct ether_addr *)(w.sdl_data + w.sdl_nlen))); if (wireless_ap_mac(wref, &AP_mac) == FALSE) { printf("Not associated\n"); } else { CFStringRef ssid; printf("Access Point: %s\n", ether_ntoa(&AP_mac)); ssid = wireless_copy_ssid_string(wref); if (ssid != NULL) { printf("SSID: "); fflush(stdout); CFShow(ssid); fflush(stderr); } if (wireless_is_wpa_enterprise(wref) == TRUE) { printf("WPA Enterprise\n"); } else { printf("Not WPA Enterprise\n"); } if (disassociate) { wireless_disassociate(wref); goto done; } else if (scan_current_ssid) { if (a_flag) { if (wireless_async_scan_ssid(wref, ssid)) { CFRunLoopObserverContext context = { 0, NULL, NULL, NULL, NULL }; CFRunLoopObserverRef observer; struct ssid_wref ref; ref.ssid = ssid; ref.wref = wref; context.info = &ref; observer = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, TRUE, 0, before_blocking, &context); if (observer != NULL) { CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode); } else { EAPLOG(LOG_ERR, "start_initialization: " "CFRunLoopObserverCreate failed!"); } CFRunLoopRun(); } else { exit(1); } } else { wireless_scan_ssid(wref, ssid); } } my_CFRelease(&ssid); } if (key_str) { uint8_t key[13]; int key_len; int hex_len = strlen(key_str); if (hex_len & 0x1) { EAPLOG(LOG_ERR, "invalid key, odd number of hex bytes\n"); exit(1); } key_len = hex_len / 2; switch (key_len) { case 5: case 13: hexstrtobin(key_str, hex_len, key, key_len); if (wireless_set_key(wref, 0, 0, key, key_len) == FALSE) { EAPLOG(LOG_ERR, "wireless_set_key failed\n"); } break; default: EAPLOG(LOG_ERR, "invalid key length %d," " must be 5 or 13 hex bytes\n", key_len); exit(1); break; } } else if (network != NULL) { CFDataRef data; CFStringRef ssid_str; data = CFDataCreateWithBytesNoCopy(NULL, (const UInt8 *)network, strlen(network), kCFAllocatorNull); ssid_str = ssid_string_from_data(data); EAPLOG(LOG_ERR, "attempting to join network '%s'\n", network); if (wireless_join(wref, ssid_str) == FALSE) { EAPLOG(LOG_ERR, "wireless_join failed\n"); } } done: wireless_free(wref); exit(0); return (0); }
int main(int argc, char *argv[]) { unsigned i; int err; struct igb_dma_alloc a_page; struct igb_packet a_packet; struct igb_packet *tmp_packet; struct igb_packet *cleaned_packets; struct igb_packet *free_packets; int c; u_int64_t last_time; int rc = 0; char *interface = NULL; int class_a_id = 0; int a_priority = 0; u_int16_t a_vid = 0; #ifdef DOMAIN_QUERY int class_b_id = 0; int b_priority = 0; u_int16_t b_vid = 0; #endif int seqnum; int time_stamp; unsigned total_samples = 0; gPtpTimeData td; int32_t sample_buffer[SAMPLES_PER_FRAME * SRC_CHANNELS]; seventeen22_header *header0; six1883_header *header1; six1883_sample *sample; uint64_t now_local, now_8021as; uint64_t update_8021as; unsigned delta_8021as, delta_local; long double ml_ratio; for (;;) { c = getopt(argc, argv, "hi:"); if (c < 0) break; switch (c) { case 'h': usage(); break; case 'i': if (interface) { printf ("only one interface per daemon is supported\n"); usage(); } interface = strdup(optarg); break; } } if (optind < argc) usage(); if (NULL == interface) { usage(); } rc = mrp_connect(); if (rc) { printf("socket creation failed\n"); return (errno); } err = pci_connect(); if (err) { printf("connect failed (%s) - are you running as root?\n", strerror(errno)); return (errno); } err = igb_init(&igb_dev); if (err) { printf("init failed (%s) - is the driver really loaded?\n", strerror(errno)); return (errno); } err = igb_dma_malloc_page(&igb_dev, &a_page); if (err) { printf("malloc failed (%s) - out of memory?\n", strerror(errno)); return (errno); } signal(SIGINT, sigint_handler); rc = get_mac_address(interface); if (rc) { printf("failed to open interface\n"); usage(); } mrp_monitor(); #ifdef DOMAIN_QUERY /* * should use mrp_get_domain() above but this is a simplification */ #endif domain_a_valid = 1; class_a_id = MSRP_SR_CLASS_A; a_priority = MSRP_SR_CLASS_A_PRIO; a_vid = 2; printf("detected domain Class A PRIO=%d VID=%04x...\n", a_priority, a_vid); #define PKT_SZ 100 mrp_register_domain(&class_a_id, &a_priority, &a_vid); igb_set_class_bandwidth(&igb_dev, PACKET_IPG / 125000, 0, PKT_SZ - 22, 0); memset(STREAM_ID, 0, sizeof(STREAM_ID)); memcpy(STREAM_ID, STATION_ADDR, sizeof(STATION_ADDR)); a_packet.dmatime = a_packet.attime = a_packet.flags = 0; a_packet.map.paddr = a_page.dma_paddr; a_packet.map.mmap_size = a_page.mmap_size; a_packet.offset = 0; a_packet.vaddr = a_page.dma_vaddr + a_packet.offset; a_packet.len = PKT_SZ; free_packets = NULL; seqnum = 0; /* divide the dma page into buffers for packets */ for (i = 1; i < ((a_page.mmap_size) / PKT_SZ); i++) { tmp_packet = malloc(sizeof(struct igb_packet)); if (NULL == tmp_packet) { printf("failed to allocate igb_packet memory!\n"); return (errno); } *tmp_packet = a_packet; tmp_packet->offset = (i * PKT_SZ); tmp_packet->vaddr += tmp_packet->offset; tmp_packet->next = free_packets; memset(tmp_packet->vaddr, 0, PKT_SZ); /* MAC header at least */ memcpy(tmp_packet->vaddr, DEST_ADDR, sizeof(DEST_ADDR)); memcpy(tmp_packet->vaddr + 6, STATION_ADDR, sizeof(STATION_ADDR)); /* Q-tag */ ((char *)tmp_packet->vaddr)[12] = 0x81; ((char *)tmp_packet->vaddr)[13] = 0x00; ((char *)tmp_packet->vaddr)[14] = ((a_priority << 13 | a_vid)) >> 8; ((char *)tmp_packet->vaddr)[15] = ((a_priority << 13 | a_vid)) & 0xFF; ((char *)tmp_packet->vaddr)[16] = 0x22; /* 1722 eth type */ ((char *)tmp_packet->vaddr)[17] = 0xF0; /* 1722 header update + payload */ header0 = (seventeen22_header *) (((char *)tmp_packet->vaddr) + 18); header0->cd_indicator = 0; header0->subtype = 0; header0->sid_valid = 1; header0->version = 0; header0->reset = 0; header0->reserved0 = 0; header0->gateway_valid = 0; header0->reserved1 = 0; header0->timestamp_uncertain = 0; memset(&(header0->stream_id), 0, sizeof(header0->stream_id)); memcpy(&(header0->stream_id), STATION_ADDR, sizeof(STATION_ADDR)); header0->length = htons(32); header1 = (six1883_header *) (header0 + 1); header1->format_tag = 1; header1->packet_channel = 0x1F; header1->packet_tcode = 0xA; header1->app_control = 0x0; header1->reserved0 = 0; header1->source_id = 0x3F; header1->data_block_size = 1; header1->fraction_number = 0; header1->quadlet_padding_count = 0; header1->source_packet_header = 0; header1->reserved1 = 0; header1->eoh = 0x2; header1->format_id = 0x10; header1->format_dependent_field = 0x02; header1->syt = 0xFFFF; tmp_packet->len = 18 + sizeof(seventeen22_header) + sizeof(six1883_header) + (SAMPLES_PER_FRAME * CHANNELS * sizeof(six1883_sample)); free_packets = tmp_packet; } /* * subtract 16 bytes for the MAC header/Q-tag - pktsz is limited to the * data payload of the ethernet frame . * * IPG is scaled to the Class (A) observation interval of packets per 125 usec */ fprintf(stderr, "advertising stream ...\n"); mrp_advertise_stream(STREAM_ID, DEST_ADDR, a_vid, PKT_SZ - 16, PACKET_IPG / 125000, a_priority, 3900); fprintf(stderr, "awaiting a listener ...\n"); mrp_await_listener(STREAM_ID); printf("got a listener ...\n"); halt_tx = 0; gptpinit(); gptpscaling(&td); if( igb_get_wallclock( &igb_dev, &now_local, NULL ) != 0 ) { fprintf( stderr, "Failed to get wallclock time\n" ); return -1; } update_8021as = td.local_time - td.ml_phoffset; delta_local = (unsigned)(now_local - td.local_time); ml_ratio = -1 * (((long double)td.ml_freqoffset) / 1000000000000) + 1; delta_8021as = (unsigned)(ml_ratio * delta_local); now_8021as = update_8021as + delta_8021as; last_time = now_local + XMIT_DELAY; time_stamp = now_8021as + RENDER_DELAY; rc = nice(-20); while (listeners && !halt_tx) { tmp_packet = free_packets; if (NULL == tmp_packet) goto cleanup; header0 = (seventeen22_header *) (((char *)tmp_packet->vaddr) + 18); header1 = (six1883_header *) (header0 + 1); free_packets = tmp_packet->next; /* unfortuntely unless this thread is at rtprio * you get pre-empted between fetching the time * and programming the packet and get a late packet */ tmp_packet->attime = last_time + PACKET_IPG; last_time += PACKET_IPG; get_samples(SAMPLES_PER_FRAME, sample_buffer); header0->seq_number = seqnum++; if (seqnum % 4 == 0) header0->timestamp_valid = 0; else header0->timestamp_valid = 1; time_stamp = htonl(time_stamp); header0->timestamp = time_stamp; time_stamp = ntohl(time_stamp); time_stamp += PACKET_IPG; header1->data_block_continuity = total_samples; total_samples += SAMPLES_PER_FRAME*CHANNELS; sample = (six1883_sample *) (((char *)tmp_packet->vaddr) + (18 + sizeof(seventeen22_header) + sizeof(six1883_header))); for (i = 0; i < SAMPLES_PER_FRAME * CHANNELS; ++i) { uint32_t tmp = htonl(sample_buffer[i]); sample[i].label = 0x40; memcpy(&(sample[i].value), &(tmp), sizeof(sample[i].value)); } err = igb_xmit(&igb_dev, 0, tmp_packet); if (!err) { continue; } if (ENOSPC == err) { /* put back for now */ tmp_packet->next = free_packets; free_packets = tmp_packet; } cleanup: igb_clean(&igb_dev, &cleaned_packets); i = 0; while (cleaned_packets) { i++; tmp_packet = cleaned_packets; cleaned_packets = cleaned_packets->next; tmp_packet->next = free_packets; free_packets = tmp_packet; } } rc = nice(0); if (halt_tx == 0) printf("listener left ...\n"); halt_tx = 1; mrp_unadvertise_stream(STREAM_ID, DEST_ADDR, a_vid, PKT_SZ - 16, PACKET_IPG / 125000, a_priority, 3900); igb_set_class_bandwidth(&igb_dev, 0, 0, 0, 0); /* disable Qav */ rc = mrp_disconnect(); igb_dma_free_page(&igb_dev, &a_page); err = igb_detach(&igb_dev); pthread_exit(NULL); return (0); }