Example #1
0
Bottle NameServer::botify(const Contact& address) {
    Bottle result;
    if (address.isValid()) {
        Bottle bname;
        bname.addString("name");
        bname.addString(address.getRegName().c_str());
        Bottle bip;
        bip.addString("ip");
        bip.addString(address.getHost().c_str());
        Bottle bnum;
        bnum.addString("port_number");
        bnum.addInt(address.getPort());
        Bottle bcarrier;
        bcarrier.addString("carrier");
        bcarrier.addString(address.getCarrier().c_str());

        result.addString("port");
        result.addList() = bname;
        result.addList() = bip;
        result.addList() = bnum;
        result.addList() = bcarrier;
    } else {
        Bottle bstate;
        bstate.addString("error");
        bstate.addInt(-2);
        bstate.addString("port not known");
        result.addString("port");
        result.addList() = bstate;
    }
    return result;
}
Example #2
0
bool SubscriberOnSql::checkSubscription(const ConstString& src,const ConstString& dest,
                                        const ConstString& srcFull,
                                        const ConstString& destFull,
                                        const ConstString& mode) {
    if (getDelegate()) {
        NestedContact nc(src);
        if (nc.getNestedName().size()>0) {
            NestedContact nc(dest);
            if (nc.getNestedName().size()>0) {
                return false;
            }
        }
    }
    if (verbose) {
        printf("+++ Checking %s %s / %s %s\n",
               src.c_str(), dest.c_str(), srcFull.c_str(), destFull.c_str());
    }
    NameStore *store = getStore();
    if (store!=NULL) {
        Contact csrc = store->query(src);
        Contact cdest = store->query(dest);
        if (csrc.isValid()&&cdest.isValid()) {
            bool srcTopic = (csrc.getCarrier()=="topic");
            bool destTopic = (cdest.getCarrier()=="topic");
            if (!(srcTopic||destTopic)) {
                if (verbose) printf("++> check connection %s %s\n", 
                                    srcFull.c_str(), destFull.c_str());
                connect(srcFull,destFull);
            }
        }
        if (mode!="") {
            ConstString mode_name = mode;
            if (mode_name=="from") {
                if (!csrc.isValid()) {
                    removeSubscription(src,dest);
                }
            } else if (mode_name=="to") {
                if (!cdest.isValid()) {
                    removeSubscription(src,dest);
                }
            }
        }
    }
    return false;
}
Example #3
0
static bool needsLookup(const Contact& contact)
{
    if (contact.getHost() != "") {
        return false;
    }
    if (contact.getCarrier() == "topic") {
        return false;
    }
    return true;
}
Example #4
0
Contact RosNameSpace::rosify(const Contact& contact) {
    ConstString carrier = ((contact.getCarrier() == "rosrpc")  ? "rosrpc" : "http");
    ConstString hostname = contact.getHost();
    if (yarp::os::impl::NameConfig::isLocalName(hostname)) {
        char hn[HOST_NAME_MAX];
        yarp::os::gethostname(hn, sizeof(hn));
        hostname = hn;
    }
    return Contact(carrier, hostname, contact.getPort());
}
Example #5
0
ConstString NameServer::textify(const Contact& address) {
    ConstString result = "";
    if (address.isValid()) {
        if (address.getPort()>=0) {
            result = "registration name ";
            result = result + address.getRegName() +
                " ip " + address.getHost() + " port " +
                NetType::toString(address.getPort()) + " type " +
                address.getCarrier() + "\n";
        } else {
            result = "registration name ";
            result = result + address.getRegName() +
                " ip " + "none" + " port " +
                "none" + " type " +
                address.getCarrier() + "\n";
        }
    }
    return result;
}
Example #6
0
 void appendEntry(yarp::os::Bottle& reply, const Contact& c) {
   Bottle& info = reply.addList();
   info.addString("registration");
   info.addString("name");
   info.addString(c.getName().c_str());
   info.addString("ip");
   info.addString(c.getHost().c_str());
   info.addString("port");
   info.addInt(c.getPort());
   info.addString("type");
   info.addString(c.getCarrier().c_str());
 }
Example #7
0
bool NetworkBase::write(const Contact& contact,
                       PortWriter& cmd,
                       PortReader& reply,
                       bool admin,
                       bool quiet,
                       double timeout) {
    ContactStyle style;
    style.admin = admin;
    style.quiet = quiet;
    style.timeout = timeout;
    style.carrier = contact.getCarrier();
    return write(contact,cmd,reply,style);
}
Example #8
0
int yarp_link(const char *from, const char *to) {
    //TODO: will it ever be possible to hard link ports?
    //  If possible, it might be an alias for yarp_simlink, as with YARP 
    //  there isn't a sym/hard linking difference

    //Create the new Contact
    Contact src = Network::queryName(from);

    printf("source [%s] is %s\n", from, src.toString().c_str());

    Contact dest = Contact::byName(to).addSocket(src.getCarrier(),src.getHost(),src.getPort());

    printf("dest [%s] should be %s\n", to, src.toString().c_str());


    return 0;
}
Example #9
0
bool NetworkProfiler::yarpNameList(ports_name_set &ports, bool complete) {
    ports.clear();

    ContactStyle style;
    style.quiet = true;
    style.timeout = 3.0;
    string nameserver = NetworkBase::getNameServerName();
    Bottle msg, reply;
    msg.addString("bot");
    msg.addString("list");
    if(!NetworkBase::write(Contact(nameserver), msg, reply, style)) {
        yError() << "Cannot write to yarp name server";
        return false;
    }

    if(reply.size() == 0) {
        yError() << "Empty reply from yarp name server";
        return false;
    }

    for (int i=1; i<reply.size(); i++) {
        Bottle *entry = reply.get(i).asList();
        if(entry != nullptr) {
            bool shouldTake = false;
            ConstString portname = entry->check("name", Value("")).asString();
            if(complete)
            {
                shouldTake = portname != "";
            }
            else
            {
                shouldTake = portname != "" && portname != "fallback" && portname != nameserver;
            }
            if (shouldTake) {
                Contact c = Contact::fromConfig(*entry);
                if(c.getCarrier() != "mcast")
                    ports.push_back(*entry);
            }
        }
    }

    return true;
}
Example #10
0
bool NameServiceOnTriples::cmdUnregister(NameTripleState& act) {
    ConstString port = act.cmd.get(1).asString();
    //printf(" - unregister %s\n", port.c_str());
    announce(port,-1);
    lock();
    Contact contact = query(port,act,"",true);
    alloc->freePortResources(contact);
    act.reply.addString("old");
    Triple t;
    t.setNameValue("port",port.c_str());
    int result = act.mem.find(t, YARP_NULLPTR);
    TripleContext context;
    context.setRid(result);
    if (result!=-1) {
        t.setNameValue("owns","*");
        list<Triple> lst = act.mem.query(t,&context);
        unlock();
        for (list<Triple>::iterator it=lst.begin();it!=lst.end();it++) {
            act.cmd.clear();
            act.cmd.addString("unregister");
            act.cmd.addString(it->value.c_str());
            cmdUnregister(act);
        }
        lock();
        t.setNsNameValue("*","*","*");
        act.mem.remove_query(t,&context);

        t.setNameValue("port",port.c_str());
        act.mem.remove_query(t, YARP_NULLPTR);
        // now, query to report that there is nothing there

        if (contact.getCarrier()!="mcast") {
            Bottle& event = act.event.addList();
            event.addVocab(Vocab::encode("del"));
            event.addString(port);
        }
    }

    act.mem.reset();
    unlock();

    return cmdQuery(act);
}
Example #11
0
Contact RosNameSpace::queryName(const ConstString& name) {
    dbg_printf("ROSNameSpace queryName(%s)\n", name.c_str());
    NestedContact nc(name);
    ConstString full = name;
    ConstString node = nc.getNodeName();
    ConstString srv = nc.getNestedName();
    ConstString cat = nc.getCategory();
    bool is_service = false;

    Bottle cmd,reply;
    if (cat.find("-1")==ConstString::npos) {
        cmd.addString("lookupNode");
        cmd.addString("dummy_id");
        cmd.addString(toRosNodeName(node));
        NetworkBase::write(getNameServerContact(),
                           cmd, reply);
    }
    Contact contact;
    if (reply.get(0).asInt()!=1) {
        cmd.clear();
        reply.clear();
        cmd.addString("lookupService");
        cmd.addString("dummy_id");
        cmd.addString(toRosNodeName(node));
        NetworkBase::write(getNameServerContact(),
                           cmd, reply);
        is_service = true;
    }
    contact = Contact::fromString(reply.get(2).asString());
    // unfortunate differences in labeling carriers
    if (contact.getCarrier()=="rosrpc") {
        contact = contact.addCarrier(ConstString("rossrv+service.") + name);
    } else {
        contact = contact.addCarrier("xmlrpc");
    }
    contact = contact.addName(name);

    if (srv == "" || !is_service) return contact;

    return Contact();
}
Example #12
0
int yarp_rename(const char *from, const char *to) {
    //TODO: the current code just renames ports, eg:
    //  /read can become /rd, but /read/rd1 cannot become /rd/rd1
    //  every subport/subdirectory should have to be renamed

    YPath ypath(from);
    if (!ypath.isPort()) { //Check that the path exists? Is it right?
        return -ENOENT;
    }


    //Create the new Contact
    Contact src = Network::queryName(from);
    Network::unregisterContact(src);

    Contact dest(to, src.getCarrier(), src.getHost(), src.getPort());

    Network::registerContact(dest);

    return 0;
}
Example #13
0
Contact RosNameSpace::rosify(const Contact& contact) {
    if (contact.getCarrier()=="rosrpc") return contact;
    return Contact::bySocket("http",contact.getHost().c_str(),
                             contact.getPort());
}
Example #14
0
bool NameServiceOnTriples::cmdQuery(NameTripleState& act, bool nested) {
    ConstString port = act.cmd.get(1).asString();

    ParseName parser;
    parser.apply(port.c_str());
    port = parser.getPortName();

    /*
    // port names may be prefixed - sort that out
    ConstString base = port;
    ConstString pat = "";
    if (base.find("/net=") == 0 || base.find("/NET=") == 0) {
        int patStart = 5;
        int patEnd = base.find('/',patStart);
        if (patEnd>=patStart) {
            pat = base.substr(patStart,patEnd-patStart);
            base = base.substr(patEnd);
        }
        port = base;
    }
    */

    if (act.reply.size()==0 && !act.bottleMode) {
        act.reply.addString("old");
    }
    Bottle& q=(act.bottleMode&&!act.nestedMode)?
        act.reply :
        act.reply.addList();
    Contact c = query(port, act, parser.getNetworkChoice(), nested);
    ConstString host = c.getHost();
    ConstString carrier = c.getCarrier();
    int sock = c.getPort();
    if (c.isValid()) {
        if (!act.bottleMode) {
            q.addString("registration");
            q.addString("name");
            q.addString(port);
            q.addString("ip");
            q.addString(host);
            q.addString("port");
            q.addInt(sock);
            q.addString("type");
            q.addString(carrier);
        } else {
            Bottle bname;
            bname.addString("name");
            bname.addString(port);
            Bottle bip;
            bip.addString("ip");
            bip.addString(host);
            Bottle bnum;
            bnum.addString("port_number");
            bnum.addInt(sock);
            Bottle bcarrier;
            bcarrier.addString("carrier");
            bcarrier.addString(carrier);
            q.addString("port");
            q.addList() = bname;
            q.addList() = bip;
            q.addList() = bnum;
            q.addList() = bcarrier;
        }
    } else {
        if (act.bottleMode) {
            Bottle bstate;
            bstate.addString("error");
            bstate.addInt(-2);
            bstate.addString("port not known");
            q.addString("port");
            q.addList() = bstate;
        }
    }
    return true;
}
Example #15
0
Contact Contact::fromString(const ConstString& txt) {
    ConstString str(txt);
    Contact c;
    ConstString::size_type start = 0;
    ConstString::size_type base = str.find("://");
    ConstString::size_type offset = 2;
    if (base==ConstString::npos) {
        base = str.find(":/");
        offset = 1;
    }
    if (base==ConstString::npos) {
        if (str.length()>0 && str[0] == '/') {
            base = 0;
            offset = 0;
        }
    }
    if (base!=ConstString::npos) {
        c = Contact::byCarrier(str.substr(0,base));
        start = base+offset;
        // check if we have a direct machine:NNN syntax
        ConstString::size_type colon = ConstString::npos;
        int mode = 0;
        int nums = 0;
        ConstString::size_type i;
        for (i=start+1; i<str.length(); i++) {
            char ch = str[i];
            if (ch==':') {
                if (mode == 0) {
                    colon = i;
                    mode = 1;
                    continue;
                } else {
                    mode = -1;
                    break;
                }
            }
            if (ch=='/') {
                break;
            }
            if (mode==1) {
                if (ch>='0'&&ch<='9') {
                    nums++;
                    continue;
                } else {
                    mode = -1;
                    break;
                }
            }
        }
        if (mode==1 && nums>=1) {
            // yes, machine:nnn
            ConstString machine = str.substr(start+1,colon-start-1);
            ConstString portnum = str.substr(colon+1, nums);
            c = c.addSocket(c.getCarrier()==""?"tcp":c.getCarrier().c_str(),
                            machine,
                            atoi(portnum.c_str()));
            start = i;
        }
    }
    ConstString rname = str.substr(start);
    if (rname!="/") {
        c = c.addName(rname.c_str());
    }
    return c;
}
Example #16
0
Contact NameServer::registerName(const ConstString& name,
                                 const Contact& address,
                                 const ConstString& remote) {
    bool reusablePort = false;
    bool reusableIp = false;

    //YARP_DEBUG(Logger::get(),"in registerName...");

    if (name!="...") {
        unregisterName(name);
    }

    Contact suggestion = address;

    if (!suggestion.isValid()) {
        suggestion = Contact(name, "...", "...", 0);
    }

    ConstString portName = name;
    if (portName == "...") {
        portName = tmpNames.get();
    }

    ConstString carrier = suggestion.getCarrier();
    if (carrier == "...") {
        carrier = "tcp";
    }

    ConstString machine = suggestion.getHost();
    int overridePort = 0;
    if (machine == "...") {
        if (carrier!="mcast") {
            if (remote=="...") {
                YARP_ERROR(Logger::get(),"remote machine name was not found!  can only guess it is local...");
                machine = "127.0.0.1";
            } else {
                machine = remote;
            }
        } else {
            machine = mcastRecord.get();
            overridePort = mcastRecord.lastPortNumber();
            reusableIp = true;
        }
    }

    int port = suggestion.getPort();
    if (port == 0) {
        if (overridePort) {
            port = overridePort;
        } else {
            port = getHostRecord(machine).get();
            reusablePort = true;
        }
    }

    suggestion = Contact(portName, carrier, machine, port);

    YARP_DEBUG(Logger::get(),ConstString("Registering ") +
               suggestion.toURI() + " for " + suggestion.getRegName());

    NameRecord& nameRecord = getNameRecord(suggestion.getRegName());
    nameRecord.setAddress(suggestion,reusablePort,reusableIp);

    Bottle event;
    event.addVocab(Vocab::encode("add"));
    event.addString(suggestion.getRegName().c_str());
    onEvent(event);

    return nameRecord.getAddress();
}
Example #17
0
Contact NameClient::registerName(const String& name, const Contact& suggest) {
    String np = getNamePart(name);
    Bottle cmd;
    cmd.addString("register");
    if (np!="") {
        cmd.addString(np.c_str());
    } else {
        cmd.addString("...");
    }
    ConstString prefix = NetworkBase::getEnvironment("YARP_IP");
    NestedContact nc = suggest.getNested();
    ConstString typ = nc.getTypeNameStar();
    if (suggest.isValid()||prefix!=""||typ!="*") {
        if (suggest.getCarrier()!="") {
            cmd.addString(suggest.getCarrier().c_str());
        } else {
            cmd.addString("...");
        }
        if (suggest.getHost()!="") {
            cmd.addString(suggest.getHost().c_str());
        } else {
            if (prefix!="") {
                Bottle ips = NameConfig::getIpsAsBottle();
                for (int i=0; i<ips.size(); i++) {
                    String ip = ips.get(i).asString().c_str();
                    if (ip.find(prefix)==0) {
                        prefix = ip.c_str();
                        break;
                    }
                }
            }
            cmd.addString((prefix!="")?prefix:"...");
        }
        if (suggest.getPort()!=0) {
            cmd.addInt(suggest.getPort());
        } else {
            cmd.addString("...");
        }
        if (typ!="*") {
            cmd.addString(typ);
        }
    }
    Bottle reply;
    send(cmd,reply);

    Contact address = extractAddress(reply);
    if (address.isValid()) {
        String reg = address.getRegName();

        /*

          // this never really got used

        cmd.fromString("set /port offers tcp text text_ack udp mcast shmem name_ser");
        cmd.get(1) = Value(reg.c_str());
        send(cmd,reply);

        // accept the same set of carriers
        cmd.get(2) = Value("accepts");
        send(cmd,reply);
        */

        cmd.clear();
        cmd.addString("set");
        cmd.addString(reg.c_str());
        cmd.addString("ips");
        cmd.append(NameConfig::getIpsAsBottle());
        send(cmd,reply);

        cmd.clear();
        cmd.addString("set");
        cmd.addString(reg.c_str());
        cmd.addString("process");
        cmd.addInt(ACE_OS::getpid());
        send(cmd,reply);
    }
    return address;
}
Example #18
0
static int metaConnect(const ConstString& src,
                       const ConstString& dest,
                       ContactStyle style,
                       int mode) {
    YARP_SPRINTF3(Logger::get(),debug,
                  "working on connection %s to %s (%s)",
                  src.c_str(),
                  dest.c_str(),
                  (mode==YARP_ENACT_CONNECT)?"connect":((mode==YARP_ENACT_DISCONNECT)?"disconnect":"check")
                  );

    // get the expressed contacts, without name server input
    Contact dynamicSrc = Contact::fromString(src);
    Contact dynamicDest = Contact::fromString(dest);

    bool topical = style.persistent;
    if (dynamicSrc.getCarrier()=="topic" ||
        dynamicDest.getCarrier()=="topic") {
        topical = true;
    }

    bool topicalNeedsLookup = !getNameSpace().connectionHasNameOfEndpoints();

    // fetch completed contacts from name server, if needed
    Contact staticSrc;
    Contact staticDest;
    if (needsLookup(dynamicSrc)&&(topicalNeedsLookup||!topical)) {
        staticSrc = NetworkBase::queryName(dynamicSrc.getName());
        if (!staticSrc.isValid()) {
            if (!style.persistent) {
                if (!style.quiet) {
                    fprintf(stderr, "Failure: could not find source port %s\n",
                            src.c_str());
                }
                return 1;
            } else {
                staticSrc = dynamicSrc;
            }
        }
    } else {
        staticSrc = dynamicSrc;
    }
    if (staticSrc.getCarrier()=="") {
        staticSrc.setCarrier("tcp");
    }
    if (staticDest.getCarrier()=="") {
        staticDest.setCarrier("tcp");
    }

    if (needsLookup(dynamicDest)&&(topicalNeedsLookup||!topical)) {
        staticDest = NetworkBase::queryName(dynamicDest.getName());
        if (!staticDest.isValid()) {
            if (!style.persistent) {
                if (!style.quiet) {
                    fprintf(stderr, "Failure: could not find destination port %s\n",
                            dest.c_str());
                }
                return 1;
            } else {
                staticDest = dynamicDest;
            }
        }
    } else {
        staticDest = dynamicDest;
    }

    if (staticSrc.getCarrier()=="xmlrpc" &&
        (staticDest.getCarrier()=="xmlrpc"||(staticDest.getCarrier().find("rossrv")==0))&&
        mode==YARP_ENACT_CONNECT) {
        // Unconnectable in general
        // Let's assume the first part is a YARP port, and use "tcp" instead
        staticSrc.setCarrier("tcp");
        staticDest.setCarrier("tcp");
    }

    ConstString carrierConstraint = "";

    // see if we can do business with the source port
    bool srcIsCompetent = false;
    bool srcIsTopic = false;
    if (staticSrc.getCarrier()!="topic") {
        if (!topical) {
            Carrier *srcCarrier = YARP_NULLPTR;
            if (staticSrc.getCarrier()!="") {
                srcCarrier = Carriers::chooseCarrier(staticSrc.getCarrier().c_str());
            }
            if (srcCarrier!=YARP_NULLPTR) {
                ConstString srcBootstrap = srcCarrier->getBootstrapCarrierName();
                if (srcBootstrap!="") {
                    srcIsCompetent = true;
                } else {
                    carrierConstraint = staticSrc.getCarrier();
                }
                delete srcCarrier;
                srcCarrier = YARP_NULLPTR;
            }
        }
    } else {
        srcIsTopic = true;
    }

    // see if we can do business with the destination port
    bool destIsCompetent = false;
    bool destIsTopic = false;
    if (staticDest.getCarrier()!="topic") {
        if (!topical) {
            Carrier *destCarrier = YARP_NULLPTR;
            if (staticDest.getCarrier()!="") {
                destCarrier = Carriers::chooseCarrier(staticDest.getCarrier().c_str());
            }
            if (destCarrier!=YARP_NULLPTR) {
                ConstString destBootstrap = destCarrier->getBootstrapCarrierName();
                if (destBootstrap!="") {
                    destIsCompetent = true;
                } else {
                    carrierConstraint = staticDest.getCarrier();
                }
                delete destCarrier;
                destCarrier = YARP_NULLPTR;
            }
        }
    } else {
        destIsTopic = true;
    }

    if (srcIsTopic||destIsTopic) {
        Bottle cmd, reply;
        NameSpace& ns = getNameSpace();

        bool ok = false;
        if (srcIsTopic) {
            if (mode==YARP_ENACT_CONNECT) {
                ok = ns.connectTopicToPort(staticSrc,staticDest,style);
            } else if (mode==YARP_ENACT_DISCONNECT) {
                ok = ns.disconnectTopicFromPort(staticSrc,staticDest,style);
            } else {
                fprintf(stderr,"Failure: cannot check subscriptions yet\n");
                return 1;
            }
        } else {
            if (mode==YARP_ENACT_CONNECT) {
                ok = ns.connectPortToTopic(staticSrc,staticDest,style);
            } else if (mode==YARP_ENACT_DISCONNECT) {
                ok = ns.disconnectPortFromTopic(staticSrc,staticDest,style);
            } else {
                fprintf(stderr,"Failure: cannot check subscriptions yet\n");
                return 1;
            }
        }
        if (!ok) {
            return 1;
        }
        if (!style.quiet) {
            if (style.verboseOnSuccess) {
                fprintf(stderr,"Success: connection to topic %s.\n", mode==YARP_ENACT_CONNECT ? "added" : "removed");
            }
        }
        return 0;
    }

    if (dynamicSrc.getCarrier()!="") {
        style.carrier = dynamicSrc.getCarrier();
    }

    if (dynamicDest.getCarrier()!="") {
        style.carrier = dynamicDest.getCarrier();
    }


    if (style.carrier!="" && carrierConstraint!="") {
        if (style.carrier!=carrierConstraint) {
            fprintf(stderr,"Failure: conflict between %s and %s\n",
                    style.carrier.c_str(),
                    carrierConstraint.c_str());
            return 1;
        }
    }
    if (carrierConstraint!="") {
        style.carrier = carrierConstraint;
    }
    if (style.carrier=="") {
        style.carrier = staticDest.getCarrier();
    }
    if (style.carrier=="") {
        style.carrier = staticSrc.getCarrier();
    }

    bool connectionIsPush = false;
    bool connectionIsPull = false;
    Carrier *connectionCarrier = YARP_NULLPTR;
    if (style.carrier!="topic") {
        connectionCarrier = Carriers::chooseCarrier(style.carrier.c_str());
        if (connectionCarrier!=YARP_NULLPTR) {
            connectionIsPush = connectionCarrier->isPush();
            connectionIsPull = !connectionIsPush;
        }
    }

    int result = -1;
    if ((srcIsCompetent&&connectionIsPush)||topical) {
        // Classic case.
        Contact c = Contact::fromString(dest);
        if (connectionCarrier!=YARP_NULLPTR) delete connectionCarrier;
        return enactConnection(staticSrc,c,style,mode,false);
    }
    if (destIsCompetent&&connectionIsPull) {
        Contact c = Contact::fromString(src);
        if (connectionCarrier!=YARP_NULLPTR) delete connectionCarrier;
        return enactConnection(staticDest,c,style,mode,true);
    }

    if (connectionCarrier!=YARP_NULLPTR) {
        if (!connectionIsPull) {
            Contact c = Contact::fromString(dest);
            result = connectionCarrier->connect(staticSrc,c,style,mode,false);
        } else {
            Contact c = Contact::fromString(src);
            result = connectionCarrier->connect(staticDest,c,style,mode,true);
        }
    }
    if (connectionCarrier!=YARP_NULLPTR) {
        delete connectionCarrier;
        connectionCarrier = YARP_NULLPTR;
    }
    if (result!=-1) {
        if (!style.quiet) {
            if (result==0) {
                if (style.verboseOnSuccess) {
                    printf("Success: added connection using custom carrier method\n");
                }
            } else {
                printf("Failure: custom carrier method did not work\n");
            }
        }
        return result;
    }

    if (mode!=YARP_ENACT_DISCONNECT) {
        fprintf(stderr,"Failure: no way to make connection %s->%s\n", src.c_str(), dest.c_str());
    }

    return 1;
}
Example #19
0
void yarp::os::impl::HttpTwoWayStream::apply(char ch) {
    if (ch=='\r') { return; }
    if (ch == '\n') {
        proc = "";
        Contact addr = yarp::os::impl::NameClient::extractAddress(part);
        if (addr.isValid()) {
            if (addr.getCarrier()=="tcp"&&
                (addr.getRegName().find("/quit")==ConstString::npos)) {
                proc += "<a href=\"http://";
                proc += addr.getHost();
                proc += ":";
                proc += NetType::toString(addr.getPort());
                proc += "\">";
                proc += addr.getRegName();
                proc += "</A> ";
                size_t len = addr.getRegName().length();
                size_t target = 30;
                if (len<target) {
                    for (size_t i=0; i<target-len; i++) {
                        proc += " ";
                    }
                }
                proc += "(";
                proc += addr.toString().c_str();
                proc += ")";
                proc += "\n";
            } else {
                // Don't show non tcp connections
                //proc += part;
                //proc += "\n";
            }
        } else {
            if ((part[0]=='\"'&&part[1]=='[')||(part[0]=='+')) {
                // translate this to a form
                if (part[0]=='+') { part[0] = ' '; }
                ConstString org = part;
                part = "<p><form method=post action='/form'>";
                size_t i=0;
                for (i=0; i<org.length(); i++) {
                    if (org[i]=='"') {
                        org[i] = ' ';
                    }
                }
                part += "<input type=hidden name=data value=\"";
                part += org;
                part += "\">";
                part += org;
                org += " ";
                bool arg = false;
                ConstString var = "";
                for (i=0; i<org.length(); i++) {
                    char ch = org[i];
                    if (arg) {
                        if ((ch>='A'&&ch<='Z')||
                            (ch>='a'&&ch<='z')||
                            (ch>='0'&&ch<='9')||
                            (ch=='_')) {
                            var += ch;
                        } else {
                            arg = false;
                            part += "\n    ";
                            part += var;
                            part += " ";
                            part += "<input type=text name=";
                            part += var;
                            part += " size=5 value=\"\">";
                            var = "";
                        }
                    }
                    if (ch=='$') {
                        arg = true;
                    }
                }
                part += "<input type=submit value=\"go\">";
                part += "</form></p>";
            }
            proc += part;
            proc += "\n";
        }
        if (data||!filterData) {
            Bytes tmp((char*)proc.c_str(),proc.length());
            delegate->getOutputStream().write(tmp);
            delegate->getOutputStream().flush();
        }
        data = false;
        if (proc[0] == 'd' || proc[0] == 'D') {
            data = true;
        }
        part = "";
    } else {
        part += ch;
    }
}
Example #20
0
bool BootstrapServer::configFileBootstrap(yarp::os::Contact& contact,
                                          bool configFileRequired,
                                          bool mayEditConfigFile) {
    Contact suggest = contact;

    // see what address is lying around
    Contact prev;
    NameConfig conf;
    if (conf.fromFile()) {
        prev = conf.getAddress();
    } else if (configFileRequired) {
        fprintf(stderr,"Could not read configuration file %s\n",
                conf.getConfigFileName().c_str());
        return false;
    }

    // merge
    if (prev.isValid()) {
        if (suggest.getHost() == "...") {
            suggest.setHost(prev.getHost());
        }
        if (suggest.getCarrier() == "...") {
            suggest.setCarrier(prev.getCarrier());
        }
        if (suggest.getPort() == 0) {
            suggest.setPort(prev.getPort());
        }
    }

    if (suggest.getRegName() == "...") {
        suggest.setName(conf.getNamespace());
    }

    // still something not set?
    if (suggest.getPort() == 0) {
        suggest.setPort(10000);
    }
    if (suggest.getHost() == "...") {
        // should get my IP
        suggest.setHost(conf.getHostName());
    }

    if (!configFileRequired)  {
        // finally, should make sure IP is local, and if not, correct it
        if (!conf.isLocalName(suggest.getHost())) {
            fprintf(stderr,"Overriding non-local address for name server\n");
            suggest.setHost(conf.getHostName());
        } else {
            // Let's just check we're not a loopback
            ConstString betterHost = conf.getHostName(false,suggest.getHost());
            if (betterHost!=suggest.getHost()) {
                fprintf(stderr,"Overriding loopback address for name server\n");
                suggest.setHost(betterHost);
            }
        }
    }
    else
    {
        if (!conf.isLocalName(conf.getHostName())) {
            fprintf(stderr,"The address written in config file doesn't belong any interface \n");
            return false;
        }
        suggest.setHost(conf.getHostName());
    }

    bool changed = false;
    if (prev.isValid()) {
        changed = (prev.getHost() != suggest.getHost()) ||
            (prev.getPort() != suggest.getPort()) ||
            (conf.getMode() != "yarp" && conf.getMode() != "");
    }
    if (changed && !mayEditConfigFile) {
        fprintf(stderr,"PROBLEM: need to change settings in %s\n",
                conf.getConfigFileName().c_str());
        fprintf(stderr,"  Current settings: host %s port %d family %s\n",
                prev.getHost().c_str(), prev.getPort(),
                (conf.getMode()=="")?"yarp":conf.getMode().c_str());
        fprintf(stderr,"  Desired settings:  host %s port %d family %s\n",
                suggest.getHost().c_str(), suggest.getPort(), "yarp");
        fprintf(stderr,"Please specify '--write' if it is ok to overwrite current settings, or\n");
        if(!configFileRequired)
            fprintf(stderr,"Please specify '--read' to use the current settings, or\n");
        else
            fprintf(stderr,"Please set an existing address in config file, or\n");
        fprintf(stderr,"delete %s\n", conf.getConfigFileName().c_str());
        return false;
    }
    bool shouldSave = changed || !prev.isValid();

    if (shouldSave) {
        // and save
        conf.setAddress(suggest);
        if (!conf.toFile()) {
            fprintf(stderr,"Could not save configuration file %s\n",
                    conf.getConfigFileName().c_str());
        }
    }

    contact = suggest;
    return true;
}
Example #21
0
bool Port::open(const Contact& contact, bool registerName,
                const char *fakeName) {
    Contact contact2 = contact;

    if (!NetworkBase::initialized()) {
        YARP_ERROR(Logger::get(), "YARP not initialized; create a yarp::os::Network object before using ports");
        return false;
    }

    ConstString n = contact2.getName();

    bool local = false;
    if (n == "" && contact2.getPort()<=0) {
        local = true;
        registerName = false;
        n = "...";
    }

    NestedContact nc(n);
    if (nc.getNestedName()!="") {
        if (nc.getNodeName() == "") {
            Nodes& nodes = NameClient::getNameClient().getNodes();
            nodes.requireActiveName();
            ConstString node_name = nodes.getActiveName();
            if (node_name!="") {
                n = n + node_name;
            }
        }
    }

    if (n!="" && n[0]!='/'  && n[0]!='=' && n!="..." && n.substr(0,3)!="...") {
        if (fakeName==NULL) {
            Nodes& nodes = NameClient::getNameClient().getNodes();
            ConstString node_name = nodes.getActiveName();
            if (node_name!="") {
                // n = node_name + "=/" + n;
                n = "/" + n + "@" + node_name;
            }
        }
    }
    if (n!="" && n[0]!='/'  && n[0]!='=' && n!="..." && n.substr(0,3)!="...") {
        if (fakeName==NULL) {
            YARP_SPRINTF1(Logger::get(),error,
                          "Port name '%s' needs to start with a '/' character",
                          n.c_str());
            return false;
        }
    }
    if (n!="" && n!="..." && n[0]!='=' && n.substr(0,3)!="...") {
        if (fakeName==NULL) {
            ConstString prefix = NetworkBase::getEnvironment("YARP_PORT_PREFIX");
            if (prefix!="") {
                n = prefix + n;
                contact2 = contact2.addName(n);
            }
        }
    }
    PortCoreAdapter *currentCore = &(HELPER(implementation));
    if (currentCore!=NULL) {
        NestedContact nc;
        nc.fromString(n);
        if (nc.getNestedName()!="") {
            if (nc.getCategory()=="") {
                // we need to add in a category
                ConstString cat = "";
                if (currentCore->commitToRead) {
                    cat = "-";
                } else if (currentCore->commitToWrite) {
                    cat = "+";
                }
                if (cat!="") {
                    if (currentCore->commitToRpc) {
                        cat += "1";
                    }
                    contact2 = contact2.addName(nc.getNestedName() +
                                                cat +
                                                "@" +
                                                nc.getNodeName());
                } else {
                    YARP_SPRINTF1(Logger::get(),error,
                                  "Error: Port '%s' is not committed to being either an input or output port.",
                                  n.c_str());
                    YARP_SPRINTF0(Logger::get(),error,
                                  "YARP does not mind, but we are trying to register with a name server that does.");
                    YARP_SPRINTF0(Logger::get(),error,
                                  "You can call Port::setWriteOnly() or Port::setReadOnly(), OR rename the port.");
                    NestedContact nc2 = nc;
                    nc2.setCategoryWrite();
                    YARP_SPRINTF1(Logger::get(),error,
                                  "For an output port, call it: %s (+ adds data)",
                                  nc2.toString().c_str());
                    nc2.setCategoryRead();
                    YARP_SPRINTF1(Logger::get(),error,
                                  "For an input port, call it: %s (- takes data)",
                                  nc2.toString().c_str());
                    return false;
                }
            }
        }
    }

    // Allow for open() to be called safely many times on the same Port
    if (currentCore->isOpened()) {
        PortCoreAdapter *newCore = new PortCoreAdapter(*this);
        YARP_ASSERT(newCore!=NULL);
        // copy state that should survive in a new open()
        if (currentCore->checkPortReader()!=NULL) {
            newCore->configReader(*(currentCore->checkPortReader()));
        }
        if (currentCore->checkReadCreator()!=NULL) {
            newCore->configReadCreator(*(currentCore->checkReadCreator()));
        }
        if (currentCore->checkWaitAfterSend()>=0) {
            newCore->configWaitAfterSend(currentCore->checkWaitAfterSend());
        }
        close();
        delete ((PortCoreAdapter*)implementation);
        implementation = newCore;
    }

    PortCoreAdapter& core = HELPER(implementation);

    core.openable();

    if (NetworkBase::localNetworkAllocation()&&contact2.getPort()<=0) {
        YARP_DEBUG(Logger::get(),"local network allocation needed");
        local = true;
    }

    bool success = true;
    Contact caddress = Contact::bySocket(contact2.getCarrier(),
                                         contact2.getHost(),
                                         contact2.getPort())
        .addName(contact2.getName());
    caddress.setNested(contact2.getNested());
    Contact address = caddress;

    core.setReadHandler(core);
    if (contact2.getPort()>0 && contact2.getHost()!="") {
        registerName = false;
    }

    ConstString typ = getType().getName();
    if (typ!="") {
        NestedContact nc;
        nc.fromString(contact2.getName());
        nc.setTypeName(typ);
        contact2.setNested(nc);
    }

    if (registerName&&!local) {
        address = NetworkBase::registerContact(contact2);
    }

    core.setControlRegistration(registerName);
    success = (address.isValid()||local)&&(fakeName==NULL);

    if (success) {
        // create a node if needed
        Nodes& nodes = NameClient::getNameClient().getNodes();
        nodes.prepare(address.getRegName().c_str());
    }

    // If we are a service client, go ahead and connect
    if (success) {
        NestedContact nc;
        nc.fromString(address.getName());
        if (nc.getNestedName()!="") {
            if (nc.getCategory() == "+1") {
                addOutput(nc.getNestedName());
            }
        }
    }

    ConstString blame = "invalid address";
    if (success) {
        success = core.listen(address,registerName);
        blame = "address conflict";
        if (success) {
            success = core.start();
            blame = "manager did not start";
        }
    }
    if (success) {
        address = core.getAddress();
        if (registerName&&local) {
            contact2 = contact2.addSocket(address.getCarrier(),
                                          address.getHost(),
                                          address.getPort());
            contact2 = contact2.addName(address.getRegName().c_str());
            Contact newName = NetworkBase::registerContact(contact2);
            core.resetPortName(newName.getName());
            address = core.getAddress();
        } else if (core.getAddress().getRegName()=="" && !registerName) {
            core.resetPortName(core.getAddress().addCarrier("").toURI());
            core.setName(core.getAddress().getRegName());
        }

        if (core.getVerbosity()>=1) {
            if (address.getRegName()=="") {
                YARP_INFO(Logger::get(),
                          String("Anonymous port active at ") +
                          address.toURI());
            } else {
                YARP_INFO(Logger::get(),
                          String("Port ") +
                          address.getRegName() +
                          " active at " +
                          address.toURI());
            }
        }
    }

    if (fakeName!=NULL) {
        success = core.manualStart(fakeName);
        blame = "unmanaged port failed to start";
    }

    if (!success) {
        YARP_ERROR(Logger::get(),
                   String("Port ") +
                   (address.isValid()?(address.getRegName().c_str()):(contact2.getName().c_str())) +
                   " failed to activate" +
                   (address.isValid()?" at ":"") +
                   (address.isValid()?address.toURI():String("")) +
                   " (" +
                   blame.c_str() +
                   ")");
    }

    if (success) {
        // create a node if needed
        Nodes& nodes = NameClient::getNameClient().getNodes();
        nodes.add(*this);
    }

    return success;
}