void ClientHandler::addClient(Ethernet *packet) { switch (packet->getEther_type()) { case ETHERTYPE_ARP: { ARP<Ethernet> arp(*packet); addClient(arp.getSha(), arp.getSpa(), (userMac.compare(arp.getSha().c_str())) ? false : true); addClient(arp.getTha(), arp.getTpa(), (userMac.compare(arp.getTha().c_str())) ? false : true); break; } case ETHERTYPE_IP: { IP<Ethernet> ip(*packet); addClient(ip.getEther_shost(), ip.getIpSrc(), (userMac.compare(ip.getEther_dhost().c_str())) ? false : true); addClient(ip.getEther_dhost(), ip.getIpDst(), (userMac.compare(ip.getEther_shost().c_str())) ? false : true); break; } case ETHERTYPE_IPV6: { IPV6<Ethernet> ipv6(*packet); addClient(ipv6.getEther_shost(), ipv6.getIp6Src(), (userMac.compare(ipv6.getEther_dhost().c_str())) ? false : true); addClient(ipv6.getEther_dhost(), ipv6.getIp6Dest(), (userMac.compare(ipv6.getEther_shost().c_str())) ? false : true); break; } default: { addClient(packet->getEther_shost(), (userMac.compare(packet->getEther_dhost().c_str())) ? false : true); addClient(packet->getEther_dhost(), (userMac.compare(packet->getEther_shost().c_str())) ? false : true); break; } } }
ArPoseWithTime RosArnlNode::rosPoseStampedToArPoseWithTime(const geometry_msgs::PoseStamped& p) { ArPoseWithTime arp(rosPoseToArPose(p)); ArTime t; t.setSec(p.header.stamp.sec); t.setMSec(p.header.stamp.nsec * 1.0e-6); arp.setTime(t); return arp; }
EthernetII ARP::make_arp_reply(ipaddress_type target, ipaddress_type sender, const hwaddress_type &hw_tgt, const hwaddress_type &hw_snd) { /* Create ARP packet and set its attributes */ ARP arp(target, sender, hw_tgt, hw_snd); arp.opcode(REPLY); /* Create the EthernetII PDU with the ARP PDU as its inner PDU */ return EthernetII(hw_tgt, hw_snd) / arp; }
bool GraphicsLayerAndroid::paintContext(SkPicture* context, const IntRect& rect) { SkAutoPictureRecord arp(context, rect.width(), rect.height()); SkCanvas* canvas = arp.getRecordingCanvas(); if (!canvas) return false; PlatformGraphicsContext platformContext(canvas); GraphicsContext graphicsContext(&platformContext); paintGraphicsLayerContents(graphicsContext, rect); return true; }
void EthernetProtocol::send(IPv4Packet ipv4Packet) { ArpProtocol arp(mDevice); MacAddress destinationMac; IPv4Address destinationIPv4 = ipv4Packet.getDestinationAddress(); if (destinationIPv4.isInRange(mDevice->getNetworkAddress(), mDevice->getMask())) { destinationMac = arp.resolveMac(destinationIPv4); } else { destinationMac = arp.resolveMac(mDevice->getGatway()); } EthernetFrame ethernetFrame(mDevice->getMac(), destinationMac); ethernetFrame.setPayload(ipv4Packet); mDevice->sendEthernet(ethernetFrame); }
int arpResolve(pcs *pc, u_int ip, u_char *dmac) { int i, c; struct packet *m; int waittime = 1000; struct timeval tv; c = 0; for (i = 0; i < POOL_SIZE; i++) { if (pc->ipmac4[i].ip == ip && (time_tick - pc->ipmac4[i].timeout) <= 120 && !etherIsZero(pc->ipmac4[i].mac)) { memcpy(dmac, pc->ipmac4[i].mac, ETH_ALEN); return 1; } } while (c++ < 3){ m = arp(pc, ip); if (m == NULL) { printf("out of memory\n"); return 0; } enq(&pc->oq, m); gettimeofday(&(tv), (void*)0); while (!timeout(tv, waittime)) { delay_ms(1); for (i = 0; i < POOL_SIZE; i++) { if (pc->ipmac4[i].ip == ip && (time_tick - pc->ipmac4[i].timeout) <= 120 && !etherIsZero(pc->ipmac4[i].mac)) { memcpy(dmac, pc->ipmac4[i].mac, ETH_ALEN); return 1; } } } } return 0; }
int process(char *packet) { struct s_ethernet *eth; /* the ethernet header */ char *payload; /* the IP header + packet payload */ /* parse ethernet header */ eth = (struct s_ethernet *) (packet); payload = packet + sizeof(struct s_ethernet); switch (htons(eth->type)) { case ETHERTYPE_IP: return ipv4(eth, payload); case ETHERTYPE_IPV6: return ipv6(eth, payload); case ETHERTYPE_ARP: log_debug("HW Protocol: ARP"); return arp(eth, payload); default: log_debug("HW Protocol: unknown [%d/0x%04x]", htons(eth->type), htons(eth->type)); return 1; } }
int zcip_main(int argc UNUSED_PARAM, char **argv) { int state; char *r_opt; unsigned opts; // ugly trick, but I want these zeroed in one go struct { const struct in_addr null_ip; const struct ether_addr null_addr; struct in_addr ip; struct ifreq ifr; int timeout_ms; /* must be signed */ unsigned conflicts; unsigned nprobes; unsigned nclaims; int ready; } L; #define null_ip (L.null_ip ) #define null_addr (L.null_addr ) #define ip (L.ip ) #define ifr (L.ifr ) #define timeout_ms (L.timeout_ms) #define conflicts (L.conflicts ) #define nprobes (L.nprobes ) #define nclaims (L.nclaims ) #define ready (L.ready ) memset(&L, 0, sizeof(L)); INIT_G(); #define FOREGROUND (opts & 1) #define QUIT (opts & 2) // parse commandline: prog [options] ifname script // exactly 2 args; -v accumulates and implies -f opt_complementary = "=2:vv:vf"; opts = getopt32(argv, "fqr:p:v", &r_opt, &pidfile, &verbose); #if !BB_MMU // on NOMMU reexec early (or else we will rerun things twice) if (!FOREGROUND) bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv); #endif // open an ARP socket // (need to do it before openlog to prevent openlog from taking // fd 3 (sock_fd==3)) xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd); if (!FOREGROUND) { // do it before all bb_xx_msg calls openlog(applet_name, 0, LOG_DAEMON); logmode |= LOGMODE_SYSLOG; } if (opts & 4) { // -r n.n.n.n if (inet_aton(r_opt, &ip) == 0 || (ntohl(ip.s_addr) & IN_CLASSB_NET) != LINKLOCAL_ADDR ) { bb_error_msg_and_die("invalid link address"); } } argv += optind - 1; /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */ /* We need to make space for script argument: */ argv[0] = argv[1]; argv[1] = argv[2]; /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */ #define argv_intf (argv[0]) xsetenv("interface", argv_intf); // initialize the interface (modprobe, ifup, etc) if (run(argv, "init", NULL)) return EXIT_FAILURE; // initialize saddr // saddr is: { u16 sa_family; u8 sa_data[14]; } //memset(&saddr, 0, sizeof(saddr)); //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?! safe_strncpy(saddr.sa_data, argv_intf, sizeof(saddr.sa_data)); // bind to the interface's ARP socket xbind(sock_fd, &saddr, sizeof(saddr)); // get the interface's ethernet address //memset(&ifr, 0, sizeof(ifr)); strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf); xioctl(sock_fd, SIOCGIFHWADDR, &ifr); memcpy(ð_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN); // start with some stable ip address, either a function of // the hardware address or else the last address we used. // we are taking low-order four bytes, as top-order ones // aren't random enough. // NOTE: the sequence of addresses we try changes only // depending on when we detect conflicts. { uint32_t t; move_from_unaligned32(t, ((char *)ð_addr + 2)); srand(t); } if (ip.s_addr == 0) ip.s_addr = pick(); // FIXME cases to handle: // - zcip already running! // - link already has local address... just defend/update // daemonize now; don't delay system startup if (!FOREGROUND) { #if BB_MMU bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/); #endif if (verbose) bb_info_msg("start, interface %s", argv_intf); } write_pidfile(pidfile); bb_signals(BB_FATAL_SIGS, cleanup); // run the dynamic address negotiation protocol, // restarting after address conflicts: // - start with some address we want to try // - short random delay // - arp probes to see if another host uses it // - arp announcements that we're claiming it // - use it // - defend it, within limits // exit if: // - address is successfully obtained and -q was given: // run "<script> config", then exit with exitcode 0 // - poll error (when does this happen?) // - read error (when does this happen?) // - sendto error (in arp()) (when does this happen?) // - revents & POLLERR (link down). run "<script> deconfig" first state = PROBE; while (1) { struct pollfd fds[1]; unsigned deadline_us; struct arp_packet p; int source_ip_conflict; int target_ip_conflict; fds[0].fd = sock_fd; fds[0].events = POLLIN; fds[0].revents = 0; // poll, being ready to adjust current timeout if (!timeout_ms) { timeout_ms = random_delay_ms(PROBE_WAIT); // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to // make the kernel filter out all packets except // ones we'd care about. } // set deadline_us to the point in time when we timeout deadline_us = MONOTONIC_US() + timeout_ms * 1000; VDBG("...wait %d %s nprobes=%u, nclaims=%u\n", timeout_ms, argv_intf, nprobes, nclaims); switch (safe_poll(fds, 1, timeout_ms)) { default: //bb_perror_msg("poll"); - done in safe_poll cleanup(EXIT_FAILURE); // timeout case 0: VDBG("state = %d\n", state); switch (state) { case PROBE: // timeouts in the PROBE state mean no conflicting ARP packets // have been received, so we can progress through the states if (nprobes < PROBE_NUM) { nprobes++; VDBG("probe/%u %s@%s\n", nprobes, argv_intf, inet_ntoa(ip)); arp(/* ARPOP_REQUEST, */ /* ð_addr, */ null_ip, &null_addr, ip); timeout_ms = PROBE_MIN * 1000; timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN); } else { // Switch to announce state. state = ANNOUNCE; nclaims = 0; VDBG("announce/%u %s@%s\n", nclaims, argv_intf, inet_ntoa(ip)); arp(/* ARPOP_REQUEST, */ /* ð_addr, */ ip, ð_addr, ip); timeout_ms = ANNOUNCE_INTERVAL * 1000; } break; case RATE_LIMIT_PROBE: // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets // have been received, so we can move immediately to the announce state state = ANNOUNCE; nclaims = 0; VDBG("announce/%u %s@%s\n", nclaims, argv_intf, inet_ntoa(ip)); arp(/* ARPOP_REQUEST, */ /* ð_addr, */ ip, ð_addr, ip); timeout_ms = ANNOUNCE_INTERVAL * 1000; break; case ANNOUNCE: // timeouts in the ANNOUNCE state mean no conflicting ARP packets // have been received, so we can progress through the states if (nclaims < ANNOUNCE_NUM) { nclaims++; VDBG("announce/%u %s@%s\n", nclaims, argv_intf, inet_ntoa(ip)); arp(/* ARPOP_REQUEST, */ /* ð_addr, */ ip, ð_addr, ip); timeout_ms = ANNOUNCE_INTERVAL * 1000; } else { // Switch to monitor state. state = MONITOR; // link is ok to use earlier // FIXME update filters run(argv, "config", &ip); ready = 1; conflicts = 0; timeout_ms = -1; // Never timeout in the monitor state. // NOTE: all other exit paths // should deconfig ... if (QUIT) cleanup(EXIT_SUCCESS); } break; case DEFEND: // We won! No ARP replies, so just go back to monitor. state = MONITOR; timeout_ms = -1; conflicts = 0; break; default: // Invalid, should never happen. Restart the whole protocol. state = PROBE; ip.s_addr = pick(); timeout_ms = 0; nprobes = 0; nclaims = 0; break; } // switch (state) break; // case 0 (timeout) // packets arriving, or link went down case 1: // We need to adjust the timeout in case we didn't receive // a conflicting packet. if (timeout_ms > 0) { unsigned diff = deadline_us - MONOTONIC_US(); if ((int)(diff) < 0) { // Current time is greater than the expected timeout time. // Should never happen. VDBG("missed an expected timeout\n"); timeout_ms = 0; } else { VDBG("adjusting timeout\n"); timeout_ms = (diff / 1000) | 1; /* never 0 */ } } if ((fds[0].revents & POLLIN) == 0) { if (fds[0].revents & POLLERR) { // FIXME: links routinely go down; // this shouldn't necessarily exit. bb_error_msg("iface %s is down", argv_intf); if (ready) { run(argv, "deconfig", &ip); } cleanup(EXIT_FAILURE); } continue; } // read ARP packet if (safe_read(sock_fd, &p, sizeof(p)) < 0) { bb_perror_msg(bb_msg_read_error); cleanup(EXIT_FAILURE); } if (p.eth.ether_type != htons(ETHERTYPE_ARP)) continue; #ifdef DEBUG { struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha; struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha; struct in_addr *spa = (struct in_addr *) p.arp.arp_spa; struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa; VDBG("%s recv arp type=%d, op=%d,\n", argv_intf, ntohs(p.eth.ether_type), ntohs(p.arp.arp_op)); VDBG("\tsource=%s %s\n", ether_ntoa(sha), inet_ntoa(*spa)); VDBG("\ttarget=%s %s\n", ether_ntoa(tha), inet_ntoa(*tpa)); } #endif if (p.arp.arp_op != htons(ARPOP_REQUEST) && p.arp.arp_op != htons(ARPOP_REPLY)) continue; source_ip_conflict = 0; target_ip_conflict = 0; if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr)) == 0 && memcmp(&p.arp.arp_sha, ð_addr, ETH_ALEN) != 0 ) { source_ip_conflict = 1; } if (p.arp.arp_op == htons(ARPOP_REQUEST) && memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0 && memcmp(&p.arp.arp_tha, ð_addr, ETH_ALEN) != 0 ) { target_ip_conflict = 1; } VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n", state, source_ip_conflict, target_ip_conflict); switch (state) { case PROBE: case ANNOUNCE: // When probing or announcing, check for source IP conflicts // and other hosts doing ARP probes (target IP conflicts). if (source_ip_conflict || target_ip_conflict) { conflicts++; if (conflicts >= MAX_CONFLICTS) { VDBG("%s ratelimit\n", argv_intf); timeout_ms = RATE_LIMIT_INTERVAL * 1000; state = RATE_LIMIT_PROBE; } // restart the whole protocol ip.s_addr = pick(); timeout_ms = 0; nprobes = 0; nclaims = 0; } break; case MONITOR: // If a conflict, we try to defend with a single ARP probe. if (source_ip_conflict) { VDBG("monitor conflict -- defending\n"); state = DEFEND; timeout_ms = DEFEND_INTERVAL * 1000; arp(/* ARPOP_REQUEST, */ /* ð_addr, */ ip, ð_addr, ip); } break; case DEFEND: // Well, we tried. Start over (on conflict). if (source_ip_conflict) { state = PROBE; VDBG("defend conflict -- starting over\n"); ready = 0; run(argv, "deconfig", &ip); // restart the whole protocol ip.s_addr = pick(); timeout_ms = 0; nprobes = 0; nclaims = 0; } break; default: // Invalid, should never happen. Restart the whole protocol. VDBG("invalid state -- starting over\n"); state = PROBE; ip.s_addr = pick(); timeout_ms = 0; nprobes = 0; nclaims = 0; break; } // switch state break; // case 1 (packets arriving) } // switch poll } // while (1) #undef argv_intf }
/// Creates difference images, returns the number that have a 0 metric. /// If outputDir.isEmpty(), don't write out diff files. static void create_diff_images (DiffMetricProc dmp, const int colorThreshold, RecordArray* differences, const SkString& baseDir, const SkString& comparisonDir, const SkString& outputDir, const StringArray& matchSubstrings, const StringArray& nomatchSubstrings, bool recurseIntoSubdirs, bool getBounds, bool verbose, DiffSummary* summary) { SkASSERT(!baseDir.isEmpty()); SkASSERT(!comparisonDir.isEmpty()); FileArray baseFiles; FileArray comparisonFiles; get_file_list(baseDir, matchSubstrings, nomatchSubstrings, recurseIntoSubdirs, &baseFiles); get_file_list(comparisonDir, matchSubstrings, nomatchSubstrings, recurseIntoSubdirs, &comparisonFiles); if (!baseFiles.isEmpty()) { qsort(baseFiles.begin(), baseFiles.count(), sizeof(SkString*), SkCastForQSort(compare_file_name_metrics)); } if (!comparisonFiles.isEmpty()) { qsort(comparisonFiles.begin(), comparisonFiles.count(), sizeof(SkString*), SkCastForQSort(compare_file_name_metrics)); } int i = 0; int j = 0; while (i < baseFiles.count() && j < comparisonFiles.count()) { SkString basePath(baseDir); SkString comparisonPath(comparisonDir); DiffRecord *drp = new DiffRecord; int v = strcmp(baseFiles[i]->c_str(), comparisonFiles[j]->c_str()); if (v < 0) { // in baseDir, but not in comparisonDir drp->fResult = DiffRecord::kCouldNotCompare_Result; basePath.append(*baseFiles[i]); comparisonPath.append(*baseFiles[i]); drp->fBase.fFilename = *baseFiles[i]; drp->fBase.fFullPath = basePath; drp->fBase.fStatus = DiffResource::kExists_Status; drp->fComparison.fFilename = *baseFiles[i]; drp->fComparison.fFullPath = comparisonPath; drp->fComparison.fStatus = DiffResource::kDoesNotExist_Status; VERBOSE_STATUS("MISSING", ANSI_COLOR_YELLOW, baseFiles[i]); ++i; } else if (v > 0) { // in comparisonDir, but not in baseDir drp->fResult = DiffRecord::kCouldNotCompare_Result; basePath.append(*comparisonFiles[j]); comparisonPath.append(*comparisonFiles[j]); drp->fBase.fFilename = *comparisonFiles[j]; drp->fBase.fFullPath = basePath; drp->fBase.fStatus = DiffResource::kDoesNotExist_Status; drp->fComparison.fFilename = *comparisonFiles[j]; drp->fComparison.fFullPath = comparisonPath; drp->fComparison.fStatus = DiffResource::kExists_Status; VERBOSE_STATUS("MISSING", ANSI_COLOR_YELLOW, comparisonFiles[j]); ++j; } else { // Found the same filename in both baseDir and comparisonDir. SkASSERT(DiffRecord::kUnknown_Result == drp->fResult); basePath.append(*baseFiles[i]); comparisonPath.append(*comparisonFiles[j]); drp->fBase.fFilename = *baseFiles[i]; drp->fBase.fFullPath = basePath; drp->fBase.fStatus = DiffResource::kExists_Status; drp->fComparison.fFilename = *comparisonFiles[j]; drp->fComparison.fFullPath = comparisonPath; drp->fComparison.fStatus = DiffResource::kExists_Status; SkAutoDataUnref baseFileBits(read_file(drp->fBase.fFullPath.c_str())); if (baseFileBits) { drp->fBase.fStatus = DiffResource::kRead_Status; } SkAutoDataUnref comparisonFileBits(read_file(drp->fComparison.fFullPath.c_str())); if (comparisonFileBits) { drp->fComparison.fStatus = DiffResource::kRead_Status; } if (NULL == baseFileBits || NULL == comparisonFileBits) { if (NULL == baseFileBits) { drp->fBase.fStatus = DiffResource::kCouldNotRead_Status; VERBOSE_STATUS("READ FAIL", ANSI_COLOR_RED, baseFiles[i]); } if (NULL == comparisonFileBits) { drp->fComparison.fStatus = DiffResource::kCouldNotRead_Status; VERBOSE_STATUS("READ FAIL", ANSI_COLOR_RED, comparisonFiles[j]); } drp->fResult = DiffRecord::kCouldNotCompare_Result; } else if (are_buffers_equal(baseFileBits, comparisonFileBits)) { drp->fResult = DiffRecord::kEqualBits_Result; VERBOSE_STATUS("MATCH", ANSI_COLOR_GREEN, baseFiles[i]); } else { AutoReleasePixels arp(drp); get_bitmap(baseFileBits, drp->fBase, SkImageDecoder::kDecodePixels_Mode); get_bitmap(comparisonFileBits, drp->fComparison, SkImageDecoder::kDecodePixels_Mode); VERBOSE_STATUS("DIFFERENT", ANSI_COLOR_RED, baseFiles[i]); if (DiffResource::kDecoded_Status == drp->fBase.fStatus && DiffResource::kDecoded_Status == drp->fComparison.fStatus) { create_and_write_diff_image(drp, dmp, colorThreshold, outputDir, drp->fBase.fFilename); } else { drp->fResult = DiffRecord::kCouldNotCompare_Result; } } ++i; ++j; } if (getBounds) { get_bounds(*drp); } SkASSERT(DiffRecord::kUnknown_Result != drp->fResult); differences->push(drp); summary->add(drp); } for (; i < baseFiles.count(); ++i) { // files only in baseDir DiffRecord *drp = new DiffRecord(); drp->fBase.fFilename = *baseFiles[i]; drp->fBase.fFullPath = baseDir; drp->fBase.fFullPath.append(drp->fBase.fFilename); drp->fBase.fStatus = DiffResource::kExists_Status; drp->fComparison.fFilename = *baseFiles[i]; drp->fComparison.fFullPath = comparisonDir; drp->fComparison.fFullPath.append(drp->fComparison.fFilename); drp->fComparison.fStatus = DiffResource::kDoesNotExist_Status; drp->fResult = DiffRecord::kCouldNotCompare_Result; if (getBounds) { get_bounds(*drp); } differences->push(drp); summary->add(drp); } for (; j < comparisonFiles.count(); ++j) { // files only in comparisonDir DiffRecord *drp = new DiffRecord(); drp->fBase.fFilename = *comparisonFiles[j]; drp->fBase.fFullPath = baseDir; drp->fBase.fFullPath.append(drp->fBase.fFilename); drp->fBase.fStatus = DiffResource::kDoesNotExist_Status; drp->fComparison.fFilename = *comparisonFiles[j]; drp->fComparison.fFullPath = comparisonDir; drp->fComparison.fFullPath.append(drp->fComparison.fFilename); drp->fComparison.fStatus = DiffResource::kExists_Status; drp->fResult = DiffRecord::kCouldNotCompare_Result; if (getBounds) { get_bounds(*drp); } differences->push(drp); summary->add(drp); } release_file_list(&baseFiles); release_file_list(&comparisonFiles); }
int main(int argc, char **argv) { unsigned pid = 0; int i; // handle CTRL-C signal (SIGINT, my_handler); signal (SIGTERM, my_handler); for (i = 1; i < argc; i++) { // default options if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-?") == 0) { usage(); return 0; } else if (strcmp(argv[i], "--version") == 0) { printf("firemon version %s\n\n", VERSION); return 0; } // options without a pid argument else if (strcmp(argv[i], "--top") == 0) { top(); // never to return } else if (strcmp(argv[i], "--list") == 0) { list(); return 0; } else if (strcmp(argv[i], "--netstats") == 0) { struct stat s; if (getuid() != 0 && stat("/proc/sys/kernel/grsecurity", &s) == 0) { fprintf(stderr, "Error: this feature is not available on Grsecurity systems\n"); exit(1); } netstats(); return 0; } // cumulative options with or without a pid argument else if (strcmp(argv[i], "--x11") == 0) { arg_x11 = 1; } else if (strcmp(argv[i], "--cgroup") == 0) { arg_cgroup = 1; } else if (strcmp(argv[i], "--cpu") == 0) { arg_cpu = 1; } else if (strcmp(argv[i], "--seccomp") == 0) { arg_seccomp = 1; } else if (strcmp(argv[i], "--caps") == 0) { arg_caps = 1; } else if (strcmp(argv[i], "--tree") == 0) { arg_tree = 1; } else if (strcmp(argv[i], "--interface") == 0) { arg_interface = 1; } else if (strcmp(argv[i], "--route") == 0) { arg_route = 1; } else if (strcmp(argv[i], "--arp") == 0) { arg_arp = 1; } else if (strncmp(argv[i], "--name=", 7) == 0) { char *name = argv[i] + 7; if (name2pid(name, (pid_t *) &pid)) { fprintf(stderr, "Error: cannot find sandbox %s\n", name); return 1; } } // etc else if (strcmp(argv[i], "--nowrap") == 0) arg_nowrap = 1; // invalid option else if (*argv[i] == '-') { fprintf(stderr, "Error: invalid option\n"); return 1; } // PID argument else { // this should be a pid number char *ptr = argv[i]; while (*ptr != '\0') { if (!isdigit(*ptr)) { fprintf(stderr, "Error: not a valid PID number\n"); exit(1); } ptr++; } sscanf(argv[i], "%u", &pid); break; } } if (arg_tree) tree((pid_t) pid); if (arg_interface) interface((pid_t) pid); if (arg_route) route((pid_t) pid); if (arg_arp) arp((pid_t) pid); if (arg_seccomp) seccomp((pid_t) pid); if (arg_caps) caps((pid_t) pid); if (arg_cpu) cpu((pid_t) pid); if (arg_cgroup) cgroup((pid_t) pid); if (arg_x11) x11((pid_t) pid); if (!arg_route && !arg_arp && !arg_interface && !arg_tree && !arg_caps && !arg_seccomp && !arg_x11) procevent((pid_t) pid); // never to return return 0; }
/** * main program */ int main(int argc, char *argv[]) { char *intf = DEFAULT_INTERFACE; char *script = NULL; struct sockaddr_ll sockAddr; struct pollfd fds[1]; struct arp_packet arpPack; struct ifreq ifr; struct ether_addr ethAddr; struct timeval tv; struct in_addr ip = {0}; int fd; int quit = 0; int ready = 0; int foreground = 0; int timeout = 0; int nprobes = 0; int nclaims = 0; int failby = 0; int i = 1; int ret = 0; int ifindex=0; int listenfd; // receive patch - recv_pack args int packet_size = 0; char packet[4096]; struct sockaddr_ll from; int alen; // init gettimeofday(&tv, NULL); prog = argv[0]; // parse arguments while (i < argc) { char *arg = argv[i++]; if (strcmp(arg, "-q") == 0) { quit = 1; } else if (strcmp(arg, "-f") == 0) { foreground = 1; } else if (strcmp(arg, "-v") == 0) { #ifdef DEBUG verbose = 1; #endif } else if (strcmp(arg, "-n") == 0) { failby = time(0) + FAILURE_INTERVAL / 1000; } else if (strcmp(arg, "-i") == 0) { if ((intf = argv[i++]) == NULL) { usage("interface name missing"); } } else if (strcmp(arg, "-s") == 0) { if ((script = argv[i++]) == NULL) { usage("script missing"); } } else if (strcmp(arg, "-ip") == 0) { char *ipstr = argv[i++]; if (ipstr == NULL) { usage("ip address missing"); } if (inet_aton(ipstr, &ip) == 0) { usage("invalid ip address"); } #ifndef DEBUG if ((ntohl(ip.s_addr) & LINKLOCAL_MASK) != LINKLOCAL_ADDR) { usage("invalid linklocal address"); } #endif } else { usage("invald argument"); } } // get a socket handle fd = socket(PF_PACKET, SOCK_DGRAM, 0); if (fd < 0){ perror("open failed"); exit(fd); } // interface set up and connectivity tests memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, intf, IFNAMSIZ - 1); if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) { perror("Interface not found"); exit(2); } ifindex = ifr.ifr_ifindex; if (ioctl(fd, SIOCGIFFLAGS, &ifr)) { perror("SIOCGIFFLAGS"); exit(2); } if (!(ifr.ifr_flags & IFF_UP)) { perror("Interface is down"); exit(2); } if (ifr.ifr_flags & (IFF_NOARP | IFF_LOOPBACK)) { perror("Interface is not ARPable"); exit(2); } if (ret = ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) { perror("ioctl failed"); exit(ret); } memcpy(ðAddr, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN); #ifdef DEBUG printf("interface: %s\n",ether2str(ðAddr)); #endif // initialize socket address memset( &sockAddr, 0, sizeof( sockAddr ) ); sockAddr.sll_family = AF_PACKET; sockAddr.sll_ifindex = ifindex; sockAddr.sll_protocol = htons(ETH_P_ARP); // bind to the ARP socket { ret = bind(fd, ( struct sockaddr * ) &sockAddr, sizeof(sockAddr)); if (ret < 0) { perror("bind failed"); exit(ret); } alen = sizeof(sockAddr); if (getsockname(fd, (struct sockaddr *) &sockAddr, &alen) == -1) { perror("getsockname"); exit(2); } } // initialize the interface run(script, "init", intf, NULL); // initialize pseudo random selection of IP addresses { srandom((ethAddr.ether_addr_octet[ETHER_ADDR_LEN-4] << 24) | (ethAddr.ether_addr_octet[ETHER_ADDR_LEN-3] << 16) | (ethAddr.ether_addr_octet[ETHER_ADDR_LEN-2] << 8) | (ethAddr.ether_addr_octet[ETHER_ADDR_LEN-1] << 0)); // pick an ip address if (ip.s_addr == 0) { pick(&ip); } } // prepare for polling fds[0].fd = fd; fds[0].events = POLLIN | POLLERR; while (1) { #ifdef DEBUG if (verbose) { printf("%s %s: polling %d, nprobes=%d, nclaims=%d\n", prog, intf, timeout, nprobes, nclaims); } #endif fds[0].revents = 0; switch (poll(fds, 1, timeout)) { case 0: //sending // timeout if ((failby != 0) && (failby < time(0))) { fprintf(stderr, "%s %s: failed to obtain address\n", prog, intf); exit(1); } if (nprobes < NPROBES) { // ARP probe #ifdef DEBUG if (verbose) { fprintf(stderr, "%s %s: ARP probe %s\n", prog, intf, inet_ntoa(ip)); } #endif arp(fd, &sockAddr, ARPOP_REQUEST, ðAddr, null_ip, &null_addr, ip); nprobes++; timeout = PROBE_INTERVAL; } else if (nclaims < NCLAIMS) { // ARP claim #ifdef DEBUG if (verbose) { fprintf(stderr, "%s %s: ARP claim %s\n", prog, intf, inet_ntoa(ip)); } #endif arp(fd, &sockAddr, ARPOP_REQUEST, ðAddr, ip, ðAddr, ip); nclaims++; timeout = CLAIM_INTERVAL; } else { // ARP take #ifdef DEBUG if (verbose) { fprintf(stderr, "%s %s: use %s\n", prog, intf, inet_ntoa(ip)); } #endif ready = 1; timeout = -1; failby = 0; run(script, "config", intf, &ip); if (quit) { shutdown( fd, 0x02 ); close( fd ); exit(0); } if (!foreground) { if (daemon(0, 0) < 0) { perror("daemon failed"); exit(1); } } } break; case 1: // i/o event if ((fds[0].revents & POLLIN) == 0) { if (fds[0].revents & POLLERR) { fprintf(stderr, "%s %s: I/O error\n", prog, intf); exit(1); } continue; } // read ARP packet to a buffer alen = sizeof(from); if ((packet_size = recvfrom(fd, packet, sizeof(packet), 0, (struct sockaddr *) &from, &alen)) < 0) { perror("recv failed"); exit(1); } // parse arp packet into arp_packet p if (!recv_pack(packet, packet_size, &from, &arpPack )) continue; #ifdef DEBUG if (verbose) { printf("%s %s: recv arp op=%d, ", prog, intf, ntohs(arpPack.arp_hdr.ar_op)); printf("source=%s %s,", ether2str(&arpPack.source_addr), inet_ntoa(arpPack.source_ip)); printf("target=%s %s\n", ether2str(&arpPack.target_addr),inet_ntoa(arpPack.target_ip)); } #endif if (arpPack.source_ip.s_addr == ip.s_addr) { #ifdef DEBUG if (verbose) { fprintf(stderr, "%s %s: ARP conflict %s\n", prog, intf, inet_ntoa(ip)); } #endif //restart ip request pick(&ip); timeout = 0; nprobes = 0; nclaims = 0; if (ready) { ready = 0; run(script, "deconfig", intf, 0); } } break; default: perror("poll failed"); exit(1); } } }
int main(void){ init_uart(); uint16_t packet_length, rxstat; uart_puts("beginning startup procedure\r\n"); /*ENC Initialisieren*/ enc28j60Init(); uart_puts("initialization finished\r\n"); //Mac Adresse setzen(stack.h, dort wird auch die Ip festgelegt) nicSetMacAddress(mymac); uart_puts("mac address set\r\n"); /* Leds konfigurieren LEDA : Link status LEDB : Receive activity Led Settings : enc28j60 datasheet, page 11*/ enc28j60PhyWrite(0x14,0b0000010000100000); /* Leds konfigurieren LEDA : Link status LEDB : Blink Fast Led Settings : enc28j60 datasheet, page 11 Auskommentieren, wenn mans lieber blinken sieht ;-) */ //enc28j60PhyWrite(0x14,0b0000010000100000); while(1) { // Buffer des Enc's abhohlen :-) packet_length = enc28j60PacketReceive(BUFFER_SIZE, buffer, &rxstat); // Wenn ein Packet angekommen ist, ist packet_length =! 0 if(packet_length) { packet_length -= 4; struct ETH_frame *frame = (struct ETH_frame *) buffer; frame->type_length = ntohs(frame->type_length); // arping uses unicast after the first by default, but we don't care because performance if(/*(*/rxstat&BROADCAST_BIT /*|| compare_macs(frame->destMac, (uint8_t *) mymac))*/ && frame->type_length == TYPE_ARP) { struct ARP_packet *arp_pkt = (struct ARP_packet *) frame->payload; if(compare_ips(arp_pkt->destIp, (uint8_t *) myip)) { arp(packet_length, buffer); } continue; } if(compare_macs(frame->destMac, (uint8_t *) mymac)) { if(frame->type_length == TYPE_IP4) { struct IP_segment *ip = (struct IP_segment *) frame->payload; if(ip->protocol == TYPE_ICMP) { icmp(packet_length, buffer); continue; } else if(ip->protocol == TYPE_UDP) { struct UDP_packet *pkt = (struct UDP_packet *) ip->payload; pkt->destPort = pkt->destPort; pkt->sourcePort = pkt->sourcePort; if(pkt->destPort == ntohs(7)) { udp(htons(pkt->length), buffer); continue; } if(pkt->destPort == ntohs(85) && compare(pkt->data, "test")) { printinbuffer(pkt->data, "Test erfolgreich!", TERMINATE); udp(18, buffer); continue; } if(pkt->destPort == ntohs(86)) { uart_puts((char*) pkt->data); uart_puts("\r\n"); continue; } } else if(ip->protocol == TYPE_TCP) { uart_puts("received tcp package!\r\n"); #if DEBUG hexdump(ip, 256); #endif struct TCP_segment *tcp = (struct TCP_segment *) ip->payload; if(tcp->sourcePort == ntohs(7)) { } } } } } } return 1; }