Exemplo n.º 1
0
void FTPClientSession::sendPASV(SocketAddress& addr)
{
	std::string response;
	int status = sendCommand("PASV", response);
	if (!isPositiveCompletion(status)) throw FTPException("PASV command failed", response, status);
	parseAddress(response, addr);
}
Exemplo n.º 2
0
static jdwpTransportError JNICALL
socketTransport_startListening(jdwpTransportEnv* env, const char* address,
                               char** actualAddress)
{
    struct sockaddr_in sa;
    int err;

    memset((void *)&sa,0,sizeof(struct sockaddr_in));
    sa.sin_family = AF_INET;

    /* no address provided */
    if ((address == NULL) || (address[0] == '\0')) {
        address = "0";
    }

    err = parseAddress(address, &sa, INADDR_ANY);
    if (err != JDWPTRANSPORT_ERROR_NONE) {
        return err;
    }

    serverSocketFD = dbgsysSocket(AF_INET, SOCK_STREAM, 0);
    if (serverSocketFD < 0) {
        RETURN_IO_ERROR("socket creation failed");
    }

    err = setOptions(serverSocketFD);
    if (err) {
        return err;
    }

    err = dbgsysBind(serverSocketFD, (struct sockaddr *)&sa, sizeof(sa));
    if (err < 0) {
        RETURN_IO_ERROR("bind failed");
    }

    err = dbgsysListen(serverSocketFD, 1);
    if (err < 0) {
        RETURN_IO_ERROR("listen failed");
    }

    {
        char buf[20];
        int len = sizeof(sa);
        jint portNum;
        err = dbgsysGetSocketName(serverSocketFD,
                               (struct sockaddr *)&sa, &len);
        portNum = dbgsysNetworkToHostShort(sa.sin_port);
        sprintf(buf, "%d", portNum);
        *actualAddress = (*callback->alloc)((int)strlen(buf) + 1);
        if (*actualAddress == NULL) {
            RETURN_ERROR(JDWPTRANSPORT_ERROR_OUT_OF_MEMORY, "out of memory");
        } else {
            strcpy(*actualAddress, buf);
        }
    }

    return JDWPTRANSPORT_ERROR_NONE;
}
Exemplo n.º 3
0
// serve functions:
// handle_request is called from server thread. It passes a MHD_Connection
// and address to the serve functions, lets parseAddress create
// a request object and let the request object serve itself.
int httpServer::handle_request(void *cls, struct MHD_Connection *connection, const char *address,
                   const char *method, const char *version, const char *upload_data,
                   size_t *upload_data_size, void **con_cls)
{
  requestType* reqOb = parseAddress(address, connection);
  reqOb->sendResponse();
  delete reqOb;
  std::cout << "handle_request connection: " << connection << std::endl;
  return 1;
}
Exemplo n.º 4
0
Arquivo: Cfg.cpp Projeto: jacobxy/test
void Cfg::setAdminAllowedIP( const char * str )
{
    StringTokenizer tk(str, " ");
    for(size_t i = 0; i < tk.count(); ++ i)
    {
        IPMask ipm = parseAddress(tk[i]);
        if(ipm.mask < 32)
            _adminIPAllowed.push_back(ipm);
    }
}
Exemplo n.º 5
0
MailMessenger::MailMessenger(Mailbox *mailbox, const MessageChannelInfo::Participant *receiver, Profile *profile, MessageRef message) :
    mailbox(mailbox),
    receiver(receiver),
    profile(profile),
    message(message),
    userIdentity(mailbox->getOwner()),
    targetContact(NULL),
    contactRequest(NULL),
    remoteConnection(NULL)
{
    parseAddress(receiver->address);
}
Exemplo n.º 6
0
std::shared_ptr<WalletInfo> createViewWallet(CryptoNote::WalletGreen &wallet)
{
    std::cout << WarningMsg("View wallets are only for viewing incoming ")
              << WarningMsg("transactions, and cannot make transfers.")
              << std::endl;

    bool create = confirm("Is this OK?");

    std::cout << std::endl;

    if (!create)
    {
        return nullptr;
    }
    
    Crypto::SecretKey privateViewKey = getPrivateKey("Private View Key: ");

    std::string address;

    while (true)
    {
        std::cout << InformationMsg("Enter your public ")
                  << InformationMsg(WalletConfig::ticker)
                  << InformationMsg(" address: ");

        std::getline(std::cin, address);
        boost::algorithm::trim(address);

        if (parseAddress(address))
        {
            break;
        }
    }

    const std::string walletFileName = getNewWalletFileName();

    const std::string msg = "Give your new wallet a password: "******"Your view wallet ")
              << InformationMsg(address)
              << InformationMsg(" has been successfully imported!")
              << std::endl << std::endl;

    viewWalletMsg();

    return std::make_shared<WalletInfo>(walletFileName, walletPass, 
                                        address, true, wallet);
}
Exemplo n.º 7
0
list<Host> FileParser::getHosts()
{
	fstream file;
	list<Host> hosts;
	Host nextHost;
	char addressAsText[256];
	file.open(filename, ios_base::in);
	while(!file.eof())
	{
		file.getline(addressAsText,256);
		if (parseAddress(addressAsText, &nextHost))  //jezeli udalo sie uzyskac poprawny adres,
			hosts.push_back(nextHost); // dodajemy do listy
	}
	file.close();
	return hosts;
}
Exemplo n.º 8
0
/*ARGSUSED*/
static int
deleteTpgt(int operandLen, char *operand[], cmdOptions_t *options)
{
	char		*first_str	= NULL;
	tgt_node_t	*node;
	cmdOptions_t	*optionList = options;
	boolean_t	isIpv6 = B_FALSE;
	uint16_t	port;
	char		IpAddress[MAX_IPADDRESS_LEN];

	if (operand == NULL)
		return (1);
	if (options == NULL)
		return (1);

	tgt_buf_add_tag(&first_str, "delete", Tag_Start);
	tgt_buf_add_tag(&first_str, XML_ELEMENT_TPGT, Tag_Start);
	tgt_buf_add(&first_str, XML_ELEMENT_NAME, operand[0]);

	switch (optionList->optval) {
	case 'A': /* all */
		tgt_buf_add(&first_str, XML_ELEMENT_ALL, optionList->optarg);
		break;
	case 'i': /* ip address */
		if (parseAddress(optionList->optarg, 0,
		    IpAddress, 256, &port, &isIpv6) !=
		    PARSE_ADDR_OK) {
			return (1);
		}
		tgt_buf_add(&first_str, XML_ELEMENT_IPADDR, IpAddress);
		break;
	default:
		(void) fprintf(stderr, "%s: %c: %s\n",
		    cmdName, optionList->optval,
		    gettext("unknown option"));
		free(first_str);
		return (1);
	}

	tgt_buf_add_tag(&first_str, XML_ELEMENT_TPGT, Tag_End);
	tgt_buf_add_tag(&first_str, "delete", Tag_End);

	node = tgt_door_call(first_str, 0);
	free(first_str);
	return (formatErrString(node));
}
Exemplo n.º 9
0
 /**
  * `Socket` Constructor.
  *
  * Constructs a `Socket` object given a listening address/port and begins
  * listening for clients.
  *
  * @param addr `std::string` object containing the listen address
  * @param port `int` containing the port number to listen on
  */
 Socket::Socket(const std::string& addr, int port) {
   // Ensure the validity of the provided port
   if (port < 1 || port > 65535)
     throw InvalidArgument{"The provided port number is out of range."};
   // Fetch a finalized sockaddr_storage for the given address
   struct sockaddr_storage address  = parseAddress(addr);
   // Use the appropriate setup helper depending on the address family
   if (address.ss_family == AF_INET || address.ss_family == AF_INET6) {
     // Assign the appropriate address family to describe the `Connection`
     this->family = (address.ss_family == AF_INET ?
       SocketFamily::IPv4 : SocketFamily::IPv6);
     // Determine the appropriate pointer type for the remote address
     auto addrPtr = (address.ss_family == AF_INET ?
       addr4(address) : addr6(address));
     // Store a text-based representation of the remote address
     char addressString[INET6_ADDRSTRLEN + 1] = {};
     this->host = inet_ntop(address.ss_family, addrPtr, addressString,
       INET6_ADDRSTRLEN);
     // Assign the port to the sockaddr struct
     *(this->family == SocketFamily::IPv4 ? port4(address) : port6(address)) =
       htons(this->port = port);
   }
   else {
     // Remote address has an unexpected address family
     throw InvalidArgument{"The remote address has an unexpected address "
       "family."};
   }
   // Setup the socket using the appropriate address family and type
   this->socket = ::socket(address.ss_family, SOCK_STREAM, 0);
   // Attempt to bind the socket to the listening address
   if (bind(this->socket, addr_(address), this->family == SocketFamily::IPv4 ?
       sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)) < 0) {
     // A problem occurred, close the socket and throw an exception
     close(this->socket);
     throw UnexpectedError{"Couldn't bind to [" + this->host + "]:" +
       std::to_string(this->port)};
   }
   else {
     // Allow reusing the socket
     int reuse = 1;
     setsockopt(this->socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int));
     // Listen with a backlog of 16 clients
     listen(this->socket, 16);
   }
 }
Exemplo n.º 10
0
void solve(char* line){
	if (line[0] != ' ') return;
	int pos = 0;
	int i;
	for (i = 0; i < strlen(line); i++)
    if (line[i] == ',') {pos = i; break;}
    pos = pos - 3;
	strncpy(stringAddress, &line[3], pos);
	stringAddress[pos] = '\0';
	address = parseAddress(stringAddress);

	if (line[1] == 'L' || line[1] == 'S') {
		referenceData(address);
	} else {
		referenceData(address);
		referenceData(address);
	}
}
Maybe<std::string> getDestinationAddress()
{
    while (true)
    {
        std::string transferAddr;

        std::cout << InformationMsg("What address do you want to "
                                    "transfer to?: ");

        std::getline(std::cin, transferAddr);
        boost::algorithm::trim(transferAddr);

        if (transferAddr == "cancel")
        {
            return Nothing<std::string>();
        }

        if (parseAddress(transferAddr))
        {
            return Just<std::string>(transferAddr);
        }
    }
}
Exemplo n.º 12
0
static InputParams parseCommand(int argc, char **argv) {

  InputParams inputParams;
  register int i;

  memset(&inputParams, 0, sizeof (struct _InputParams));

  if (argc < 2) {
    printUsage(argv[0]);
    exit(EXIT_FAILURE);
  }

  parseAddress(argv[1], &inputParams);

  for (i = 2; i < argc; i++) {
    if (!strncmp(argv[i], "-timeout=", 9)) {
      inputParams.hasTimeout = 1;
      inputParams.timeout = atoi(argv[i] + 9);
    } else if(!strncmp(argv[i], "-lAddress=", 10)) {
      inputParams.lAddress = argv[i]+10;
      inputParams.hasLAddress = 1;
    } else if (!strncmp(argv[i], "-outputFile=", 12)) {
      inputParams.outputFile = open(argv[i]+12, O_APPEND|O_WRONLY);
      if (inputParams.outputFile < 0) {
	fprintf(stderr, "Invalid file %s\n", argv[i]+12);
	exit(EXIT_FAILURE);
      } else {
	inputParams.hasOutput = 1;
      }
    } else {
      printUsage(argv[0]);
      exit(EXIT_FAILURE);
    }
  }
  return inputParams;
}
Exemplo n.º 13
0
StoragePtr TableFunctionMySQL::executeImpl(const ASTPtr & ast_function, const Context & context) const
{
    const ASTFunction & args_func = typeid_cast<const ASTFunction &>(*ast_function);

    if (!args_func.arguments)
        throw Exception("Table function 'mysql' must have arguments.", ErrorCodes::LOGICAL_ERROR);

    ASTs & args = typeid_cast<ASTExpressionList &>(*args_func.arguments).children;

    if (args.size() < 5 || args.size() > 7)
        throw Exception("Table function 'mysql' requires 5-7 parameters: MySQL('host:port', database, table, 'user', 'password'[, replace_query, 'on_duplicate_clause']).",
            ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    for (size_t i = 0; i < args.size(); ++i)
        args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(args[i], context);

    std::string host_port = static_cast<const ASTLiteral &>(*args[0]).value.safeGet<String>();
    std::string database_name = static_cast<const ASTLiteral &>(*args[1]).value.safeGet<String>();
    std::string table_name = static_cast<const ASTLiteral &>(*args[2]).value.safeGet<String>();
    std::string user_name = static_cast<const ASTLiteral &>(*args[3]).value.safeGet<String>();
    std::string password = static_cast<const ASTLiteral &>(*args[4]).value.safeGet<String>();

    bool replace_query = false;
    std::string on_duplicate_clause;
    if (args.size() >= 6)
        replace_query = static_cast<const ASTLiteral &>(*args[5]).value.safeGet<UInt64>() > 0;
    if (args.size() == 7)
        on_duplicate_clause = static_cast<const ASTLiteral &>(*args[6]).value.safeGet<String>();

    if (replace_query && !on_duplicate_clause.empty())
        throw Exception(
            "Only one of 'replace_query' and 'on_duplicate_clause' can be specified, or none of them",
            ErrorCodes::BAD_ARGUMENTS);

    /// 3306 is the default MySQL port number
    auto parsed_host_port = parseAddress(host_port, 3306);

    mysqlxx::Pool pool(database_name, parsed_host_port.first, user_name, password, parsed_host_port.second);

    /// Determine table definition by running a query to INFORMATION_SCHEMA.

    Block sample_block
    {
        { std::make_shared<DataTypeString>(), "name" },
        { std::make_shared<DataTypeString>(), "type" },
        { std::make_shared<DataTypeUInt8>(), "is_nullable" },
        { std::make_shared<DataTypeUInt8>(), "is_unsigned" },
        { std::make_shared<DataTypeUInt64>(), "length" },
    };

    WriteBufferFromOwnString query;
    query << "SELECT"
            " COLUMN_NAME AS name,"
            " DATA_TYPE AS type,"
            " IS_NULLABLE = 'YES' AS is_nullable,"
            " COLUMN_TYPE LIKE '%unsigned' AS is_unsigned,"
            " CHARACTER_MAXIMUM_LENGTH AS length"
        " FROM INFORMATION_SCHEMA.COLUMNS"
        " WHERE TABLE_SCHEMA = " << quote << database_name
        << " AND TABLE_NAME = " << quote << table_name
        << " ORDER BY ORDINAL_POSITION";

    MySQLBlockInputStream result(pool.Get(), query.str(), sample_block, DEFAULT_BLOCK_SIZE);

    NamesAndTypesList columns;
    while (Block block = result.read())
    {
        size_t rows = block.rows();
        for (size_t i = 0; i < rows; ++i)
            columns.emplace_back(
                (*block.getByPosition(0).column)[i].safeGet<String>(),
                getDataType(
                    (*block.getByPosition(1).column)[i].safeGet<String>(),
                    (*block.getByPosition(2).column)[i].safeGet<UInt64>() && context.getSettings().external_table_functions_use_nulls,
                    (*block.getByPosition(3).column)[i].safeGet<UInt64>(),
                    (*block.getByPosition(4).column)[i].safeGet<UInt64>()));

    }

    auto res = StorageMySQL::create(
        table_name,
        std::move(pool),
        database_name,
        table_name,
        replace_query,
        on_duplicate_clause,
        ColumnsDescription{columns},
        context);

    res->startup();
    return res;
}
Exemplo n.º 14
0
bool QGeoCodeXmlParser::parsePlace(QGeoPlace *place)
{
    /*
    <xsd:complexType name="Place">
        <xsd:all>
            <xsd:element name="location" type="gc:Location"/>
            <xsd:element minOccurs="0" name="address" type="gc:Address"/>
            <xsd:element minOccurs="0" name="alternatives" type="gc:Alternatives"/>
        </xsd:all>
        <xsd:attribute name="title" type="xsd:string" use="required"/>
        <xsd:attribute name="language" type="gc:LanguageCode" use="required"/>
    </xsd:complexType>

    <xsd:simpleType name="LanguageCode">
        <xsd:restriction base="xsd:string">
            <xsd:length value="3"/>
        </xsd:restriction>
    </xsd:simpleType>
    */

    Q_ASSERT(m_reader->isStartElement() && m_reader->name() == "place");

    if (!m_reader->attributes().hasAttribute("title")) {
        m_reader->raiseError("The element \"place\" did not have the required attribute \"title\".");
        return false;
    }

    if (!m_reader->attributes().hasAttribute("language")) {
        //m_reader->raiseError("The element \"place\" did not have the required attribute \"language\".");
        //return false;
    } else {
        QString lang = m_reader->attributes().value("language").toString();

        if (lang.length() != 3) {
            m_reader->raiseError(QString("The attribute \"language\" of the element \"place\" was not of length 3 (length was %1).").arg(lang.length()));
            return false;
        }
    }

    bool parsedLocation = false;
    bool parsedAddress = false;
    bool parsedAlternatives = false;

    while (m_reader->readNextStartElement()) {
        QString name = m_reader->name().toString();
        if (name == "location") {
            if (parsedLocation) {
                m_reader->raiseError("The element \"place\" has multiple child elements named \"location\" (exactly one expected)");
                return false;
            }

            if (!parseLocation(place))
                return false;

            parsedLocation = true;
        } else if (name == "address") {
            if (parsedAddress) {
                m_reader->raiseError("The element \"place\" has multiple child elements named \"address\" (at most one expected)");
                return false;
            }

            QGeoAddress address;
            if (!parseAddress(&address))
                return false;
            else
                place->setAddress(address);

            place->setAddress(address);

            parsedAddress = true;
        } else if (name == "alternatives") {
            if (parsedAlternatives) {
                m_reader->raiseError("The element \"place\" has multiple child elements named \"alternatives\" (at most one expected)");
                return false;
            }

            // skip alternatives for now
            // need to work out if we have a use for them at all
            // and how to store them if we get them
            m_reader->skipCurrentElement();

            parsedAlternatives = true;
        } else {
            m_reader->raiseError(QString("The element \"place\" did not expect a child element named \"%1\".").arg(m_reader->name().toString()));
            return false;
        }
    }

    if (!parsedLocation) {
        m_reader->raiseError("The element \"place\" has no child elements named \"location\" (exactly one expected)");
        return false;
    }

    return true;
}
Exemplo n.º 15
0
void EventAddress::setAddress (const ssi_char_t *address) {
    parseAddress (address);
}
Exemplo n.º 16
0
void Importer::fillPara29()
{
    parseCoutryCode(blankLine);
    parseAddress(blankLine);
}
Exemplo n.º 17
0
void Importer::parse()
{
    QFile file(inputFile);

    if (!file.open(QFile::ReadOnly))
        return;
    QTextStream in(&file);
    in.setCodec("IBM 866");

    numberDoc = 1;
    while (!in.atEnd())
    {
        QString line;
        in.readLine(); // шапка
        in.readLine(); //
        in.readLine();
        in.readLine(); // Код формы по КНД 1151078

        parsePriznak(in.readLine()); // Признак

        parseTitle(in.readLine()); // Строка с датой и номером справки
        in.readLine(); //
        in.readLine(); // п. 1
        parseINNCPP(in.readLine());  // п. 1.1
        parseOrgname(in.readLine()); // п. 1.2
        if (params[QString::number(numberDoc) + "_Orgname"].isEmpty())
                parseOrgname(in.readLine(), 1);
        in.readLine();
        parseOKATOTEL(in.readLine()); // п. 1.3 п. 1.4
        in.readLine(); // п. 2
        parseINN(in.readLine()); // п. 2.1
        in.readLine();
        parseFIOTBN(in.readLine()); // п. 2.2
        parseStatusDrGr(in.readLine()); // п. 2.3 - п. 2.5
        parseCodeDocSeriesNum(in.readLine()); // п. 2.6 - п. 2.7
        in.readLine(); // п. 2.8
        parseIndexRegCode(in.readLine());

        fillAddress();
        line = in.readLine();
        while (!line.contains(WINtoUnicode("Дом")))
        {                        
            if (line.contains(WINtoUnicode("Город")))
                parseCity(line);
            else if (line.contains(WINtoUnicode("Улица")))
                parseStreet(line);
            else if (line.contains(WINtoUnicode("Населенный пункт")))
                parseLocality(line);
            line = in.readLine();
        }
        parseHomeFlat(line);

        in.readLine();
        fillPara29();
        line = in.readLine();
        if (line.left(3) == "2.9")
        {
            parseCoutryCode(line);
            parseAddress(in.readLine());
            in.readLine();
            line = in.readLine();
        }
        parseTax(line); // п. 3
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();

        line = in.readLine();
        QChar sym(0x2514);

        int incomeTableRowsCount = 1;
        while (line[0] != sym)
        {          
            parseIncomeTable(QString::number(incomeTableRowsCount++), line);
            line = in.readLine();           
        }
        addParametr("incomeTableRowsCount", QString::number(incomeTableRowsCount));

        in.readLine();

        fillPara4();
        line = in.readLine(); // п. 4

        while (line.left(3) != " 5.")
        {
            QString para = line.left(3);
            if (para == "")
            {
            }
            else if (para == "4. ")
            {
            }
            else if (para == "4.1")
            {
                in.readLine();
                line = in.readLine();
                parseTaxDeductions(line);
            }
            else if (para == "4.2")
            {
                parsePara42(line);
            }
            else if ((para == "4.3") || (para == "4.4"))
            {
                parsePara43_44(line);
            }           
            else if (para == "4.5")
            {
                parsePara45(line);
            }
            else if (para == "4.6")
            {
                parsePara46(line);
            }
            line = in.readLine();
        }

        //in.readLine(); // п. 5       
        fillPara5();
        line = in.readLine();
        while (line[0] != sym)
        {
            QString para = line.mid(1, 4);

            if (para == "5.1.")
                parseAmountIncome(line);   // п. 5.1
            else if (para == "5.2.")
                parseTaxableAmountIncome(line); // п. 5.2
            else if (para == "5.3.")
                parseAmountOfTaxCalculated(line); // п. 5.3
            else if (para == "5.4.")
                parseAmountOfTaxWithheld(line); // п. 5.4
            else if (para == "5.5.")
                parsePara55Sum(line);  // п. 5.5
            else if (para == "5.6.")
                parsePara56Sum(line);  // п. 5.6
            else if (para == "5.7.")
                parsePara57Sum(line);  // п. 5.7
            else if (para == "5.8.")
                parsePara58Sum(line);  // п. 5.8
            else if (para == "5.9.")
                parsePara59Sum(line);  // п. 5.9
            else if (para == "5.10")
                parsePara510Sum(line);  // п. 5.10
            line = in.readLine();
        }

        in.readLine();
        in.readLine();
        parseBottom(in.readLine());

        QChar pageBreak(0x0C);
        line = in.readLine();
        while (!in.atEnd() && line != pageBreak)        
            line = in.readLine();

        numberDoc++;
    }
    file.close();

}
Exemplo n.º 18
0
static jdwpTransportError JNICALL
socketTransport_attach(jdwpTransportEnv* env, const char* addressString, jlong attachTimeout,
                       jlong handshakeTimeout)
{
    struct sockaddr_in sa;
    int err;

    if (addressString == NULL || addressString[0] == '\0') {
        RETURN_ERROR(JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT, "address is missing");
    }

    err = parseAddress(addressString, &sa, 0x7f000001);
    if (err != JDWPTRANSPORT_ERROR_NONE) {
        return err;
    }

    socketFD = dbgsysSocket(AF_INET, SOCK_STREAM, 0);
    if (socketFD < 0) {
        RETURN_IO_ERROR("unable to create socket");
    }

    err = setOptions(socketFD);
    if (err) {
        return err;
    }

    /*
     * To do a timed connect we make the socket non-blocking
     * and poll with a timeout;
     */
    if (attachTimeout > 0) {
        dbgsysConfigureBlocking(socketFD, JNI_FALSE);
    }

    err = dbgsysConnect(socketFD, (struct sockaddr *)&sa, sizeof(sa));
    if (err == DBG_EINPROGRESS && attachTimeout > 0) {
        err = dbgsysFinishConnect(socketFD, (long)attachTimeout);

        if (err == DBG_ETIMEOUT) {
            dbgsysConfigureBlocking(socketFD, JNI_TRUE);
            RETURN_ERROR(JDWPTRANSPORT_ERROR_TIMEOUT, "connect timed out");
        }
    }

    if (err < 0) {
        RETURN_IO_ERROR("connect failed");
    }

    if (attachTimeout > 0) {
        dbgsysConfigureBlocking(socketFD, JNI_TRUE);
    }

    err = handshake(socketFD, handshakeTimeout);
    if (err) {
        dbgsysSocketClose(socketFD);
        socketFD = -1;
        return err;
    }

    return JDWPTRANSPORT_ERROR_NONE;
}
int main(int argc, char * const argv[])
{
	struct option long_options[] = {
		{ "daemon", no_argument, nullptr, 'd' },
		{ "user", required_argument, nullptr, 'u' },
		{ "varnish", required_argument, nullptr, 'v' },
		{ "redis", required_argument, nullptr, 'r' },
		{ 0, 0, 0, 0 }
	};

	bool daemonize = false;
	std::string userName;
	std::string varnishAddr;
	std::string redisAddr;

	for (bool done = false; !done; ) {
		int long_index = 0;
		switch (getopt_long(argc, argv, "hdu:v:r:", long_options, &long_index)) {
			case 'h':
				printHelp();
				return 0;
			case 'd':
				daemonize = true;
				break;
			case 'u':
				userName = optarg;
				break;
			case 'v':
				varnishAddr = optarg;
				break;
			case 'r':
				redisAddr = optarg;
				break;
			case 0: // long opt with value != NULL
				done = true;
				break;
			case '?': // ambiguous match / unknown arg
				printHelp();
				return 1;
			default:
				done = true;
				break;
		}
	}

	if (varnishAddr.empty() || redisAddr.empty()) {
		printf("varnish: %s\n", varnishAddr.c_str());
		printf("redis: %s\n", redisAddr.c_str());
		printHelp();
		return 2;
	}

	if (!dropPrivileges(userName))
		return 3;

	ev::default_loop ev;

	auto varnish_config = std::make_shared<varnish_cfg>();
	if (!parseAddress(varnishAddr, varnish_config->host, varnish_config->port))
		return 4;

	auto redis_config = std::make_shared<redis_cfg>();
	redis_config->skey = REDIS_QUEUE_KEY;
	if (!parseAddress(redisAddr, redis_config->host, redis_config->port))
		return 5;

	std::unique_ptr<PurgeWorker> worker(new PurgeWorker(ev, redis_config.get(), varnish_config.get()));

	if (daemonize && ::daemon(false /*no chdir?*/, false /*no close?*/) < 0) {
		fprintf(stderr, "Daemonizing failed: %s\n", strerror(errno));
		return 6;
	}

	worker->run();

	return 0;
}
void transfer(std::shared_ptr<WalletInfo> walletInfo,
              std::vector<std::string> args)
{
    uint16_t mixin;
    std::string address;
    uint64_t amount;
    uint64_t fee = CryptoNote::parameters::MINIMUM_FEE;
    std::string extra;

    /* Check we have enough args for the default required parameters */
    if (args.size() >= 3)
    {
        if (parseMixin(args[0]) && parseAddress(args[1])
         && parseAmount(args[2]))
        {
            mixin = std::stoi(args[0]);
            address = args[1];
            parseAmount(args[2], amount);
        }
        else
        {
            return;
        }
    }
    else
    {
        std::cout << WarningMsg("Not enough arguments given!") << std::endl
                  << "Try running just " << SuggestionMsg("transfer")
                  << " for a walk through guide to transferring." << std::endl;
        return;
    }

    for (size_t i = 0; i < args.size(); i++)
    {
        if (args[i] == "-f")
        {
            if (i+1 < args.size())
            {
                if (parseFee(args[i+1]))
                {
                    parseAmount(args[i+1], fee);
                }
                else
                {
                    return;
                }
            }
            else
            {
                std::cout << WarningMsg("Fee flag given but no fee follows!")
                          << std::endl;
                return;
            }
        }
        else if (args[i] == "-p")
        {
            if (i+1 < args.size())
            {
                std::vector<uint8_t> extraVec;
                std::string extraString;

                /* Convert the payment ID into an "extra" */
                if (!CryptoNote::createTxExtraWithPaymentId(args[i+1],
                                                            extraVec))
                {
                    std::cout << WarningMsg("Failed to parse payment ID! "
                                            "Payment ID's are 64 character "
                                            "hexadecimal strings.")
                              << std::endl;
                    return;
                }
                else
                {
                    /* Then convert the "extra" back into a string so we
                       can pass the argument that walletgreen expects. 
                       Note this string is not the same as the original
                       paymentID string! */
                    for (auto i : extraVec)
                    {
                        extraString += static_cast<char>(i);
                    }
                }

                extra = extraString;
            }
            else
            {
                std::cout << WarningMsg("Payment ID flag given but no payment "
                                        "ID follows!") << std::endl;
                return;
            }
        }
    }

    doTransfer(mixin, address, amount, fee, extra, walletInfo);
}
Exemplo n.º 21
0
ServerConfiguration::ServerConfiguration(const std::string& file) : ConfigurationBase(file) {
	const std::string dns = getProperty(std::string("dns"));
	parseAddress(dns, &_dnsHost, &_dnsPort);
}