grafo ( char file[]) { R=route(read(file)); M.geometric(R); }
bool TraCIServerAPI_Simulation::commandDistanceRequest(TraCIServer& server, tcpip::Storage& inputStorage, tcpip::Storage& outputStorage, int commandId) { Position pos1; Position pos2; std::pair<const MSLane*, SUMOReal> roadPos1; std::pair<const MSLane*, SUMOReal> roadPos2; // read position 1 int posType = inputStorage.readUnsignedByte(); switch (posType) { case POSITION_ROADMAP: try { std::string roadID = inputStorage.readString(); roadPos1.second = inputStorage.readDouble(); roadPos1.first = getLaneChecking(roadID, inputStorage.readUnsignedByte(), roadPos1.second); pos1 = roadPos1.first->getShape().positionAtOffset(roadPos1.second); } catch (TraCIException& e) { server.writeStatusCmd(commandId, RTYPE_ERR, e.what()); return false; } break; case POSITION_2D: case POSITION_3D: { SUMOReal p1x = inputStorage.readDouble(); SUMOReal p1y = inputStorage.readDouble(); pos1.set(p1x, p1y); } if (posType == POSITION_3D) { inputStorage.readDouble(); // z value is ignored } roadPos1 = convertCartesianToRoadMap(pos1); break; default: server.writeStatusCmd(commandId, RTYPE_ERR, "Unknown position format used for distance request"); return false; } // read position 2 posType = inputStorage.readUnsignedByte(); switch (posType) { case POSITION_ROADMAP: try { std::string roadID = inputStorage.readString(); roadPos2.second = inputStorage.readDouble(); roadPos2.first = getLaneChecking(roadID, inputStorage.readUnsignedByte(), roadPos2.second); pos2 = roadPos2.first->getShape().positionAtOffset(roadPos2.second); } catch (TraCIException& e) { server.writeStatusCmd(commandId, RTYPE_ERR, e.what()); return false; } break; case POSITION_2D: case POSITION_3D: { SUMOReal p2x = inputStorage.readDouble(); SUMOReal p2y = inputStorage.readDouble(); pos2.set(p2x, p2y); } if (posType == POSITION_3D) { inputStorage.readDouble(); // z value is ignored } roadPos2 = convertCartesianToRoadMap(pos2); break; default: server.writeStatusCmd(commandId, RTYPE_ERR, "Unknown position format used for distance request"); return false; } // read distance type int distType = inputStorage.readUnsignedByte(); SUMOReal distance = 0.0; if (distType == REQUEST_DRIVINGDIST) { // compute driving distance if ((roadPos1.first == roadPos2.first) && (roadPos1.second <= roadPos2.second)) { // same edge distance = roadPos2.second - roadPos1.second; } else { MSEdgeVector newRoute; MSNet::getInstance()->getRouterTT().compute( &roadPos1.first->getEdge(), &roadPos2.first->getEdge(), 0, MSNet::getInstance()->getCurrentTimeStep(), newRoute); MSRoute route("", newRoute, false, 0, std::vector<SUMOVehicleParameter::Stop>()); distance = route.getDistanceBetween(roadPos1.second, roadPos2.second, &roadPos1.first->getEdge(), &roadPos2.first->getEdge()); } } else { // compute air distance (default) distance = pos1.distanceTo(pos2); } // write response command outputStorage.writeUnsignedByte(TYPE_DOUBLE); outputStorage.writeDouble(distance); return true; }
static bool test_route(const unsigned n_airspaces, const RasterMap& map) { Airspaces airspaces; setup_airspaces(airspaces, map.GetMapCenter(), n_airspaces); { std::ofstream fout("results/terrain.txt"); unsigned nx = 100; unsigned ny = 100; GeoPoint origin(map.GetMapCenter()); for (unsigned i = 0; i < nx; ++i) { for (unsigned j = 0; j < ny; ++j) { fixed fx = (fixed)i / (nx - 1) * fixed(2.0) - fixed_one; fixed fy = (fixed)j / (ny - 1) * fixed(2.0) - fixed_one; GeoPoint x(origin.longitude + Angle::Degrees(fixed(0.2) + fixed(0.7) * fx), origin.latitude + Angle::Degrees(fixed(0.9) * fy)); short h = map.GetInterpolatedHeight(x); fout << x.longitude.Degrees() << " " << x.latitude.Degrees() << " " << h << "\n"; } fout << "\n"; } fout << "\n"; } { // local scope, see what happens when we go out of scope GeoPoint p_start(Angle::Degrees(fixed(-0.3)), Angle::Degrees(fixed(0.0))); p_start += map.GetMapCenter(); GeoPoint p_dest(Angle::Degrees(fixed(0.8)), Angle::Degrees(fixed(-0.7))); p_dest += map.GetMapCenter(); AGeoPoint loc_start(p_start, RoughAltitude(map.GetHeight(p_start) + 100)); AGeoPoint loc_end(p_dest, RoughAltitude(map.GetHeight(p_dest) + 100)); AircraftState state; GlidePolar glide_polar(fixed(0.1)); AirspaceAircraftPerformanceGlide perf(glide_polar); GeoVector vec(loc_start, loc_end); fixed range = fixed(10000) + vec.distance / 2; state.location = loc_start; state.altitude = loc_start.altitude; { Airspaces as_route(airspaces, false); // dummy // real one, see if items changed as_route.synchronise_in_range(airspaces, vec.MidPoint(loc_start), range); int size_1 = as_route.size(); if (verbose) printf("# route airspace size %d\n", size_1); as_route.synchronise_in_range(airspaces, vec.MidPoint(loc_start), fixed_one); int size_2 = as_route.size(); if (verbose) printf("# route airspace size %d\n", size_2); ok(size_2 < size_1, "shrink as", 0); // go back as_route.synchronise_in_range(airspaces, vec.MidPoint(loc_end), range); int size_3 = as_route.size(); if (verbose) printf("# route airspace size %d\n", size_3); ok(size_3 >= size_2, "grow as", 0); // and again as_route.synchronise_in_range(airspaces, vec.MidPoint(loc_start), range); int size_4 = as_route.size(); if (verbose) printf("# route airspace size %d\n", size_4); ok(size_4 >= size_3, "grow as", 0); scan_airspaces(state, as_route, perf, true, loc_end); } // try the solver SpeedVector wind(Angle::Degrees(fixed(0)), fixed(0.0)); GlidePolar polar(fixed_one); GlideSettings settings; settings.SetDefaults(); AirspaceRoute route(airspaces); route.UpdatePolar(settings, polar, polar, wind); route.SetTerrain(&map); RoutePlannerConfig config; config.mode = RoutePlannerConfig::Mode::BOTH; bool sol = false; for (int i = 0; i < NUM_SOL; i++) { loc_end.latitude += Angle::Degrees(fixed(0.1)); loc_end.altitude = map.GetHeight(loc_end) + 100; route.Synchronise(airspaces, loc_start, loc_end); if (route.Solve(loc_start, loc_end, config)) { sol = true; if (verbose) { PrintHelper::print_route(route); } } else { if (verbose) { printf("# fail\n"); } sol = false; } char buffer[80]; sprintf(buffer, "route %d solution", i); ok(sol, buffer, 0); } } return true; }
TestHttpServer() : ProcessBase("TestHttpServer") { route("/test", None(), &TestHttpServer::test); }
boolean RF22Router::recvfromAck(uint8_t* buf, uint8_t* len, uint8_t* source, uint8_t* dest, uint8_t* id, uint8_t* flags) { uint8_t tmpMessageLen = sizeof(_tmpMessage); uint8_t _from; uint8_t _to; uint8_t _id; uint8_t _flags; if (RF22ReliableDatagram::recvfromAck((uint8_t*)&_tmpMessage, &tmpMessageLen, &_from, &_to, &_id, &_flags)) { // Here we simulate networks with limited visibility between nodes // so we can test routing #ifdef RF22_TEST_NETWORK if ( #if RF22_TEST_NETWORK==1 // This looks like 1-2-3-4 (_thisAddress == 1 && _from == 2) || (_thisAddress == 2 && (_from == 1 || _from == 3)) || (_thisAddress == 3 && (_from == 2 || _from == 4)) || (_thisAddress == 4 && _from == 3) #elif RF22_TEST_NETWORK==2 // This looks like 1-2-4 // | | | // --3-- (_thisAddress == 1 && (_from == 2 || _from == 3)) || _thisAddress == 2 || _thisAddress == 3 || (_thisAddress == 4 && (_from == 2 || _from == 3)) #elif RF22_TEST_NETWORK==3 // This looks like 1-2-4 // | | // --3-- (_thisAddress == 1 && (_from == 2 || _from == 3)) || (_thisAddress == 2 && (_from == 1 || _from == 4)) || (_thisAddress == 3 && (_from == 1 || _from == 4)) || (_thisAddress == 4 && (_from == 2 || _from == 3)) #elif RF22_TEST_NETWORK==4 // This looks like 1-2-3 // | // 4 (_thisAddress == 1 && _from == 2) || _thisAddress == 2 || (_thisAddress == 3 && _from == 2) || (_thisAddress == 4 && _from == 2) #endif ) { // OK } else { return false; // Pretend we got nothing } #endif peekAtMessage(&_tmpMessage, tmpMessageLen); // See if its for us or has to be routed if (_tmpMessage.header.dest == _thisAddress || _tmpMessage.header.dest == RF22_BROADCAST_ADDRESS) { // Deliver it here if (source) *source = _tmpMessage.header.source; if (dest) *dest = _tmpMessage.header.dest; if (id) *id = _tmpMessage.header.id; if (flags) *flags = _tmpMessage.header.flags; uint8_t msgLen = tmpMessageLen - sizeof(RoutedMessageHeader); if (*len > msgLen) *len = msgLen; memcpy(buf, _tmpMessage.data, *len); return true; // Its for you! } else if ( _tmpMessage.header.dest != RF22_BROADCAST_ADDRESS && _tmpMessage.header.hops++ < _max_hops) { // Maybe it has to be routed to the next hop // REVISIT: if it fails due to no route or unable to deliver to the next hop, // tell the originator. BUT HOW? route(&_tmpMessage, tmpMessageLen); } // Discard it and maybe wait for another } return false; }
virtual void initialize() { route("/", None(), &Help::help); }
std::vector<tripoint> map::route( const tripoint &f, const tripoint &t, const pathfinding_settings &settings, const std::set<tripoint> &pre_closed ) const { /* TODO: If the origin or destination is out of bound, figure out the closest * in-bounds point and go to that, then to the real origin/destination. */ std::vector<tripoint> ret; if( f == t || !inbounds( f ) ) { return ret; } if( !inbounds( t ) ) { tripoint clipped = t; clip_to_bounds( clipped ); return route( f, clipped, settings, pre_closed ); } // First, check for a simple straight line on flat ground // Except when the line contains a pre-closed tile - we need to do regular pathing then static const auto non_normal = PF_SLOW | PF_WALL | PF_VEHICLE | PF_TRAP; if( f.z == t.z ) { const auto line_path = line_to( f, t ); const auto &pf_cache = get_pathfinding_cache_ref( f.z ); // Check all points for any special case (including just hard terrain) if( std::all_of( line_path.begin(), line_path.end(), [&pf_cache]( const tripoint & p ) { return !( pf_cache.special[p.x][p.y] & non_normal ); } ) ) { const std::set<tripoint> sorted_line( line_path.begin(), line_path.end() ); if( is_disjoint( sorted_line, pre_closed ) ) { return line_path; } } } // If expected path length is greater than max distance, allow only line path, like above if( rl_dist( f, t ) > settings.max_dist ) { return ret; } int max_length = settings.max_length; int bash = settings.bash_strength; int climb_cost = settings.climb_cost; bool doors = settings.allow_open_doors; bool trapavoid = settings.avoid_traps; const int pad = 16; // Should be much bigger - low value makes pathfinders dumb! int minx = std::min( f.x, t.x ) - pad; int miny = std::min( f.y, t.y ) - pad; int minz = std::min( f.z, t.z ); // TODO: Make this way bigger int maxx = std::max( f.x, t.x ) + pad; int maxy = std::max( f.y, t.y ) + pad; int maxz = std::max( f.z, t.z ); // Same TODO as above clip_to_bounds( minx, miny, minz ); clip_to_bounds( maxx, maxy, maxz ); pathfinder pf( minx, miny, maxx, maxy ); // Make NPCs not want to path through player // But don't make player pathing stop working for( const auto &p : pre_closed ) { if( p.x >= minx && p.x < maxx && p.y >= miny && p.y < maxy ) { pf.close_point( p ); } } // Start and end must not be closed pf.unclose_point( f ); pf.unclose_point( t ); pf.add_point( 0, 0, f, f ); bool done = false; do { auto cur = pf.get_next(); const int parent_index = flat_index( cur.x, cur.y ); auto &layer = pf.get_layer( cur.z ); auto &cur_state = layer.state[parent_index]; if( cur_state == ASL_CLOSED ) { continue; } if( layer.gscore[parent_index] > max_length ) { // Shortest path would be too long, return empty vector return std::vector<tripoint>(); } if( cur == t ) { done = true; break; } cur_state = ASL_CLOSED; const auto &pf_cache = get_pathfinding_cache_ref( cur.z ); const auto cur_special = pf_cache.special[cur.x][cur.y]; // 7 3 5 // 1 . 2 // 6 4 8 constexpr std::array<int, 8> x_offset{{ -1, 1, 0, 0, 1, -1, -1, 1 }}; constexpr std::array<int, 8> y_offset{{ 0, 0, -1, 1, -1, 1, -1, 1 }}; for( size_t i = 0; i < 8; i++ ) { const tripoint p( cur.x + x_offset[i], cur.y + y_offset[i], cur.z ); const int index = flat_index( p.x, p.y ); // @todo: Remove this and instead have sentinels at the edges if( p.x < minx || p.x >= maxx || p.y < miny || p.y >= maxy ) { continue; } if( layer.state[index] == ASL_CLOSED ) { continue; } // Penalize for diagonals or the path will look "unnatural" int newg = layer.gscore[parent_index] + ( ( cur.x != p.x && cur.y != p.y ) ? 1 : 0 ); const auto p_special = pf_cache.special[p.x][p.y]; // @todo: De-uglify, de-huge-n if( !( p_special & non_normal ) ) { // Boring flat dirt - the most common case above the ground newg += 2; } else { int part = -1; const maptile &tile = maptile_at_internal( p ); const auto &terrain = tile.get_ter_t(); const auto &furniture = tile.get_furn_t(); const vehicle *veh = veh_at_internal( p, part ); const int cost = move_cost_internal( furniture, terrain, veh, part ); // Don't calculate bash rating unless we intend to actually use it const int rating = ( bash == 0 || cost != 0 ) ? -1 : bash_rating_internal( bash, furniture, terrain, false, veh, part ); if( cost == 0 && rating <= 0 && ( !doors || !terrain.open ) && veh == nullptr && climb_cost <= 0 ) { layer.state[index] = ASL_CLOSED; // Close it so that next time we won't try to calculate costs continue; } newg += cost; if( cost == 0 ) { if( climb_cost > 0 && p_special & PF_CLIMBABLE ) { // Climbing fences newg += climb_cost; } else if( doors && terrain.open && ( !terrain.has_flag( "OPENCLOSE_INSIDE" ) || !is_outside( cur ) ) ) { // Only try to open INSIDE doors from the inside // To open and then move onto the tile newg += 4; } else if( veh != nullptr ) { part = veh->obstacle_at_part( part ); int dummy = -1; if( doors && veh->part_flag( part, VPFLAG_OPENABLE ) && ( !veh->part_flag( part, "OPENCLOSE_INSIDE" ) || veh_at_internal( cur, dummy ) == veh ) ) { // Handle car doors, but don't try to path through curtains newg += 10; // One turn to open, 4 to move there } else if( part >= 0 && bash > 0 ) { // Car obstacle that isn't a door // @todo: Account for armor int hp = veh->parts[part].hp(); if( hp / 20 > bash ) { // Threshold damage thing means we just can't bash this down layer.state[index] = ASL_CLOSED; continue; } else if( hp / 10 > bash ) { // Threshold damage thing means we will fail to deal damage pretty often hp *= 2; } newg += 2 * hp / bash + 8 + 4; } else if( part >= 0 ) { if( !doors || !veh->part_flag( part, VPFLAG_OPENABLE ) ) { // Won't be openable, don't try from other sides layer.state[index] = ASL_CLOSED; } continue; } } else if( rating > 1 ) { // Expected number of turns to bash it down, 1 turn to move there // and 5 turns of penalty not to trash everything just because we can newg += ( 20 / rating ) + 2 + 10; } else if( rating == 1 ) { // Desperate measures, avoid whenever possible newg += 500; } else { // Unbashable and unopenable from here if( !doors || !terrain.open ) { // Or anywhere else for that matter layer.state[index] = ASL_CLOSED; } continue; } } if( trapavoid && p_special & PF_TRAP ) { const auto &ter_trp = terrain.trap.obj(); const auto &trp = ter_trp.is_benign() ? tile.get_trap_t() : ter_trp; if( !trp.is_benign() ) { // For now make them detect all traps if( has_zlevels() && terrain.has_flag( TFLAG_NO_FLOOR ) ) { // Special case - ledge in z-levels // Warning: really expensive, needs a cache if( valid_move( p, tripoint( p.x, p.y, p.z - 1 ), false, true ) ) { tripoint below( p.x, p.y, p.z - 1 ); if( !has_flag( TFLAG_NO_FLOOR, below ) ) { // Otherwise this would have been a huge fall auto &layer = pf.get_layer( p.z - 1 ); // From cur, not p, because we won't be walking on air pf.add_point( layer.gscore[parent_index] + 10, layer.score[parent_index] + 10 + 2 * rl_dist( below, t ), cur, below ); } // Close p, because we won't be walking on it layer.state[index] = ASL_CLOSED; continue; } } else if( trapavoid ) { // Otherwise it's walkable newg += 500; } } } } // If not visited, add as open // If visited, add it only if we can do so with better score if( layer.state[index] == ASL_NONE || newg < layer.gscore[index] ) { pf.add_point( newg, newg + 2 * rl_dist( p, t ), cur, p ); } } if( !has_zlevels() || !( cur_special & PF_UPDOWN ) || !settings.allow_climb_stairs ) { // The part below is only for z-level pathing continue; } const maptile &parent_tile = maptile_at_internal( cur ); const auto &parent_terrain = parent_tile.get_ter_t(); if( settings.allow_climb_stairs && cur.z > minz && parent_terrain.has_flag( TFLAG_GOES_DOWN ) ) { tripoint dest( cur.x, cur.y, cur.z - 1 ); dest = vertical_move_destination<TFLAG_GOES_UP>( *this, dest ); if( inbounds( dest ) ) { auto &layer = pf.get_layer( dest.z ); pf.add_point( layer.gscore[parent_index] + 2, layer.score[parent_index] + 2 * rl_dist( dest, t ), cur, dest ); } } if( settings.allow_climb_stairs && cur.z < maxz && parent_terrain.has_flag( TFLAG_GOES_UP ) ) { tripoint dest( cur.x, cur.y, cur.z + 1 ); dest = vertical_move_destination<TFLAG_GOES_DOWN>( *this, dest ); if( inbounds( dest ) ) { auto &layer = pf.get_layer( dest.z ); pf.add_point( layer.gscore[parent_index] + 2, layer.score[parent_index] + 2 * rl_dist( dest, t ), cur, dest ); } } if( cur.z < maxz && parent_terrain.has_flag( TFLAG_RAMP ) && valid_move( cur, tripoint( cur.x, cur.y, cur.z + 1 ), false, true ) ) { auto &layer = pf.get_layer( cur.z + 1 ); for( size_t it = 0; it < 8; it++ ) { const tripoint above( cur.x + x_offset[it], cur.y + y_offset[it], cur.z + 1 ); pf.add_point( layer.gscore[parent_index] + 4, layer.score[parent_index] + 4 + 2 * rl_dist( above, t ), cur, above ); } } } while( !done && !pf.empty() ); if( done ) { ret.reserve( rl_dist( f, t ) * 2 ); tripoint cur = t; // Just to limit max distance, in case something weird happens for( int fdist = max_length; fdist != 0; fdist-- ) { const int cur_index = flat_index( cur.x, cur.y ); const auto &layer = pf.get_layer( cur.z ); const tripoint &par = layer.parent[cur_index]; if( cur == f ) { break; } ret.push_back( cur ); // Jumps are acceptable on 1 z-level changes // This is because stairs teleport the player too if( rl_dist( cur, par ) > 1 && abs( cur.z - par.z ) != 1 ) { debugmsg( "Jump in our route! %d:%d:%d->%d:%d:%d", cur.x, cur.y, cur.z, par.x, par.y, par.z ); return ret; } cur = par; } std::reverse( ret.begin(), ret.end() ); } return ret; }
void VersionProcess::initialize() { route("/", VERSION_HELP(), &VersionProcess::version); }
std::vector<tripoint> map::route( const tripoint &f, const tripoint &t, const int bash, const int maxdist ) const { return route( f, t, bash, maxdist, {{ g->u.pos() }} ); }
void NetTradeRoute::Unpacketize(uint16 id, uint8 *buf, uint16 size) { sint32 pos; uint32 transportCost; uint32 passesThrough; uint32 sourceCityID; uint32 destCityID; uint32 recip; uint16 numWp; sint32 i; Assert(MAKE_CIV3_ID(buf[0], buf[1]) == k_PACKET_TRADE_ROUTE_ID); TradeRoute route(getlong(&buf[2])); g_network.CheckReceivedObject((uint32)route); if(!g_theTradePool->IsValid(route)) { m_routeData = new TradeRouteData(route); } else { m_routeData = g_theTradePool->AccessTradeRoute(route); } pos = 6; uint8 newRoute; PULLBYTE(newRoute); m_newRoute = newRoute != 0; PULLBYTETYPE(m_routeData->m_owner, PLAYER_INDEX); PULLBYTETYPE(m_routeData->m_payingFor, PLAYER_INDEX); PULLLONG(transportCost); m_routeData->m_transportCost = transportCost / 10000.; PULLBYTETYPE(m_routeData->m_sourceRouteType, ROUTE_TYPE); PULLLONG(m_routeData->m_sourceResource); PULLLONG(passesThrough); for(i = 0; i < k_MAX_PLAYERS; i++) { m_routeData->m_passesThrough[i] = (passesThrough & (1 << i)) ? TRUE : FALSE; } PULLBYTE(m_routeData->m_crossesWater); PULLBYTE(m_routeData->m_isActive); PULLLONG(m_routeData->m_color); PULLLONG(m_routeData->m_outline); PULLLONG(m_routeData->m_gold_in_return); PULLLONG(sourceCityID); PULLLONG(destCityID); if(!g_theTradePool->IsValid(m_routeData->m_id)) { m_routeData->m_sourceCity = Unit(sourceCityID); m_routeData->m_destinationCity = Unit(destCityID); } else { if(m_routeData->m_sourceCity.m_id != sourceCityID) { m_routeData->m_sourceCity.DelTradeRoute(route); m_routeData->m_sourceCity = Unit(sourceCityID); m_routeData->m_sourceCity.AddTradeRoute(route); } if(m_routeData->m_destinationCity.m_id != destCityID) { m_routeData->m_destinationCity.DelTradeRoute(route); m_routeData->m_destinationCity = Unit(destCityID); m_routeData->m_destinationCity.AddTradeRoute(route); } } PULLLONG(recip); m_routeData->m_recip = TradeRoute(recip); PULLSHORT(numWp); m_routeData->RemoveFromCells(); m_routeData->m_path.Clear(); PLAYER_INDEX owner; for(i = 0; i < numWp; i++) { MapPoint pnt; PULLSHORTTYPE(pnt.x, sint16); PULLSHORTTYPE(pnt.y, sint16); m_routeData->m_path.Insert(pnt); owner = m_routeData->m_sourceCity.GetOwner(); g_theWorld->GetCell(pnt)->AddTradeRoute(route); } if(!g_theTradePool->IsValid(route)) { g_theTradePool->HackSetKey(((uint32)m_routeData->m_id & k_ID_KEY_MASK) + 1); g_theTradePool->Insert(m_routeData); m_routeData->m_sourceCity.AddTradeRoute(route, !m_newRoute); m_routeData->m_destinationCity.AddTradeRoute(route, !m_newRoute); g_theTradePool->m_all_routes->Insert(route); g_director->TradeActorCreate(route); } TradeManager::Notify(); }
virtual void initialize() { route("/start", &Profiler::start); route("/stop", &Profiler::stop); }
void justine::sampleclient::MyShmClient::start10 ( boost::asio::io_service& io_service, const char * port ) { #ifdef DEBUG foo(); #endif boost::asio::ip::tcp::resolver resolver ( io_service ); boost::asio::ip::tcp::resolver::query query ( boost::asio::ip::tcp::v4(), "localhost", port ); boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve ( query ); boost::asio::ip::tcp::socket socket ( io_service ); boost::asio::connect ( socket, iterator ); std::vector<Cop> cops = initcops ( socket ); bool pursuit {false}; unsigned int g {0u}; unsigned int f {0u}; unsigned int t {0u}; unsigned int s {0u}; std::vector<Gangster> gngstrs; for ( ;; ) { std::this_thread::sleep_for ( std::chrono::milliseconds ( 200 ) ); for ( auto cop:cops ) { car ( socket, cop, &f, &t, &s ); if ( true ) { gngstrs = gangsters ( socket, cop, t ); if ( gngstrs.size() > 0 ) g = gngstrs[0].to; else g = 0; if ( g > 0 ) { if(dst(f, gngstrs[0].to) == 0) continue; std::vector<osmium::unsigned_object_id_type> path = hasDijkstraPathMy ( t, gngstrs ); if ( path.size() > 1 && pursuit==false ) { route ( socket, cop, path ); pursuit = true; } } } if(pursuit) { std::vector<osmium::unsigned_object_id_type> pathPur = hasDijkstraPath ( t, gngstrs[0].to ); if ( distanceMy(pathPur) < 150 || distanceMy(pathPur) > 1000 ) { route ( socket, cop, pathPur ); } else { std::vector<osmium::unsigned_object_id_type> pathPur2 = hasDijkstraPath ( t, gngstrs[0].from ); if ( pathPur2.size() > 0 && distanceMy(pathPur2) < distanceMy(pathPur) ) { route ( socket, cop, pathPur2 ); } } } if ( t == g ) pursuit = false; } } }
void ForwardRules::buildDefaultRules(const char* domain, const char* hostname, const char* ipAddress, const char* fqhn, int localPort, TiXmlDocument& xmlDoc) { // Note: fqhn == fully qualified host name UtlString hostnamePort(hostname ? hostname : "localhost"); UtlString domainPort(domain ? domain : ""); UtlString ipAddressPort(ipAddress ? ipAddress : "127.0.0.1"); UtlString fqhnPort(fqhn ? fqhn : "localhost"); if(localPort == 5060) localPort = PORT_NONE; if(portIsValid(localPort)) { char portString[40]; sprintf(portString,":%d", localPort); hostnamePort.append(portString); domainPort.append(portString); ipAddressPort.append(portString); fqhnPort.append(portString); } UtlString sdsAddress(fqhn); sdsAddress.append(":5090"); UtlString statusAddress(fqhn); statusAddress.append(":5110"); UtlString regAddress(fqhn); regAddress.append(":5070"); UtlString configAddress("sipuaconfig"); UtlString configFqhnAddress(configAddress); configFqhnAddress.append("."); configFqhnAddress.append(domain); TiXmlElement routes("routes"); TiXmlElement route("route"); route.SetAttribute("mappingType", "local"); TiXmlElement routeFromDomain("routeFrom"); TiXmlText domainText(domainPort.data()); TiXmlElement routeFromFqhn("routeFrom"); TiXmlText fqhnText(fqhnPort.data()); TiXmlElement routeFromHost("routeFrom"); TiXmlText hostText(hostnamePort.data()); TiXmlElement routeFromIp("routeFrom"); TiXmlText ipText(ipAddressPort.data()); TiXmlElement methodMatch("methodMatch"); TiXmlElement methodPattern("methodPattern"); TiXmlText subscribe("SUBSCRIBE"); TiXmlElement fieldMatchConfig("fieldMatch"); fieldMatchConfig.SetAttribute("fieldName", "Event"); TiXmlElement fieldPatternConfig("fieldPattern"); TiXmlText configEvent("sip-config"); TiXmlElement routeToSds("routeTo"); TiXmlText sdsText(sdsAddress.data()); TiXmlElement fieldMatchStatus("fieldMatch"); fieldMatchStatus.SetAttribute("fieldName", "Event"); TiXmlElement fieldPatternStatus("fieldPattern"); TiXmlText mwiEvent("message-summary*"); TiXmlElement routeToStatus("routeTo"); TiXmlText statusText(statusAddress.data()); TiXmlElement routeToReg("routeTo"); TiXmlText regText(regAddress.data()); TiXmlElement routeConfig("route"); TiXmlElement routeFromFqhnConfig("routeFrom"); TiXmlText fqhnConfigText(configFqhnAddress.data()); TiXmlElement routeFromConfig("routeFrom"); TiXmlText configText(configAddress.data()); // Link everything up in reverse order as it TinyXml // makes copies routeFromDomain.InsertEndChild(domainText); route.InsertEndChild(routeFromDomain); routeFromHost.InsertEndChild(hostText); route.InsertEndChild(routeFromHost); routeFromFqhn.InsertEndChild(fqhnText); route.InsertEndChild(routeFromFqhn); routeFromIp.InsertEndChild(ipText); route.InsertEndChild(routeFromIp); methodPattern.InsertEndChild(subscribe); methodMatch.InsertEndChild(methodPattern); fieldPatternStatus.InsertEndChild(mwiEvent); fieldMatchStatus.InsertEndChild(fieldPatternStatus); routeToStatus.InsertEndChild(statusText); fieldMatchStatus.InsertEndChild(routeToStatus); methodMatch.InsertEndChild(fieldMatchStatus); fieldPatternConfig.InsertEndChild(configEvent); fieldMatchConfig.InsertEndChild(fieldPatternConfig); routeToSds.InsertEndChild(sdsText); fieldMatchConfig.InsertEndChild(routeToSds); methodMatch.InsertEndChild(fieldMatchConfig); routeToReg.InsertEndChild(regText); methodMatch.InsertEndChild(routeToReg); route.InsertEndChild(methodMatch); route.InsertEndChild(routeToReg); routeFromFqhnConfig.InsertEndChild(fqhnConfigText); routeConfig.InsertEndChild(routeFromFqhnConfig); routeFromConfig.InsertEndChild(configText); routeConfig.InsertEndChild(routeFromConfig); routeConfig.InsertEndChild(routeToReg); routes.InsertEndChild(route); routes.InsertEndChild(routeConfig); xmlDoc.InsertEndChild(routes); }
grafo ( route P) { R=route(P); M.geometric(P); }
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool Routing::removeRoute(const RouteIndex& i) { Route* object = route(i); if ( object == NULL ) return false; return remove(object); }
void NtfyPacket(std::shared_ptr<GlobalGrid::VSocket> socket,unsigned char* packetData, size_t packetLength) { if(sessions.find(socket) == sessions.end()) { //We should have an AES key in our packet here encrypted with our public key. //Packet header -- thumbprint (16 bytes) (unverified data element), session key (variable length, encrypted) if(packetLength<=16) { return; } void* packet = RSA_Decrypt(privkey,packetData+16,packetLength-16); if(packet == 0) { //Decryption failure. return; } unsigned char* buffer; size_t sz; GlobalGrid::Buffer_Get(packet,&buffer,&sz); if(sz>=32) { //We have a new Session. Session route(socket,buffer,packetData); sessions.insert(route); //Respond with ACK, which verifies our identity //Send challenge to verify remote identity. char hexprint[33]; ToHexString((unsigned char*)route.claimedThumbprint,16,hexprint); hexprint[32] = 0; void* remoteKey = DB_FindAuthority(hexprint); if(remoteKey) { SendChallenge(remoteKey,route,socket); }else { //We don't have a remote key. Request it. unsigned char izard[16]; memset(izard,0,16); izard[0] = 2; aes_encrypt(route.key,izard); socket->Send(izard,16); } GlobalGrid::GGObject_Free(packet); }else { GlobalGrid::GGObject_Free(packet); } }else { //Bind to existing Session. if(packetLength % 16 != 0) { //Invalid packet. return; } Session session = *sessions.find(socket); for(size_t i = 0;i<packetLength;i+=16) { aes_decrypt(session.key,packetData+i); } switch(*packetData) { case 0: //Challenge request { //Decrypt challenge uint16_t len; memcpy(&len,packetData+1,2); void* challenge = RSA_Decrypt(privkey,packetData+1+2,len); if(challenge == 0) { return; } unsigned char* challenge_bytes; size_t challenge_sz; GlobalGrid::Buffer_Get(challenge,&challenge_bytes,&challenge_sz); if(challenge_sz != 16) { GlobalGrid::GGObject_Free(challenge); return; } unsigned char response[32]; memset(response,0,32); response[0] = 1; memcpy(response+1,challenge_bytes,16); aes_encrypt(session.key,response); aes_encrypt(session.key,response+16); socket->Send(response,32); GlobalGrid::GGObject_Free(challenge); } break; case 1: { //Response to challenge (identity verification) if(memcmp(session.challenge,packetData+1,16) == 0) { session.verified = true; printf("Identity verified.\n"); } } break; case 2: { //Request for public encryptionKey. void* key = RSA_Export(privkey,false); unsigned char* key_bytes; size_t key_size; GlobalGrid::Buffer_Get(key,&key_bytes,&key_size); size_t aligned = key_size+1; aligned+=16-(aligned % 16); unsigned char* packet = new unsigned char[aligned]; memcpy(packet+1,key_bytes,key_size); packet[0] = 3; for(size_t i = 0;i<aligned;i+=16) { aes_encrypt(session.key,packet+i); } socket->Send(packet,aligned); delete[] packet; GlobalGrid::GGObject_Free(key); } break; case 3: { //Received public encryption key void* key = RSA_Key(packetData+1,packetLength-1); char thumbprint[33]; RSA_thumbprint(key,thumbprint); thumbprint[32] = 0; void* obj = DB_FindAuthority(thumbprint); if(obj == 0) { void* keybin = RSA_Export(key,false); unsigned char* cert; size_t cert_len; GlobalGrid::Buffer_Get(keybin,&cert,&cert_len); DB_Insert_Certificate(thumbprint,cert,cert_len,false); GlobalGrid::GGObject_Free(keybin); if(session.verified == false) { //TODO: Send verification request SendChallenge(key,session,socket); } }else { RSA_Free(obj); } } break; case 4: { //Route packet packetData++; unsigned char ttl = *packetData; packetData++; //Intended destination GlobalGrid::Guid dest; memcpy(dest.value,packetData,16); packetData+=16; GlobalGrid::Guid localThumbprint; RSA_thumbprint(privkey,(unsigned char*)localThumbprint.value); uint32_t packetSize; memcpy(&packetSize,packetData,4); packetData+=16; if(dest == localGuid) { printf("TODO: Packet destined for ourselves\n"); return; } SendPacket(packetData,packetSize,ttl,dest,session.claimedThumbprint); } break; } } }
//TODO: minor, the event is not actually stored (or better, it's copied if stored). //Adjust the fact that we are now passing the size of what is passed in bytes and not number of packets void MF_ContentSocketManager::recvRequest(MF_APIRecv *event){ MF_Log::mf_log(MF_DEBUG, "MF_ContentSocketManager:recvRequest handle receive request from API"); struct MsgRecvReply rcR; if(!pendingRec.empty()){ MF_Log::mf_log(MF_DEBUG, "MF_ContentSocketManager::recvRequest other recv requests are already waiting"); if(event->getBlk()){ MF_Log::mf_log(MF_DEBUG, "MF_ContentSocketManager::recvRequest the request is blocking so will wait"); MF_APIRecv *newEvent = new MF_APIRecv(); newEvent->setBlk(event->getBlk()); newEvent->setReqID(event->getReqID()); newEvent->setSize(event->getSize()); newEvent->setUID(event->getUID()); pendingRec.push_back(newEvent); } else{ MF_Log::mf_log(MF_DEBUG, "MF_ContentSocketManager::recvRequest the request is non blocking so it will not wait"); rcR.type = MSG_TYPE_RECV_REPLY; rcR.UID = ID; rcR.retValue = STACK_NO_BUFFER_AVAIL; rcR.reqID = event->getReqID(); rcR.size = 0; _system->getSocketServer()->send((char *)&rcR, sizeof(struct MsgRecvReply), &cliAddr); } } else if(trnsp->dataAvailable()){ MF_Log::mf_log(MF_DEBUG, "MF_ContentSocketManager::recvRequest data available in transport"); //check with transport if there is something available vector<u_char *> *v = new vector<u_char *>(); u_int size = trnsp->getData(v, event->getSize()); if(size){ MF_Log::mf_log(MF_DEBUG, "MF_ContentSocketManager::recvRequest the buffer is big enough, getting ready to pass data"); rcR.type = MSG_TYPE_RECV_REPLY; rcR.UID = ID; rcR.retValue = STACK_ACTION_SUCCESS; rcR.reqID = event->getReqID(); //TODO: check this is correct rcR.size = size; //rcR.size = MF_BasicTransport::computeChunkPktCnt(size + MF_BasicTransport::computeMsgChkCnt(size)*HIGH_HEADER_LEN); RoutingHeader route(MF_PacketSupport::getNetworkHeaderPtr(v->front())); rcR.sGUID = route.getSrcGUID().to_int(); _system->getSocketServer()->send((char *)&rcR, sizeof(struct MsgRecvReply), &cliAddr); sendData(v, size); recvBuffer.putVector(v); } else{ MF_Log::mf_log(MF_DEBUG, "MF_ContentSocketManager::recvRequest the buffer is not big enough, reply will trigger an error"); rcR.type = MSG_TYPE_RECV_REPLY; rcR.UID = ID; rcR.retValue = STACK_NO_BUFFER_AVAIL; rcR.reqID = event->getReqID(); rcR.size = 0; _system->getSocketServer()->send((char *)&rcR, sizeof(struct MsgRecvReply), &cliAddr); } } else if(event->getBlk()){ MF_Log::mf_log(MF_DEBUG, "MF_ContentSocketManager::recvRequest no data available and the request is blocking so will wait"); MF_APIRecv *newEvent = new MF_APIRecv(); newEvent->setBlk(event->getBlk()); newEvent->setReqID(event->getReqID()); newEvent->setSize(event->getSize()); newEvent->setUID(event->getUID()); pendingRec.push_back(newEvent); } else{ MF_Log::mf_log(MF_DEBUG, "MF_ContentSocketManager::recvRequest no data available and the request is not blocking so will not wait"); rcR.type = MSG_TYPE_RECV_REPLY; rcR.UID = ID; rcR.retValue = STACK_NO_BUFFER_AVAIL; rcR.reqID = event->getReqID(); rcR.size = 0; _system->getSocketServer()->send((char *)&rcR, sizeof(struct MsgRecvReply), &cliAddr); } }
static void new_data(int fd,void *user) { LINK *lnk = user; int got; got = read(fd,lnk->buffer+lnk->len,BUFFER_SIZE-lnk->len); if (got < 0) perror("read"); if (got <= 0) drop_link(lnk); lnk->len += got; if (lnk->state != id_set) { LINK *walk; char *end; int id; if (!memchr(lnk->buffer,0,lnk->len)) return; id = strtol(lnk->buffer,&end,0); if (*end) { diag(COMPONENT,DIAG_ERROR,"invalid line id \"%s\"",lnk->buffer); drop_link(lnk); return; } for (walk = links; walk; walk = walk->next) if (walk->state != id_none && id == walk->id) break; if (walk) { if (walk->state == id_set) { diag(COMPONENT,DIAG_ERROR,"line state mismatch (id %d)",id); drop_link(lnk); return; } diag(COMPONENT,DIAG_INFO,"reconnected link %d",id); walk->state = id_set; walk->fd = lnk->fd; walk->len = lnk->len; memcpy(walk->buffer,lnk->buffer,lnk->len); drop_link(lnk); lnk = walk; dsp_fd_add(lnk->fd,new_data,walk); } else { diag(COMPONENT,DIAG_INFO,"new link %d",id); lnk->state = id_set; lnk->id = id; } notify(lnk->id,1); lnk->len -= strlen(lnk->buffer)+1; memmove(lnk->buffer,lnk->buffer-strlen(lnk->buffer)-1,lnk->len); } while (lnk->len >= sizeof(struct atmtcp_hdr)) { struct atmtcp_hdr *hdr = (struct atmtcp_hdr *) lnk->buffer; LINK *out; int size; size = sizeof(struct atmtcp_hdr)+ntohl(hdr->length); if (lnk->len < size) break; out = route(lnk,hdr); if (out) { int sent; sent = write(out->fd,lnk->buffer,size); if (sent < 0) perror("write"); else if (sent != size) diag(COMPONENT,DIAG_ERROR,"bad write: %d != %d",sent,size); if (sent != size) drop_link(out); } lnk->len -= size; memmove(lnk->buffer,lnk->buffer+size,lnk->len); } }
void Pages::track(Document *doc){ std::string sub; int tid = route("track", path, sub); bool post = cgi.getEnvironment().getRequestMethod() == "POST"; if(!tid) return; if(sub == ""){ ExtendedTrack t(tid); if(!t) return; doc->setHtml("html/track.tpl", t.title); doc->rootDict()->SetValueAndShowSection("TID", number(t.id), "HAS_OEMBED"); t.fill(doc->dict()); t.player(doc->dict(), true); Audio(&t).fill(doc->dict()); doc->dict()->ShowSection(Youtube(t.artist.id) ? "HAS_YOUTUBE" : "NO_YOUTUBE"); Dict *embed = doc->dict()->AddIncludeDictionary("EMBED_CODE"); embed->SetFilename("html/embed-code.tpl"); embed->SetIntValue("WIDTH", 150); t.Track::fill(embed); Dict *uploader = doc->dict()->AddIncludeDictionary("UPLOADER"); uploader->SetFilename("html/uploader.tpl"); uploader->SetValue("ACTION", t.url() + "/upload"); int hits = Stat::push("trackView", t.artist.id, tid); doc->dict()->SetValue("HIT_COUNT", number(hits)); int unique_hits = Stat::get("trackView", 0, tid, true); doc->dict()->SetValue("UNIQUE_HIT_COUNT", number(unique_hits)); doc->rootDict()->ShowSection("REQUIRES_STATS_JS"); Session::fill(doc->dict()); EventList::track(t).fill(doc->dict(), "EVENTS", false); doc->dict()->ShowSection(Follower(Session::user().id).favorited(tid) ? "IS_FAVORITE" : "NOT_FAVORITE"); if(Session::user()){ DB::Result playlists = DB::query( "SELECT id, name FROM playlists WHERE user_id = " + number(Session::user().id) + " ORDER BY name ASC"); if(!playlists.empty()){ doc->dict()->ShowSection("HAS_PLAYLISTS"); for(DB::Result::const_iterator i=playlists.begin(); i!=playlists.end(); i++){ Dict *playlist = doc->dict()->AddSectionDictionary("PLAYLIST"); playlist->SetValue("PLAYLIST_ID", i->at(0)); playlist->SetValue("PLAYLIST_NAME", i->at(1)); } } } } else if(sub == "delete"){ Track t(tid); if(!t) return; if(!t.artist.self()) doc->redirect(t.url()); else if(!post || cgi("confirm") != "Delete" || Session::nonce() != cgi("nonce")){ Session::newNonce(); doc->setHtml("html/delete.tpl", "Track deletion"); doc->dict()->SetValue("WHAT", t.title); doc->dict()->SetValue("CANCEL_URL", t.url()); } else{ log("Deleting track: " + t.title + " (" + number(t.id) + ")"); Art art(t.id); if(art) art.remove(); Audio(&t).unlink(); Playlist::removeTrack(t.id); DB::query("DELETE FROM events WHERE track_id = " + number(t.id)); DB::query("DELETE FROM featured_tracks WHERE track_id = " + number(t.id)); DB::query("DELETE FROM favorites WHERE type = 'track' AND ref = " + number(t.id)); DB::query("DELETE FROM user_features WHERE type = 'track' AND ref = " + number(t.id)); DB::query("DELETE FROM tracks WHERE id = " + number(t.id)); doc->redirect(Session::user().url()); } } else if(sub == "publish"){ Track t(tid); if(!t) return; if(tid != number(cgi("tid"))) return doc->redirect(t.url()); if(t.artist.self() && !t.visible && post){ DB::query("UPDATE tracks SET visible = 't', date = 'now' WHERE id = " + number(t.id)); Event e; e.type = Event::Publish; e.source = t.artist; e.track = t; e.push(); std::vector<std::string> emails = Follower(t.artist.id).followers(); std::string maildata = "From: EqBeats notification <*****@*****.**>\n" "Message-ID: notify-t" + number(t.id) + "\n" "Subject: " + filter("EqBeats notification: " + t.artist.name + " - " + t.title) + "\n" "Precedence: bulk\n\n" + t.artist.name + " just published a new track : " + t.title + "\n" "Listen to it here : " + eqbeatsUrl() + t.url() + "\n\n" "You're receiving this email because you're following " + t.artist.name + " on EqBeats.\n" "If you don't want to receive these notifications anymore, go to " + eqbeatsUrl() + t.artist.url() + " and click \"Stop following\"."; for(std::vector<std::string>::const_iterator i = emails.begin(); i!=emails.end(); i++) sendMail(i->c_str(), maildata.c_str()); } doc->redirect(t.url()); } }
int main(int __argc, char ** __argv) { if(__argc != 5){ cout<<"incomplete commands"; return 0; } char * fileName = __argv[1]; char * fileName2 = __argv[2]; istringstream ss(__argv[3]); ss>> srcNodeLabel; istringstream ss2(__argv[4]); ss2>>destNodeLabel; // create a file-reading object ifstream fin; fin.open(fileName); // open a file if (!fin.good()) return 1; // exit if file not found int v1, v2,w1,numEdges; fin>> numVertices>> numEdges; if(srcNodeLabel > numVertices || srcNodeLabel < 0) { cout<<"error, out of bounds source vertex"; return 0 ; } if(destNodeLabel > numVertices || destNodeLabel < 0) { cout<<"error, out of bounds destination vertex"; return 0 ; } g = new Graph(numVertices); //allocate memory to vertexToIPMap = (int **)malloc(numVertices * sizeof(int *)); for(int i=0; i<numVertices;i++) vertexToIPMap[i] = (int *) malloc(32*sizeof(int)); while (fin >> v1 >> v2 >>w1 ) { //insert into graph g->vertices[v1].insert(pair<int,int>(v2,w1)); g->vertices[v2].insert(pair<int,int>(v1,w1)); } //read input file 2 // create a file-reading object ifstream fin2; fin2.open(fileName2); // open a file if (!fin2.good()) return 1; // exit if file not found int v = 0; string ipLine; // read each line of the file while ( fin2>> ipLine) { // process the tokens size_t pos = 0; string token[4]; string delimiter = "."; int i = 0; while ((pos = ipLine.find(delimiter)) != std::string::npos) { token[i] = ipLine.substr(0, pos); ipLine.erase(0, pos + delimiter.length()); i++; } token[i] = ipLine; int k=0; int ip[32]; for (int i = 0; i < 4; i++) // n = #of tokens { int N = atoi(token[i].c_str()); int O[8];//The output array bitset<8> A=N;//A will hold the binary representation of N for(int i=0,j=7;i<8;i++,j--) { //Assigning the bits one by one. O[i]=A[j]; ip[k]=O[i]; k++; } } int w =0; while(w<32) { vertexToIPMap[v][w] =ip[w]; //populate map w++ ; } v++; } vector<int> prev = dijkstra(g, srcNodeLabel, destNodeLabel); //calculate prev array for source vertex map<int,BinTrie *> vertexToBinTrie; //map to store pointer to bin tree with owner vertex as key vertexToBinTrie.insert(pair<int, BinTrie *>(srcNodeLabel,constructBinTrie(srcNodeLabel,prev))); //construct and populate bin trie map condenseBinTrie( vertexToBinTrie[srcNodeLabel]); //condense the trie for efficiency int node = prev[destNodeLabel]; //loop to construct and condense bin tries of all vertices while(node != srcNodeLabel) { vertexToBinTrie.insert(pair<int, BinTrie *>(node,constructBinTrie(node,dijkstra(g,node,destNodeLabel)))); condenseBinTrie(vertexToBinTrie[node]); node = prev[node]; } route(srcNodeLabel,destNodeLabel,vertexToBinTrie); //for routing packet from source to destination //free memory delete(g); delete(fHeap); free(vertexToIPMap); return 0; }
/* check all connections to see if anything happened on their sockets */ static void check_network_activity(fd_set * readset, fd_set * writeset) { connection_t *c; avl_node_t *node; int result, i; socklen_t len = sizeof(result); vpn_packet_t packet; static int errors = 0; /* check input from kernel */ if(device_fd >= 0 && FD_ISSET(device_fd, readset)) { if(devops.read(&packet)) { if(packet.len) { errors = 0; packet.priority = 0; route(myself, &packet); } } else { usleep(errors * 50000); errors++; if(errors > 10) { logger(LOG_ERR, "Too many errors from %s, exiting!", device); running = false; } } } /* check meta connections */ for(node = connection_tree->head; node; node = node->next) { c = node->data; if(c->status.remove) continue; if(FD_ISSET(c->socket, writeset)) { if(c->status.connecting) { c->status.connecting = false; getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len); if(!result) finish_connecting(c); else { ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result)); closesocket(c->socket); do_outgoing_connection(c); continue; } } if(!flush_meta(c)) { terminate_connection(c, c->status.active); continue; } } if(FD_ISSET(c->socket, readset)) { if(!receive_meta(c)) { terminate_connection(c, c->status.active); continue; } } } for(i = 0; i < listen_sockets; i++) { if(FD_ISSET(listen_socket[i].udp, readset)) handle_incoming_vpn_data(i); if(FD_ISSET(listen_socket[i].tcp, readset)) handle_new_meta_connection(listen_socket[i].tcp); } }
std::vector<tripoint> map::route( const tripoint &f, const tripoint &t, const int bash, const int maxdist ) const { /* TODO: If the origin or destination is out of bound, figure out the closest * in-bounds point and go to that, then to the real origin/destination. */ if( !inbounds( f ) ) { return {}; } if( !inbounds( t ) ) { tripoint clipped = t; clip_to_bounds( clipped ); return route( f, clipped, bash, maxdist ); } // First, check for a simple straight line on flat ground // Except when the player is on the line - we need to do regular pathing then const tripoint &pl_pos = g->u.pos(); if( f.z == t.z && clear_path( f, t, -1, 2, 2 ) ) { const auto line_path = line_to( f, t ); if( pl_pos.z != f.z ) { // Player on different z-level, certainly not on the line return line_path; } if( std::find( line_path.begin(), line_path.end(), pl_pos ) == line_path.end() ) { return line_path; } } const int pad = 8; // Should be much bigger - low value makes pathfinders dumb! int minx = std::min( f.x, t.x ) - pad; int miny = std::min( f.y, t.y ) - pad; int minz = std::min( f.z, t.z ); // TODO: Make this way bigger int maxx = std::max( f.x, t.x ) + pad; int maxy = std::max( f.y, t.y ) + pad; int maxz = std::max( f.z, t.z ); // Same TODO as above clip_to_bounds( minx, miny, minz ); clip_to_bounds( maxx, maxy, maxz ); pathfinder pf( minx, miny, maxx, maxy ); pf.add_point( 0, 0, f, f ); // Make NPCs not want to path through player // But don't make player pathing stop working if( f != pl_pos && t != pl_pos ) { pf.close_point( pl_pos ); } bool done = false; do { auto cur = pf.get_next(); const int parent_index = flat_index( cur.x, cur.y ); auto &layer = pf.get_layer( cur.z ); auto &cur_state = layer.state[parent_index]; if( cur_state == ASL_CLOSED ) { continue; } if( layer.gscore[parent_index] > maxdist ) { // Shortest path would be too long, return empty vector return std::vector<tripoint>(); } if( cur == t ) { done = true; break; } cur_state = ASL_CLOSED; // 7 3 5 // 1 . 2 // 6 4 8 constexpr std::array<int, 8> x_offset{{ -1, 1, 0, 0, 1, -1, -1, 1 }}; constexpr std::array<int, 8> y_offset{{ 0, 0, -1, 1, -1, 1, -1, 1 }}; for( size_t i = 0; i < 8; i++ ) { const tripoint p( cur.x + x_offset[i], cur.y + y_offset[i], cur.z ); const int index = flat_index( p.x, p.y ); // TODO: Remove this and instead have sentinels at the edges if( p.x < minx || p.x >= maxx || p.y < miny || p.y >= maxy ) { continue; } if( layer.state[index] == ASL_CLOSED ) { continue; } int part = -1; const maptile &tile = maptile_at_internal( p ); const auto &terrain = tile.get_ter_t(); const auto &furniture = tile.get_furn_t(); const vehicle *veh = veh_at_internal( p, part ); const int cost = move_cost_internal( furniture, terrain, veh, part ); // Don't calculate bash rating unless we intend to actually use it const int rating = ( bash == 0 || cost != 0 ) ? -1 : bash_rating_internal( bash, furniture, terrain, false, veh, part ); if( cost == 0 && rating <= 0 && terrain.open.empty() && veh == nullptr ) { layer.state[index] = ASL_CLOSED; // Close it so that next time we won't try to calc costs continue; } int newg = layer.gscore[parent_index] + cost + ( (cur.x != p.x && cur.y != p.y ) ? 1 : 0); if( cost == 0 ) { // Handle all kinds of doors // Only try to open INSIDE doors from the inside if( !terrain.open.empty() && ( !terrain.has_flag( "OPENCLOSE_INSIDE" ) || !is_outside( cur ) ) ) { newg += 4; // To open and then move onto the tile } else if( veh != nullptr ) { part = veh->obstacle_at_part( part ); int dummy = -1; if( veh->part_flag( part, VPFLAG_OPENABLE ) && ( !veh->part_flag( part, "OPENCLOSE_INSIDE" ) || veh_at_internal( cur, dummy ) == veh ) ) { // Handle car doors, but don't try to path through curtains newg += 10; // One turn to open, 4 to move there } else if( part != -1 && bash > 0 ) { // Car obstacle that isn't a door // Or there is no car obstacle, but the car is wedged into an obstacle, // in which case part == -1 newg += 2 * veh->parts[part].hp / bash + 8 + 4; } else { if( !veh->part_flag( part, VPFLAG_OPENABLE ) ) { // Won't be openable, don't try from other sides layer.state[index] = ASL_CLOSED; } continue; } } else if( rating > 1 ) { // Expected number of turns to bash it down, 1 turn to move there // and 5 turns of penalty not to trash everything just because we can newg += ( 20 / rating ) + 2 + 10; } else if( rating == 1 ) { // Desperate measures, avoid whenever possible newg += 500; } else { continue; // Unbashable and unopenable from here } } const auto &ter_trp = terrain.trap.obj(); const auto &trp = ter_trp.is_benign() ? tile.get_trap_t() : ter_trp; if( !trp.is_benign() ) { // For now make them detect all traps newg += 500; } // If not visited, add as open // If visited, add it only if we can do so with better score if( layer.state[index] == ASL_NONE || newg < layer.gscore[index] ) { pf.add_point( newg, newg + 2 * rl_dist( p, t ), cur, p ); } } if( !has_zlevels() ) { // The part below is only for z-level pathing continue; } const maptile &parent_tile = maptile_at_internal( cur ); const auto &parent_terrain = parent_tile.get_ter_t(); if( cur.z > minz && parent_terrain.has_flag( TFLAG_GOES_DOWN ) ) { tripoint dest( cur.x, cur.y, cur.z - 1 ); dest = vertical_move_destination<TFLAG_GOES_UP>( *this, dest ); if( inbounds( dest ) ) { auto &layer = pf.get_layer( dest.z ); pf.add_point( layer.gscore[parent_index] + 2, layer.score[parent_index] + 2 * rl_dist( dest, t ), cur, dest ); } } if( cur.z < maxz && parent_terrain.has_flag( TFLAG_GOES_UP ) ) { tripoint dest( cur.x, cur.y, cur.z + 1 ); dest = vertical_move_destination<TFLAG_GOES_DOWN>( *this, dest ); if( inbounds( dest ) ) { auto &layer = pf.get_layer( dest.z ); pf.add_point( layer.gscore[parent_index] + 2, layer.score[parent_index] + 2 * rl_dist( dest, t ), cur, dest ); } } } while( !done && !pf.empty() ); std::vector<tripoint> ret; ret.reserve( rl_dist( f, t ) * 2 ); if( done ) { tripoint cur = t; // Just to limit max distance, in case something weird happens for( int fdist = maxdist; fdist != 0; fdist-- ) { const int cur_index = flat_index( cur.x, cur.y ); const auto &layer = pf.get_layer( cur.z ); const tripoint &par = layer.parent[cur_index]; if( cur == f ) { break; } ret.push_back( cur ); // Jumps are acceptable on 1 z-level changes // This is because stairs teleport the player too if( rl_dist( cur, par ) > 1 && abs( cur.z - par.z ) != 1 ) { debugmsg( "Jump in our route! %d:%d:%d->%d:%d:%d", cur.x, cur.y, cur.z, par.x, par.y, par.z ); return ret; } cur = par; } std::reverse( ret.begin(), ret.end() ); } return ret; }
static unsigned int route_oif(const struct ipt_route_target_info *route_info, struct sk_buff *skb) { unsigned int ifindex = 0; struct net_device *dev_out = NULL; /* The user set the interface name to use. * Getting the current interface index. */ if ((dev_out = dev_get_by_name(route_info->oif))) { ifindex = dev_out->ifindex; } else { /* Unknown interface name : packet dropped */ if (net_ratelimit()) DEBUGP("ipt_ROUTE: oif interface %s not found\n", route_info->oif); return NF_DROP; } /* Trying the standard way of routing packets */ switch (route(skb, ifindex, route_info)) { case 1: dev_put(dev_out); if (route_info->flags & IPT_ROUTE_CONTINUE) return IPT_CONTINUE; ip_direct_send(skb); return NF_STOLEN; case 0: /* Failed to send to oif. Trying the hard way */ if (route_info->flags & IPT_ROUTE_CONTINUE) return NF_DROP; if (net_ratelimit()) DEBUGP("ipt_ROUTE: forcing the use of %i\n", ifindex); /* We have to force the use of an interface. * This interface must be a tunnel interface since * otherwise we can't guess the hw address for * the packet. For a tunnel interface, no hw address * is needed. */ if ((dev_out->type != ARPHRD_TUNNEL) && (dev_out->type != ARPHRD_IPGRE)) { if (net_ratelimit()) DEBUGP("ipt_ROUTE: can't guess the hw addr !\n"); dev_put(dev_out); return NF_DROP; } /* Send the packet. This will also free skb * Do not go through the POST_ROUTING hook because * skb->dst is not set and because it will probably * get confused by the destination IP address. */ skb->dev = dev_out; dev_direct_send(skb); dev_put(dev_out); return NF_STOLEN; default: /* Unexpected error */ dev_put(dev_out); return NF_DROP; } }
static void receive_packet(node_t *n, vpn_packet_t *packet) { ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)", packet->len, n->name, n->hostname); route(n, packet); }
void In3(const SwitchBasedComm__msg_impl * msg_data) { printf(RCV_DEBUG,3,msg_data->toclient); route(msg_data); }
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; }
void MessageSwitch::AddRoute(unsigned int begin, unsigned int end, BufferedTransformation &destination, const std::string &channel) { RangeRoute route(begin, end, Route(&destination, channel)); RouteList::iterator it = upper_bound(m_routes.begin(), m_routes.end(), route); m_routes.insert(it, route); }
void Hub::tileToAntennaProcess() { if (reset.read()) { for (unsigned int i =0 ;i<txChannels.size();i++) { int channel = txChannels[i]; flag[channel]->write(HOLD_CHANNEL); } for (int i = 0; i < num_ports; i++) { ack_rx[i]->write(0); current_level_rx[i] = 0; } return; } for (unsigned int i =0 ;i<txChannels.size();i++) { int channel = txChannels[i]; string macPolicy = token_ring->getPolicy(channel).first; if (macPolicy == TOKEN_PACKET) txRadioProcessTokenPacket(channel); else if (macPolicy == TOKEN_HOLD) txRadioProcessTokenHold(channel); else if (macPolicy == TOKEN_MAX_HOLD) txRadioProcessTokenMaxHold(channel); else assert(false); } int * r_from_tile = new int[num_ports]; // 1st phase: Reservation for (int j = 0; j < num_ports; j++) { int i = (start_from_port + j) % (num_ports); if (!buffer_from_tile[i].IsEmpty()) { //LOG << "Reservation: buffer_from_tile not empty on port " << i << endl; Flit flit = buffer_from_tile[i].Front(); power.bufferFromTileFront(); r_from_tile[i] = route(flit); if (flit.flit_type == FLIT_TYPE_HEAD) { assert(r_from_tile[i]==DIRECTION_WIRELESS); int channel = selectChannel(local_id,tile2Hub(flit.dst_id)); assert(channel!=NOT_VALID && "hubs are connected by any channel"); if (tile2antenna_reservation_table.isAvailable(channel)) { tile2antenna_reservation_table.reserve(i, channel); } else { //LOG << "Reservation: wireless channel " << channel << " not available ..." << endl; } } } } start_from_port++; // 2nd phase: Forwarding for (int i = 0; i < num_ports; i++) { if (!buffer_from_tile[i].IsEmpty()) { Flit flit = buffer_from_tile[i].Front(); // powerFront already accounted in 1st phase assert(r_from_tile[i] == DIRECTION_WIRELESS); int channel = tile2antenna_reservation_table.getOutputPort(i); if (channel != NOT_RESERVED) { if (!(init[channel]->buffer_tx.IsFull()) ) { LOG << "Flit moved from buffer_from_tile["<<i<<"] to buffer_tx["<<channel<<"] " << endl; buffer_from_tile[i].Pop(); power.bufferFromTilePop(); init[channel]->buffer_tx.Push(flit); power.antennaBufferPush(); if (flit.flit_type == FLIT_TYPE_TAIL) tile2antenna_reservation_table.release(channel); } } else { //LOG << "Forwarding: No channel reserved for port direction " << i << endl; } } }// for all the ports for (int i = 0; i < num_ports; i++) { /* if (!buffer_from_tile[i].deadlockFree()) { LOG << " deadlock on buffer " << i << endl; buffer_from_tile[i].Print("deadlock"); } */ if ((req_rx[i]->read() == 1 - current_level_rx[i]) && !buffer_from_tile[i].IsFull()) { //LOG << "Reading flit on port " << i << endl; Flit received_flit = flit_rx[i]->read(); buffer_from_tile[i].Push(received_flit); power.bufferFromTilePush(); current_level_rx[i] = 1 - current_level_rx[i]; } ack_rx[i]->write(current_level_rx[i]); } // IMPORTANT: do not move from here // The txPowerManager assumes that all flit buffer write have been done updateTxPower(); }
static void run(){ route(SERVER->scriptName); sendHtml(); }
int gateroute(unsigned int command, struct rtmptab *rtmp) { struct sockaddr_at dst, gate; unsigned short net; if ( command == RTMP_DEL && ( rtmp->rt_flags & RTMPTAB_ROUTE ) == 0 ) { return( -1 ); } if ( command == RTMP_ADD && ( rtmp->rt_flags & RTMPTAB_ROUTE )) { return( -1 ); } net = ntohs( rtmp->rt_firstnet ); /* * Since we will accept routes from gateways who advertise their * address as 0.YY, we must munge the gateway address we give to * the kernel. Otherwise, we'll get a bunch of routes to the loop * back interface, and who wants that? */ memset( &gate, 0, sizeof( struct sockaddr_at )); #ifdef BSD4_4 gate.sat_len = sizeof( struct sockaddr_at ); #endif /* BSD4_4 */ gate.sat_family = AF_APPLETALK; gate.sat_addr.s_net = rtmp->rt_gate->g_sat.sat_addr.s_net; gate.sat_addr.s_node = rtmp->rt_gate->g_sat.sat_addr.s_node; if ( gate.sat_addr.s_net == 0 ) { gate.sat_addr.s_net = net; } memset( &dst, 0, sizeof( struct sockaddr_at )); #ifdef BSD4_4 dst.sat_len = sizeof( struct sockaddr_at ); #endif /* BSD4_4 */ dst.sat_family = AF_APPLETALK; dst.sat_addr.s_node = ATADDR_ANYNODE; do { dst.sat_addr.s_net = htons( net ); #ifndef BSD4_4 if ( route( command, (struct sockaddr *) &dst, (struct sockaddr *) &gate, RTF_UP | RTF_GATEWAY )) { LOG(log_error, logtype_atalkd, "route: %u -> %u.%u: %s", net, ntohs( gate.sat_addr.s_net ), gate.sat_addr.s_node, strerror(errno) ); continue; } #else /* ! BSD4_4 */ if ( route( command, (struct sockaddr_at *) &dst, (struct sockaddr_at *) &gate, RTF_UP | RTF_GATEWAY )) { LOG(log_error, logtype_atalkd, "route: %u -> %u.%u: %s", net, ntohs( gate.sat_addr.s_net ), gate.sat_addr.s_node, strerror(errno) ); continue; } #endif /* ! BSD4_4 */ } while ( net++ < ntohs( rtmp->rt_lastnet )); if ( command == RTMP_ADD ) { rtmp->rt_flags |= RTMPTAB_ROUTE; } if ( command == RTMP_DEL ) { rtmp->rt_flags &= ~RTMPTAB_ROUTE; } return( 0 ); }