static Boolean parseSourceFilterAttribute(char const* sdpLine, struct in_addr& sourceAddr) { // Check for a "a=source-filter:incl IN IP4 <something> <source>" line. // Note: At present, we don't check that <something> really matches // one of our multicast addresses. We also don't support more than // one <source> ##### Boolean result = False; // until we succeed char* sourceName = strDupSize(sdpLine); // ensures we have enough space do { if (sscanf(sdpLine, "a=source-filter: incl IN IP4 %*s %s", sourceName) != 1) break; // Now, convert this name to an address, if we can: NetAddressList addresses(sourceName); if (addresses.numAddresses() == 0) break; netAddressBits sourceAddrBits = *(netAddressBits*)(addresses.firstAddress()->data()); if (sourceAddrBits == 0) break; sourceAddr.s_addr = sourceAddrBits; result = True; } while (0); delete[] sourceName; return result; }
void Codec20::readNewTopologyAndHash(Transport& transport, HeaderParams& params) const{ // Just consume the header's byte // Do not evaluate new topology right now int newTopologyId = transport.readVInt(); params.topologyId.setId(newTopologyId); //update topologyId reference uint32_t clusterSize = transport.readVInt(); TRACE("Coded20::readNewToplogyAndhash(): clusterSize=%d",clusterSize); std::vector<InetSocketAddress> addresses(clusterSize); for (uint32_t i = 0; i < clusterSize; i++) { std::string host(transport.readString()); int16_t port = transport.readUnsignedShort(); addresses[i] = InetSocketAddress(host, port); } uint8_t hashFunctionVersion = transport.readByte(); uint32_t numSegments = transport.readVInt(); std::vector<std::vector<InetSocketAddress>> segmentOwners(numSegments); if (hashFunctionVersion > 0) { TRACE("Codec20::readNewTopologyAndHash: numSegments=%d", numSegments); for (uint32_t i = 0; i < numSegments; i++) { uint8_t numOwners = transport.readByte(); segmentOwners[i]=std::vector<InetSocketAddress>(numOwners); for (uint8_t j = 0; j < numOwners; j++) { uint32_t memberIndex = transport.readVInt(); segmentOwners[i][j] = addresses[memberIndex]; } } } TransportFactory &tf = transport.getTransportFactory(); bool noTopologyInfo=false; int currentTopology = 0; try { currentTopology = tf.getTopologyId(params.cacheName); } catch (std::exception &e) { noTopologyInfo=true; } int topologyAge = tf.getTopologyAge(); if (noTopologyInfo || (params.topologyAge == topologyAge && currentTopology != newTopologyId)) { params.topologyId = newTopologyId; tf.updateServers(addresses); if (hashFunctionVersion == 0) { TRACE("Not using a consistent hash function (hash function version == 0)."); } else { TRACE("Updating client hash function with %u number of segments", numSegments); } tf.updateHashFunction(segmentOwners, numSegments, hashFunctionVersion, params.cacheName, params.topologyId.getId()); } else { TRACE("Outdated topology received (topology id = %d, topology age = %d), so ignoring it: s", newTopologyId, topologyAge/*, Arrays.toString(addresses)*/); } }
static QByteArray localName() { QByteArray result(QHostInfo::localDomainName().toLatin1()); if (!result.isEmpty()) return result; QList<QHostAddress> addresses(QNetworkInterface::allAddresses()); if (!addresses.isEmpty()) return "[" + addresses.first().toString().toLatin1() + "]"; return "localhost.localdomain"; }
void TMailMessage::parse(const QString &str) { QRegExp rx("(\\n\\n|\\r\\n\\r\\n)", Qt::CaseSensitive, QRegExp::RegExp2); int idx = rx.indexIn(str, 0); int bdidx = idx + rx.matchedLength(); if (idx < 0) { tError("Not found mail headers"); setBody(str); } else { QString header = str.left(idx); QByteArray ba; ba.reserve((int)(header.length() * 1.2)); int i = 0; while (i < header.length()) { char c = header[i].toLatin1(); if (c > 0) { ba += c; ++i; } else { // not Latin-1 char int j = indexOfUsAscii(header, i); if (j < 0) { j = header.length(); } ba += THttpUtility::toMimeEncoded(header.mid(i, j - i), textCodec); i = j; } } // Parses header TInternetMessageHeader::parse(ba); addRecipients(addresses("To")); addRecipients(addresses("Cc")); addRecipients(addresses("Bcc")); // Sets body QString body = str.mid(bdidx); setBody(body); } }
static KMime::Types::Mailbox::List stripMyAddressesFromAddressList(const KMime::Types::Mailbox::List &list, const KMime::Types::AddrSpecList me) { KMime::Types::Mailbox::List addresses(list); for (KMime::Types::Mailbox::List::Iterator it = addresses.begin(); it != addresses.end();) { if (me.contains(it->addrSpec())) { it = addresses.erase(it); } else { ++it; } } return addresses; }
// ============================================================================ // put IOpaqueAddress in NTuple (has sense only for Event tag collection Ntuples) // ============================================================================ StatusCode Tuples::TupleObj::column ( const std::string& name , IOpaqueAddress* address ) { if ( invalid () ) { return InvalidTuple ; } if ( !evtColType () ) { return InvalidOperation ; } if ( 0 == address ) { return Error ( "column('" + name + "') IOpaqueAddress* is NULL!" , InvalidObject ) ; } Address* item = addresses( name ); if ( 0 == item ) { return InvalidItem ; } *item = address ; return StatusCode::SUCCESS ; }
netAddressBits MediaSubsession::connectionEndpointAddress() const { do { // Get the endpoint name from with us, or our parent session: char const* endpointString = connectionEndpointName(); if (endpointString == NULL) { endpointString = parentSession().connectionEndpointName(); } if (endpointString == NULL) break; // Now, convert this name to an address, if we can: NetAddressList addresses(endpointString); if (addresses.numAddresses() == 0) break; return *(netAddressBits*)(addresses.firstAddress()->data()); } while (0); // No address known: return 0; }
static QByteArray localName() { QByteArray result(QHostInfo::localDomainName().toLatin1()); if (!result.isEmpty()) return result; QList<QHostAddress> addresses(QNetworkInterface::allAddresses()); if (addresses.isEmpty()) return "localhost.localdomain"; QHostAddress addr; // try to find a non-loopback address foreach (const QHostAddress &a, addresses) { if (!a.isLoopback() && !a.isNull()) { addr = a; break; } } if (addr.isNull()) addr = addresses.first(); return "[" + addr.toString().toLatin1() + "]"; }
char* getSDPDescriptionFromURL(Medium* client, char const* url, char const* username, char const* password, char const* proxyServerName, unsigned short proxyServerPortNum, unsigned short clientStartPortNum) { SIPClient* sipClient = (SIPClient*)client; if (proxyServerName != NULL) { // Tell the SIP client about the proxy: NetAddressList addresses(proxyServerName); if (addresses.numAddresses() == 0) { client->envir() << "Failed to find network address for \"" << proxyServerName << "\"\n"; } else { NetAddress address = *(addresses.firstAddress()); unsigned proxyServerAddress // later, allow for IPv6 ##### = *(unsigned*)(address.data()); if (proxyServerPortNum == 0) proxyServerPortNum = 5060; // default sipClient->setProxyServer(proxyServerAddress, proxyServerPortNum); } } if (clientStartPortNum == 0) clientStartPortNum = 8000; // default sipClient->setClientStartPortNum(clientStartPortNum); char* result; if (username != NULL && password != NULL) { result = sipClient->inviteWithPassword(url, username, password); } else { result = sipClient->invite(url); } extern unsigned statusCode; statusCode = sipClient->inviteStatus(); return result; }
void getSDPDescription(RTSPClient::responseHandler* afterFunc) { extern char* proxyServerName; if (proxyServerName != NULL) { // Tell the SIP client about the proxy: NetAddressList addresses(proxyServerName); if (addresses.numAddresses() == 0) { ourSIPClient->envir() << "Failed to find network address for \"" << proxyServerName << "\"\n"; } else { NetAddress address = *(addresses.firstAddress()); unsigned proxyServerAddress // later, allow for IPv6 ##### = *(unsigned*)(address.data()); extern unsigned short proxyServerPortNum; if (proxyServerPortNum == 0) proxyServerPortNum = 5060; // default ourSIPClient->setProxyServer(proxyServerAddress, proxyServerPortNum); } } extern unsigned short desiredPortNum; unsigned short clientStartPortNum = desiredPortNum; if (clientStartPortNum == 0) clientStartPortNum = 8000; // default ourSIPClient->setClientStartPortNum(clientStartPortNum); extern char const* streamURL; char const* username = ourAuthenticator == NULL ? NULL : ourAuthenticator->username(); char const* password = ourAuthenticator == NULL ? NULL : ourAuthenticator->password(); char* result; if (username != NULL && password != NULL) { result = ourSIPClient->inviteWithPassword(streamURL, username, password); } else { result = ourSIPClient->invite(streamURL); } int resultCode = result == NULL ? -1 : 0; afterFunc(NULL, resultCode, strDup(result)); }
ref_vector(R &&r) : adaptor_range<derefs, std::vector<T *>>( derefs(), map(addresses(), std::forward<R>(r))) { }
QByteArray TMailMessage::fromAddress() const { QList<QByteArray> addr = addresses("From"); return addr.value(0); }
void GenerateCustomer::Process(int numberOfCustomers) { ifstream names(m_nameFile); if (names) cout << "Successfully opened names file" << endl; else cout << "Failed to open names file" << endl; ifstream addresses(m_addressFile); if (addresses) cout << "Successfully opened addresses file" << endl; else cout << "Failed to open addresses file" << endl; ifstream numbers(m_numberFile); if (numbers) cout << "Successfully opened numbers file" << endl; else cout << "Failed to open numbers file" << endl; ofstream output("output.txt"); if (output) cout << "Successfully opened output file" << endl; else cout << "Failed to open output file" << endl; char *processing = new char[256]; for (int idx = 0; idx < numberOfCustomers; idx++) { output << "EXECUTE [dbo].[AddCust] \""; //First name names.getline(processing, 256, ','); output << processing << " "; //Last name names.getline(processing, 256, '\n'); output << processing << "\", "; //Address-street addresses.getline(processing, 256, ','); output << "\"" << processing << ", "; //Address-city addresses.getline(processing, 256, ','); output << processing << ", "; //Address-state addresses.getline(processing, 256, ','); output << processing << ", "; //Address-zip addresses.getline(processing, 256, '\n'); output << processing << "\", "; //Phone number numbers.getline(processing, 256, '\n'); output << " " << processing << ", "; //User ID & end line output << "NULL\n"; } }
int main(int argc, char* argv[]) { boost::program_options::options_description desc(""); desc.add_options() ("multicast-address", boost::program_options::value<std::string>(), "") ("interface", boost::program_options::value<std::string>(), "") ("rtsp-port", boost::program_options::value<boost::uint16_t>(), "") ("avg-bit-rate", boost::program_options::value<int>(), "") ("buffer-size", boost::program_options::value<size_t>(), "") ("stats-interval", boost::program_options::value<size_t>(), ""); boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); boost::program_options::notify(vm); if (vm.count("interface")) { std::string interfaceAddress = vm["interface"].as<std::string>(); NetAddressList addresses(interfaceAddress.c_str()); if (addresses.numAddresses() == 0) { std::cout << "Failed to find network address for \"" << interfaceAddress << "\"" << std::endl; return -1; } ReceivingInterfaceAddr = *(unsigned*)(addresses.firstAddress()->data()); } char sourceAddressStr[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(ReceivingInterfaceAddr), sourceAddressStr, sizeof(sourceAddressStr)); std::cout << "Using source address " << sourceAddressStr << std::endl; if (vm.count("rtsp-port")) { rtspPort = vm["rtsp-port"].as<boost::uint16_t>(); } else { rtspPort = 8555; } std::cout << "Using RTSP port " << rtspPort << std::endl; // Create 'groupsocks' for RTP and RTCP: if(vm.count("multicast-address")) { inet_pton(AF_INET, vm["multicast-address"].as<std::string>().c_str(), &(destinationAddress.s_addr)); } else { inet_pton(AF_INET, "224.0.67.67", &(destinationAddress.s_addr)); } if (vm.count("avg-bit-rate")) { avgBitRate = vm["avg-bit-rate"].as<int>(); } else { avgBitRate = DEFAULT_AVG_BIT_RATE; } std::string bitRateString = to_human_readable_byte_count(avgBitRate, true, false); std::cout << "Using an average encoding bit rate of " << bitRateString << "/s per face" << std::endl; if (vm.count("buffer-size")) { bufferSize = vm["buffer-size"].as<size_t>(); } else { bufferSize = DEFAULT_BUFFER_SIZE; } std::string bufferSizeString = to_human_readable_byte_count(bufferSize, false, false); std::cout << "Using a buffer size of " << bufferSizeString << std::endl; size_t statsInterval; if (vm.count("stats-interval")) { statsInterval = vm["stats-interval"].as<size_t>(); } else { statsInterval = DEFAULT_STATS_INTERVAL; } av_log_set_level(AV_LOG_WARNING); avcodec_register_all(); setupRTSP(); boost::thread networkThread = boost::thread(&networkLoop); Process unityProcess(CUBEMAPEXTRACTIONPLUGIN_ID, false); Process thisProcess(ALLOSERVER_ID, true); while (true) { std::cout << "Waiting for Unity ..." << std::endl; unityProcess.waitForBirth(); std::cout << "Connected to Unity :)" << std::endl; startStreaming(); stats.autoSummary(boost::chrono::seconds(statsInterval), AlloReceiver::statValsMaker, AlloReceiver::postProcessorMaker, AlloReceiver::formatStringMaker); unityProcess.join(); std::cout << "Lost connection to Unity :(" << std::endl; stopStreaming(); stats.stopAutoSummary(); } return 0; }
Boolean SIPClient::parseSIPURL(UsageEnvironment& env, char const* url, NetAddress& address, portNumBits& portNum) { do { // Parse the URL as "sip:<username>@<address>:<port>/<etc>" // (with ":<port>" and "/<etc>" optional) // Also, skip over any "<username>[:<password>]@" preceding <address> char const* prefix = "sip:"; unsigned const prefixLength = 4; if (_strncasecmp(url, prefix, prefixLength) != 0) { env.setResultMsg("URL is not of the form \"", prefix, "\""); break; } unsigned const parseBufferSize = 100; char parseBuffer[parseBufferSize]; unsigned addressStartIndex = prefixLength; while (url[addressStartIndex] != '\0' && url[addressStartIndex++] != '@') {} char const* from = &url[addressStartIndex]; // Skip over any "<username>[:<password>]@" char const* from1 = from; while (*from1 != '\0' && *from1 != '/') { if (*from1 == '@') { from = ++from1; break; } ++from1; } char* to = &parseBuffer[0]; unsigned i; for (i = 0; i < parseBufferSize; ++i) { if (*from == '\0' || *from == ':' || *from == '/') { // We've completed parsing the address *to = '\0'; break; } *to++ = *from++; } if (i == parseBufferSize) { env.setResultMsg("URL is too long"); break; } NetAddressList addresses(parseBuffer); if (addresses.numAddresses() == 0) { env.setResultMsg("Failed to find network address for \"", parseBuffer, "\""); break; } address = *(addresses.firstAddress()); portNum = 5060; // default value char nextChar = *from; if (nextChar == ':') { int portNumInt; if (sscanf(++from, "%d", &portNumInt) != 1) { env.setResultMsg("No port number follows ':'"); break; } if (portNumInt < 1 || portNumInt > 65535) { env.setResultMsg("Bad port number"); break; } portNum = (portNumBits)portNumInt; } return True; } while (0); return False; }
void MiniCluster<Dtype>::run(shared_ptr<Solver<Dtype> > root_solver, const vector<int>& gpus, int total_gpus) { #ifdef INFINIBAND RDMAAdapter adapter; LOG(INFO) << "Found RDMA adapter " << adapter.name(); // Create channel for each peer vector<shared_ptr<RDMAChannel> > peers(size_); for (int i = 0; i < size_; ++i) { if (i != rank_) { peers[i].reset(new RDMAChannel(adapter)); } } // Connect channels all to all for (int i = 0; i < size_; ++i) { vector<string> addresses(1); if (i != rank_) { addresses[0] = peers[i]->address(); } AllGather(&addresses); for (int j = 0; j < addresses.size(); ++j) LOG(INFO) << addresses[j]; if (i == rank_) { for (int j = 0; j < size_; ++j) { if (j != rank_) { peers[j]->Connect(addresses[j]); } } } } vector<shared_ptr<P2PSync<Dtype> > > syncs(gpus.size()); // RDMASync will create all necessary buffers syncs[0].reset(new RDMASync<Dtype>(root_solver, peers, rank_)); #else // Create channel for each peer vector<shared_ptr<SocketChannel> > peers(size_); for (int i = 0; i < size_; ++i) { if (i != rank_) { peers[i].reset(new SocketChannel()); } } SocketAdapter adapter(&peers); usleep(10000); // Get all channels to connect to vector<string> addresses(1); // Set local address to send to master in AllGather. // If you are master, you still need to set it, so // that it is sent to everyone during regular broadcast in AllGather addresses[0] = adapter.address(); LOG(INFO) << "Adapter address " << adapter.address().c_str(); AllGather(&addresses); for (int j = 0; j < addresses.size(); ++j) LOG(INFO) << "ADDRESS [" << addresses.at(j).c_str() << "]"; // Connect to all channnels for (int j = 0; j < size_; ++j) { if (j != rank_) { LOG(INFO) << "Connecting to [" << addresses[j].c_str() << "]"; peers[j]->Connect(addresses[j]); } } #ifndef CPU_ONLY vector<shared_ptr<P2PSync<Dtype> > > syncs(gpus.size()); syncs[0].reset(new SocketSync<Dtype>(root_solver, peers, rank_)); #else vector<shared_ptr<P2PSyncCPU<Dtype> > > syncs(1); syncs[0].reset(new SocketSyncCPU<Dtype>(root_solver, peers, rank_)); #endif #endif #ifndef CPU_ONLY syncs[0]->prepare(gpus, &syncs); LOG(INFO)<< "Starting Optimization"; // Switch to total number of GPUs once the datareaders are ready Caffe::set_solver_count(total_gpus); for (int i = 1; i < syncs.size(); ++i) { syncs[i]->StartInternalThread(); } // Run root solver on current thread syncs[0]->solver()->Solve(); for (int i = 1; i < syncs.size(); ++i) { syncs[i]->StopInternalThread(); } #else Caffe::set_solver_count(1); LOG(INFO) << "Starting solver..."; syncs[0]->solver()->Solve(); #endif }
int main(int argc, char** argv) { // Begin by setting up our usage environment: TaskScheduler* scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); progName = argv[0]; gettimeofday(&startTime, NULL); #ifdef USE_SIGNALS // Allow ourselves to be shut down gracefully by a SIGHUP or a SIGUSR1: signal(SIGHUP, signalHandlerShutdown); signal(SIGUSR1, signalHandlerShutdown); #endif unsigned short desiredPortNum = 0; // unfortunately we can't use getopt() here, as Windoze doesn't have it while (argc > 2) { char* const opt = argv[1]; if (opt[0] != '-') usage(); switch (opt[1]) { case 'p': { // specify start port number int portArg; if (sscanf(argv[2], "%d", &portArg) != 1) { usage(); } if (portArg <= 0 || portArg >= 65536 || portArg&1) { *env << "bad port number: " << portArg << " (must be even, and in the range (0,65536))\n"; usage(); } desiredPortNum = (unsigned short)portArg; ++argv; --argc; break; } case 'r': { // do not receive data (instead, just 'play' the stream(s)) createReceivers = False; break; } case 'q': { // output a QuickTime file (to stdout) outputQuickTimeFile = True; break; } case '4': { // output a 'mp4'-format file (to stdout) outputQuickTimeFile = True; generateMP4Format = True; break; } case 'i': { // output an AVI file (to stdout) outputAVIFile = True; break; } case 'I': { // specify input interface... NetAddressList addresses(argv[2]); if (addresses.numAddresses() == 0) { *env << "Failed to find network address for \"" << argv[2] << "\""; break; } ReceivingInterfaceAddr = *(unsigned*)(addresses.firstAddress()->data()); ++argv; --argc; break; } case 'a': { // receive/record an audio stream only audioOnly = True; singleMedium = "audio"; break; } case 'v': { // receive/record a video stream only videoOnly = True; singleMedium = "video"; break; } case 'V': { // disable verbose output verbosityLevel = 0; break; } case 'd': { // specify duration, or how much to delay after end time float arg; if (sscanf(argv[2], "%g", &arg) != 1) { usage(); } if (argv[2][0] == '-') { // not "arg<0", in case argv[2] was "-0" // a 'negative' argument was specified; use this for "durationSlop": duration = 0; // use whatever's in the SDP durationSlop = -arg; } else { duration = arg; durationSlop = 0; } ++argv; --argc; break; } case 'D': { // specify maximum number of seconds to wait for packets: if (sscanf(argv[2], "%u", &interPacketGapMaxTime) != 1) { usage(); } ++argv; --argc; break; } case 'c': { // play continuously playContinuously = True; break; } case 'S': { // specify an offset to use with "SimpleRTPSource"s if (sscanf(argv[2], "%d", &simpleRTPoffsetArg) != 1) { usage(); } if (simpleRTPoffsetArg < 0) { *env << "offset argument to \"-S\" must be >= 0\n"; usage(); } ++argv; --argc; break; } case 'O': { // Don't send an "OPTIONS" request before "DESCRIBE" sendOptionsRequest = False; break; } case 'o': { // Send only the "OPTIONS" request to the server sendOptionsRequestOnly = True; break; } case 'm': { // output multiple files - one for each frame oneFilePerFrame = True; break; } case 'n': { // notify the user when the first data packet arrives notifyOnPacketArrival = True; break; } case 't': { // stream RTP and RTCP over the TCP 'control' connection if (controlConnectionUsesTCP) { streamUsingTCP = True; } else { usage(); } break; } case 'T': { // stream RTP and RTCP over a HTTP connection if (controlConnectionUsesTCP) { if (argc > 3 && argv[2][0] != '-') { // The next argument is the HTTP server port number: if (sscanf(argv[2], "%hu", &tunnelOverHTTPPortNum) == 1 && tunnelOverHTTPPortNum > 0) { ++argv; --argc; break; } } } // If we get here, the option was specified incorrectly: usage(); break; } case 'u': { // specify a username and password username = argv[2]; password = argv[3]; argv+=2; argc-=2; if (allowProxyServers && argc > 3 && argv[2][0] != '-') { // The next argument is the name of a proxy server: proxyServerName = argv[2]; ++argv; --argc; if (argc > 3 && argv[2][0] != '-') { // The next argument is the proxy server port number: if (sscanf(argv[2], "%hu", &proxyServerPortNum) != 1) { usage(); } ++argv; --argc; } } break; } case 'A': { // specify a desired audio RTP payload format unsigned formatArg; if (sscanf(argv[2], "%u", &formatArg) != 1 || formatArg >= 96) { usage(); } desiredAudioRTPPayloadFormat = (unsigned char)formatArg; ++argv; --argc; break; } case 'M': { // specify a MIME subtype for a dynamic RTP payload type mimeSubtype = argv[2]; if (desiredAudioRTPPayloadFormat==0) desiredAudioRTPPayloadFormat =96; ++argv; --argc; break; } case 'w': { // specify a width (pixels) for an output QuickTime or AVI movie if (sscanf(argv[2], "%hu", &movieWidth) != 1) { usage(); } movieWidthOptionSet = True; ++argv; --argc; break; } case 'h': { // specify a height (pixels) for an output QuickTime or AVI movie if (sscanf(argv[2], "%hu", &movieHeight) != 1) { usage(); } movieHeightOptionSet = True; ++argv; --argc; break; } case 'f': { // specify a frame rate (per second) for an output QT or AVI movie if (sscanf(argv[2], "%u", &movieFPS) != 1) { usage(); } movieFPSOptionSet = True; ++argv; --argc; break; } case 'F': { // specify a prefix for the audio and video output files fileNamePrefix = argv[2]; ++argv; --argc; break; } case 'b': { // specify the size of buffers for "FileSink"s if (sscanf(argv[2], "%u", &fileSinkBufferSize) != 1) { usage(); } ++argv; --argc; break; } case 'B': { // specify the size of input socket buffers if (sscanf(argv[2], "%u", &socketInputBufferSize) != 1) { usage(); } ++argv; --argc; break; } // Note: The following option is deprecated, and may someday be removed: case 'l': { // try to compensate for packet loss by repeating frames packetLossCompensate = True; break; } case 'y': { // synchronize audio and video streams syncStreams = True; break; } case 'H': { // generate hint tracks (as well as the regular data tracks) generateHintTracks = True; break; } case 'Q': { // output QOS measurements qosMeasurementIntervalMS = 1000; // default: 1 second if (argc > 3 && argv[2][0] != '-') { // The next argument is the measurement interval, // in multiples of 100 ms if (sscanf(argv[2], "%u", &qosMeasurementIntervalMS) != 1) { usage(); } qosMeasurementIntervalMS *= 100; ++argv; --argc; } break; } case 's': { // specify initial seek time (trick play) double arg; if (sscanf(argv[2], "%lg", &arg) != 1 || arg < 0) { usage(); } initialSeekTime = arg; ++argv; --argc; break; } case 'z': { // scale (trick play) float arg; if (sscanf(argv[2], "%g", &arg) != 1 || arg == 0.0f) { usage(); } scale = arg; ++argv; --argc; break; } default: { usage(); break; } } ++argv; --argc; } if (argc != 2) usage(); if (outputQuickTimeFile && outputAVIFile) { *env << "The -i and -q (or -4) flags cannot both be used!\n"; usage(); } Boolean outputCompositeFile = outputQuickTimeFile || outputAVIFile; if (!createReceivers && outputCompositeFile) { *env << "The -r and -q (or -4 or -i) flags cannot both be used!\n"; usage(); } if (outputCompositeFile && !movieWidthOptionSet) { *env << "Warning: The -q, -4 or -i option was used, but not -w. Assuming a video width of " << movieWidth << " pixels\n"; } if (outputCompositeFile && !movieHeightOptionSet) { *env << "Warning: The -q, -4 or -i option was used, but not -h. Assuming a video height of " << movieHeight << " pixels\n"; } if (outputCompositeFile && !movieFPSOptionSet) { *env << "Warning: The -q, -4 or -i option was used, but not -f. Assuming a video frame rate of " << movieFPS << " frames-per-second\n"; } if (audioOnly && videoOnly) { *env << "The -a and -v flags cannot both be used!\n"; usage(); } if (sendOptionsRequestOnly && !sendOptionsRequest) { *env << "The -o and -O flags cannot both be used!\n"; usage(); } if (tunnelOverHTTPPortNum > 0) { if (streamUsingTCP) { *env << "The -t and -T flags cannot both be used!\n"; usage(); } else { streamUsingTCP = True; } } if (!createReceivers && notifyOnPacketArrival) { *env << "Warning: Because we're not receiving stream data, the -n flag has no effect\n"; } if (durationSlop < 0) { // This parameter wasn't set, so use a default value. // If we're measuring QOS stats, then don't add any slop, to avoid // having 'empty' measurement intervals at the end. durationSlop = qosMeasurementIntervalMS > 0 ? 0.0 : 5.0; } char* url = argv[1]; // Create our client object: ourClient = createClient(*env, verbosityLevel, progName); if (ourClient == NULL) { *env << "Failed to create " << clientProtocolName << " client: " << env->getResultMsg() << "\n"; shutdown(); } if (sendOptionsRequest) { // Begin by sending an "OPTIONS" command: char* optionsResponse = getOptionsResponse(ourClient, url, username, password); if (sendOptionsRequestOnly) { if (optionsResponse == NULL) { *env << clientProtocolName << " \"OPTIONS\" request failed: " << env->getResultMsg() << "\n"; } else { *env << clientProtocolName << " \"OPTIONS\" request returned: " << optionsResponse << "\n"; } shutdown(); } delete[] optionsResponse; } // Open the URL, to get a SDP description: char* sdpDescription = getSDPDescriptionFromURL(ourClient, url, username, password, proxyServerName, proxyServerPortNum, desiredPortNum); if (sdpDescription == NULL) { *env << "Failed to get a SDP description from URL \"" << url << "\": " << env->getResultMsg() << "\n"; shutdown(); } *env << "Opened URL \"" << url << "\", returning a SDP description:\n" << sdpDescription << "\n"; // Create a media session object from this SDP description: session = MediaSession::createNew(*env, sdpDescription); delete[] sdpDescription; if (session == NULL) { *env << "Failed to create a MediaSession object from the SDP description: " << env->getResultMsg() << "\n"; shutdown(); } else if (!session->hasSubsessions()) { *env << "This session has no media subsessions (i.e., \"m=\" lines)\n"; shutdown(); } // Then, setup the "RTPSource"s for the session: MediaSubsessionIterator iter(*session); MediaSubsession *subsession; Boolean madeProgress = False; char const* singleMediumToTest = singleMedium; while ((subsession = iter.next()) != NULL) { // If we've asked to receive only a single medium, then check this now: if (singleMediumToTest != NULL) { if (strcmp(subsession->mediumName(), singleMediumToTest) != 0) { *env << "Ignoring \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession, because we've asked to receive a single " << singleMedium << " session only\n"; continue; } else { // Receive this subsession only singleMediumToTest = "xxxxx"; // this hack ensures that we get only 1 subsession of this type } } if (desiredPortNum != 0) { subsession->setClientPortNum(desiredPortNum); desiredPortNum += 2; } if (createReceivers) { if (!subsession->initiate(simpleRTPoffsetArg)) { *env << "Unable to create receiver for \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession: " << env->getResultMsg() << "\n"; } else { *env << "Created receiver for \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession (client ports " << subsession->clientPortNum() << "-" << subsession->clientPortNum()+1 << ")\n"; madeProgress = True; if (subsession->rtpSource() != NULL) { // Because we're saving the incoming data, rather than playing // it in real time, allow an especially large time threshold // (1 second) for reordering misordered incoming packets: unsigned const thresh = 1000000; // 1 second subsession->rtpSource()->setPacketReorderingThresholdTime(thresh); // Set the RTP source's OS socket buffer size as appropriate - either if we were explicitly asked (using -B), // or if the desired FileSink buffer size happens to be larger than the current OS socket buffer size. // (The latter case is a heuristic, on the assumption that if the user asked for a large FileSink buffer size, // then the input data rate may be large enough to justify increasing the OS socket buffer size also.) int socketNum = subsession->rtpSource()->RTPgs()->socketNum(); unsigned curBufferSize = getReceiveBufferSize(*env, socketNum); if (socketInputBufferSize > 0 || fileSinkBufferSize > curBufferSize) { unsigned newBufferSize = socketInputBufferSize > 0 ? socketInputBufferSize : fileSinkBufferSize; newBufferSize = setReceiveBufferTo(*env, socketNum, newBufferSize); if (socketInputBufferSize > 0) { // The user explicitly asked for the new socket buffer size; announce it: *env << "Changed socket receive buffer size for the \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession from " << curBufferSize << " to " << newBufferSize << " bytes\n"; } } } } } else { if (subsession->clientPortNum() == 0) { *env << "No client port was specified for the \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession. (Try adding the \"-p <portNum>\" option.)\n"; } else { madeProgress = True; } } } if (!madeProgress) shutdown(); // Perform additional 'setup' on each subsession, before playing them: setupStreams(); // Create output files: if (createReceivers) { if (outputQuickTimeFile) { // Create a "QuickTimeFileSink", to write to 'stdout': qtOut = QuickTimeFileSink::createNew(*env, *session, "stdout", fileSinkBufferSize, movieWidth, movieHeight, movieFPS, packetLossCompensate, syncStreams, generateHintTracks, generateMP4Format); if (qtOut == NULL) { *env << "Failed to create QuickTime file sink for stdout: " << env->getResultMsg(); shutdown(); } qtOut->startPlaying(sessionAfterPlaying, NULL); } else if (outputAVIFile) { // Create an "AVIFileSink", to write to 'stdout': aviOut = AVIFileSink::createNew(*env, *session, "stdout", fileSinkBufferSize, movieWidth, movieHeight, movieFPS, packetLossCompensate); if (aviOut == NULL) { *env << "Failed to create AVI file sink for stdout: " << env->getResultMsg(); shutdown(); } aviOut->startPlaying(sessionAfterPlaying, NULL); } else { // Create and start "FileSink"s for each subsession: madeProgress = False; iter.reset(); while ((subsession = iter.next()) != NULL) { if (subsession->readSource() == NULL) continue; // was not initiated // Create an output file for each desired stream: char outFileName[1000]; if (singleMedium == NULL) { // Output file name is // "<filename-prefix><medium_name>-<codec_name>-<counter>" static unsigned streamCounter = 0; snprintf(outFileName, sizeof outFileName, "%s%s-%s-%d", fileNamePrefix, subsession->mediumName(), subsession->codecName(), ++streamCounter); } else { sprintf(outFileName, "stdout"); } FileSink* fileSink; if (strcmp(subsession->mediumName(), "audio") == 0 && (strcmp(subsession->codecName(), "AMR") == 0 || strcmp(subsession->codecName(), "AMR-WB") == 0)) { // For AMR audio streams, we use a special sink that inserts AMR frame hdrs: fileSink = AMRAudioFileSink::createNew(*env, outFileName, fileSinkBufferSize, oneFilePerFrame); } else if (strcmp(subsession->mediumName(), "video") == 0 && (strcmp(subsession->codecName(), "H264") == 0)) { // For H.264 video stream, we use a special sink that insert start_codes: fileSink = H264VideoFileSink::createNew(*env, outFileName, fileSinkBufferSize, oneFilePerFrame); } else { // Normal case: fileSink = FileSink::createNew(*env, outFileName, fileSinkBufferSize, oneFilePerFrame); } subsession->sink = fileSink; if (subsession->sink == NULL) { *env << "Failed to create FileSink for \"" << outFileName << "\": " << env->getResultMsg() << "\n"; } else { if (singleMedium == NULL) { *env << "Created output file: \"" << outFileName << "\"\n"; } else { *env << "Outputting data from the \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession to 'stdout'\n"; } if (strcmp(subsession->mediumName(), "video") == 0 && strcmp(subsession->codecName(), "MP4V-ES") == 0 && subsession->fmtp_config() != NULL) { // For MPEG-4 video RTP streams, the 'config' information // from the SDP description contains useful VOL etc. headers. // Insert this data at the front of the output file: unsigned configLen; unsigned char* configData = parseGeneralConfigStr(subsession->fmtp_config(), configLen); struct timeval timeNow; gettimeofday(&timeNow, NULL); fileSink->addData(configData, configLen, timeNow); delete[] configData; } subsession->sink->startPlaying(*(subsession->readSource()), subsessionAfterPlaying, subsession); // Also set a handler to be called if a RTCP "BYE" arrives // for this subsession: if (subsession->rtcpInstance() != NULL) { subsession->rtcpInstance()->setByeHandler(subsessionByeHandler, subsession); } madeProgress = True; } } if (!madeProgress) shutdown(); } } // Finally, start playing each subsession, to start the data flow: startPlayingStreams(); env->taskScheduler().doEventLoop(); // does not return return 0; // only to prevent compiler warning }
void GenerateEmployee::Process(int numberOfEmployees) { ifstream usernames(m_usernameFile); if (usernames) cout << "Successfully opened username file" << endl; else cout << "Failed to open usernames file" << endl; ifstream numbers(m_numberFile); if (numbers) cout << "Successfully opened number file" << endl; else cout << "Failed to open number file" << endl; ifstream addresses(m_addressFile); if (addresses) cout << "Successfully opened address file" << endl; else cout << "Failed to open address file" << endl; ofstream output("output.txt"); if (output) cout << "Successfully opened output file" << endl; else cout << "Failed to open output file" << endl; char *processing = new char[256]; for (int idx = 0; idx < numberOfEmployees; idx++) { output << "EXECUTE [dbo].[AddUser] "; //Username usernames.getline(processing, 256, '\n'); output << "\"" << processing << "\", "; //Phone number numbers.getline(processing, 256, '\n'); output << processing << ", "; //Permissions (31 for now) output << "31, "; //Address-street addresses.getline(processing, 256, ','); output << "\"" << processing << ", "; //Address-city addresses.getline(processing, 256, ','); output << processing << ", "; //Address-state addresses.getline(processing, 256, ','); output << processing << ", "; //Address-zip addresses.getline(processing, 256, '\n'); output << processing << "\""; //End line output << '\n'; } }
iterator end() const { return (addresses() + this->size()); }
iterator begin() const { return addresses(); }
UniValue deriveaddresses(const JSONRPCRequest& request) { if (request.fHelp || request.params.empty() || request.params.size() > 2) { throw std::runtime_error( RPCHelpMan{"deriveaddresses", {"\nDerives one or more addresses corresponding to an output descriptor.\n" "Examples of output descriptors are:\n" " pkh(<pubkey>) P2PKH outputs for the given pubkey\n" " wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n" " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n" " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n" "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n" "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n" "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"}, { {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."}, {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED_NAMED_ARG, "If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive."}, }, RPCResult{ "[ address ] (array) the derived addresses\n" }, RPCExamples{ "First three native segwit receive addresses\n" + HelpExampleCli("deriveaddresses", "\"wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#trd0mf0l\" \"[0,2]\"") }}.ToString() ); } RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType()}); // Range argument is checked later const std::string desc_str = request.params[0].get_str(); int64_t range_begin = 0; int64_t range_end = 0; if (request.params.size() >= 2 && !request.params[1].isNull()) { std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]); } FlatSigningProvider key_provider; auto desc = Parse(desc_str, key_provider, /* require_checksum = */ true); if (!desc) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid descriptor")); } if (!desc->IsRange() && request.params.size() > 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor"); } if (desc->IsRange() && request.params.size() == 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor"); } UniValue addresses(UniValue::VARR); for (int i = range_begin; i <= range_end; ++i) { FlatSigningProvider provider; std::vector<CScript> scripts; if (!desc->Expand(i, key_provider, scripts, provider)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys")); } for (const CScript &script : scripts) { CTxDestination dest; if (!ExtractDestination(script, dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Descriptor does not have a corresponding address")); } addresses.push_back(EncodeDestination(dest)); } } // This should not be possible, but an assert seems overkill: if (addresses.empty()) { throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result"); } return addresses; }
ref_vector(std::initializer_list<std::reference_wrapper<T>> il) : adaptor_range<derefs, std::vector<T *>>(derefs(), map(addresses(), il)) { }
QList<QPair<QString, QVariant>> EntryBase::GetVCardRepresentation () const { Account_->GetClientConnection ()->FetchVCard (GetJID ()); const auto vcard = GetVCard (); QList<QPair<QString, QVariant>> result { { tr ("Photo"), QImage::fromData (vcard.photo ()) }, { "JID", vcard.from () }, { tr ("Real name"), vcard.fullName () }, { tr ("Birthday"), vcard.birthday () }, { "URL", vcard.url () }, { tr ("About"), vcard.description () } }; for (const auto& phone : vcard.phones ()) { if (phone.number ().isEmpty ()) continue; QStringList attrs; if (phone.type () & QXmppVCardPhone::Preferred) attrs << tr ("preferred"); if (phone.type () & QXmppVCardPhone::Home) attrs << tr ("home"); if (phone.type () & QXmppVCardPhone::Work) attrs << tr ("work"); if (phone.type () & QXmppVCardPhone::Cell) attrs << tr ("cell"); result.append ({ tr ("Phone"), attrs.isEmpty () ? phone.number () : phone.number () + " (" + attrs.join (", ") + ")" }); } for (const auto& email : vcard.emails ()) { if (email.address ().isEmpty ()) continue; QStringList attrs; if (email.type () == QXmppVCardEmail::Preferred) attrs << tr ("preferred"); if (email.type () == QXmppVCardEmail::Home) attrs << tr ("home"); if (email.type () == QXmppVCardEmail::Work) attrs << tr ("work"); if (email.type () == QXmppVCardEmail::X400) attrs << "X400"; result.append ({ "Email", attrs.isEmpty () ? email.address () : email.address () + " (" + attrs.join (", ") + ")" }); } for (const auto& address : vcard.addresses ()) { if ((address.country () + address.locality () + address.postcode () + address.region () + address.street ()).isEmpty ()) continue; QStringList attrs; if (address.type () & QXmppVCardAddress::Home) attrs << tr ("home"); if (address.type () & QXmppVCardAddress::Work) attrs << tr ("work"); if (address.type () & QXmppVCardAddress::Postal) attrs << tr ("postal"); if (address.type () & QXmppVCardAddress::Preferred) attrs << tr ("preferred"); QString str; QStringList fields; auto addField = [&fields] (const QString& label, const QString& val) { if (!val.isEmpty ()) fields << label.arg (val); }; addField (tr ("Country: %1"), address.country ()); addField (tr ("Region: %1"), address.region ()); addField (tr ("Locality: %1", "User's locality"), address.locality ()); addField (tr ("Street: %1"), address.street ()); addField (tr ("Postal code: %1"), address.postcode ()); result.append ({ tr ("Address"), fields }); } #if QXMPP_VERSION >= 0x000800 const auto& orgInfo = vcard.organization (); result.append ({ tr ("Organization"), orgInfo.organization () }); result.append ({ tr ("Organization unit"), orgInfo.unit () }); result.append ({ tr ("Job title"), orgInfo.title () }); result.append ({ tr ("Job role"), orgInfo.role () }); #endif return result; }
int main(int argc, char** argv) { // Begin by setting up our usage environment: TaskScheduler* scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); progName = argv[0]; gettimeofday(&startTime, NULL); #ifdef USE_SIGNALS // Allow ourselves to be shut down gracefully by a SIGHUP or a SIGUSR1: signal(SIGHUP, signalHandlerShutdown); signal(SIGUSR1, signalHandlerShutdown); #endif // unfortunately we can't use getopt() here, as Windoze doesn't have it while (argc > 2) { char* const opt = argv[1]; if (opt[0] != '-') usage(); switch (opt[1]) { case 'p': { // specify start port number int portArg; if (sscanf(argv[2], "%d", &portArg) != 1) { usage(); } if (portArg <= 0 || portArg >= 65536 || portArg&1) { *env << "bad port number: " << portArg << " (must be even, and in the range (0,65536))\n"; usage(); } desiredPortNum = (unsigned short)portArg; ++argv; --argc; break; } case 'r': { // do not receive data (instead, just 'play' the stream(s)) createReceivers = False; break; } case 'q': { // output a QuickTime file (to stdout) outputQuickTimeFile = True; break; } case '4': { // output a 'mp4'-format file (to stdout) outputQuickTimeFile = True; generateMP4Format = True; break; } case 'i': { // output an AVI file (to stdout) outputAVIFile = True; break; } case 'I': { // specify input interface... NetAddressList addresses(argv[2]); if (addresses.numAddresses() == 0) { *env << "Failed to find network address for \"" << argv[2] << "\""; break; } ReceivingInterfaceAddr = *(unsigned*)(addresses.firstAddress()->data()); ++argv; --argc; break; } case 'a': { // receive/record an audio stream only audioOnly = True; singleMedium = "audio"; break; } case 'v': { // receive/record a video stream only videoOnly = True; singleMedium = "video"; break; } case 'V': { // disable verbose output verbosityLevel = 0; break; } case 'd': { // specify duration, or how much to delay after end time float arg; if (sscanf(argv[2], "%g", &arg) != 1) { usage(); } if (argv[2][0] == '-') { // not "arg<0", in case argv[2] was "-0" // a 'negative' argument was specified; use this for "durationSlop": duration = 0; // use whatever's in the SDP durationSlop = -arg; } else { duration = arg; durationSlop = 0; } ++argv; --argc; break; } case 'D': { // specify maximum number of seconds to wait for packets: if (sscanf(argv[2], "%u", &interPacketGapMaxTime) != 1) { usage(); } ++argv; --argc; break; } case 'c': { // play continuously playContinuously = True; break; } case 'S': { // specify an offset to use with "SimpleRTPSource"s if (sscanf(argv[2], "%d", &simpleRTPoffsetArg) != 1) { usage(); } if (simpleRTPoffsetArg < 0) { *env << "offset argument to \"-S\" must be >= 0\n"; usage(); } ++argv; --argc; break; } case 'O': { // Don't send an "OPTIONS" request before "DESCRIBE" sendOptionsRequest = False; break; } case 'o': { // Send only the "OPTIONS" request to the server sendOptionsRequestOnly = True; break; } case 'm': { // output multiple files - one for each frame oneFilePerFrame = True; break; } case 'n': { // notify the user when the first data packet arrives notifyOnPacketArrival = True; break; } case 't': { // stream RTP and RTCP over the TCP 'control' connection if (controlConnectionUsesTCP) { streamUsingTCP = True; } else { usage(); } break; } case 'T': { // stream RTP and RTCP over a HTTP connection if (controlConnectionUsesTCP) { if (argc > 3 && argv[2][0] != '-') { // The next argument is the HTTP server port number: if (sscanf(argv[2], "%hu", &tunnelOverHTTPPortNum) == 1 && tunnelOverHTTPPortNum > 0) { ++argv; --argc; break; } } } // If we get here, the option was specified incorrectly: usage(); break; } case 'u': { // specify a username and password username = argv[2]; password = argv[3]; argv+=2; argc-=2; if (allowProxyServers && argc > 3 && argv[2][0] != '-') { // The next argument is the name of a proxy server: proxyServerName = argv[2]; ++argv; --argc; if (argc > 3 && argv[2][0] != '-') { // The next argument is the proxy server port number: if (sscanf(argv[2], "%hu", &proxyServerPortNum) != 1) { usage(); } ++argv; --argc; } } ourAuthenticator = new Authenticator; ourAuthenticator->setUsernameAndPassword(username, password); break; } case 'A': { // specify a desired audio RTP payload format unsigned formatArg; if (sscanf(argv[2], "%u", &formatArg) != 1 || formatArg >= 96) { usage(); } desiredAudioRTPPayloadFormat = (unsigned char)formatArg; ++argv; --argc; break; } case 'M': { // specify a MIME subtype for a dynamic RTP payload type mimeSubtype = argv[2]; if (desiredAudioRTPPayloadFormat==0) desiredAudioRTPPayloadFormat =96; ++argv; --argc; break; } case 'w': { // specify a width (pixels) for an output QuickTime or AVI movie if (sscanf(argv[2], "%hu", &movieWidth) != 1) { usage(); } movieWidthOptionSet = True; ++argv; --argc; break; } case 'h': { // specify a height (pixels) for an output QuickTime or AVI movie if (sscanf(argv[2], "%hu", &movieHeight) != 1) { usage(); } movieHeightOptionSet = True; ++argv; --argc; break; } case 'f': { // specify a frame rate (per second) for an output QT or AVI movie if (sscanf(argv[2], "%u", &movieFPS) != 1) { usage(); } movieFPSOptionSet = True; ++argv; --argc; break; } case 'F': { // specify a prefix for the audio and video output files fileNamePrefix = argv[2]; ++argv; --argc; break; } case 'b': { // specify the size of buffers for "FileSink"s if (sscanf(argv[2], "%u", &fileSinkBufferSize) != 1) { usage(); } ++argv; --argc; break; } case 'B': { // specify the size of input socket buffers if (sscanf(argv[2], "%u", &socketInputBufferSize) != 1) { usage(); } ++argv; --argc; break; } // Note: The following option is deprecated, and may someday be removed: case 'l': { // try to compensate for packet loss by repeating frames packetLossCompensate = True; break; } case 'y': { // synchronize audio and video streams syncStreams = True; break; } case 'H': { // generate hint tracks (as well as the regular data tracks) generateHintTracks = True; break; } case 'Q': { // output QOS measurements qosMeasurementIntervalMS = 1000; // default: 1 second if (argc > 3 && argv[2][0] != '-') { // The next argument is the measurement interval, // in multiples of 100 ms if (sscanf(argv[2], "%u", &qosMeasurementIntervalMS) != 1) { usage(); } qosMeasurementIntervalMS *= 100; ++argv; --argc; } break; } case 's': { // specify initial seek time (trick play) double arg; if (sscanf(argv[2], "%lg", &arg) != 1 || arg < 0) { usage(); } initialSeekTime = arg; ++argv; --argc; break; } case 'z': { // scale (trick play) float arg; if (sscanf(argv[2], "%g", &arg) != 1 || arg == 0.0f) { usage(); } scale = arg; ++argv; --argc; break; } default: { usage(); break; } } ++argv; --argc; } if (argc != 2) usage(); if (outputQuickTimeFile && outputAVIFile) { *env << "The -i and -q (or -4) flags cannot both be used!\n"; usage(); } Boolean outputCompositeFile = outputQuickTimeFile || outputAVIFile; if (!createReceivers && outputCompositeFile) { *env << "The -r and -q (or -4 or -i) flags cannot both be used!\n"; usage(); } if (outputCompositeFile && !movieWidthOptionSet) { *env << "Warning: The -q, -4 or -i option was used, but not -w. Assuming a video width of " << movieWidth << " pixels\n"; } if (outputCompositeFile && !movieHeightOptionSet) { *env << "Warning: The -q, -4 or -i option was used, but not -h. Assuming a video height of " << movieHeight << " pixels\n"; } if (outputCompositeFile && !movieFPSOptionSet) { *env << "Warning: The -q, -4 or -i option was used, but not -f. Assuming a video frame rate of " << movieFPS << " frames-per-second\n"; } if (audioOnly && videoOnly) { *env << "The -a and -v flags cannot both be used!\n"; usage(); } if (sendOptionsRequestOnly && !sendOptionsRequest) { *env << "The -o and -O flags cannot both be used!\n"; usage(); } if (tunnelOverHTTPPortNum > 0) { if (streamUsingTCP) { *env << "The -t and -T flags cannot both be used!\n"; usage(); } else { streamUsingTCP = True; } } if (!createReceivers && notifyOnPacketArrival) { *env << "Warning: Because we're not receiving stream data, the -n flag has no effect\n"; } if (durationSlop < 0) { // This parameter wasn't set, so use a default value. // If we're measuring QOS stats, then don't add any slop, to avoid // having 'empty' measurement intervals at the end. durationSlop = qosMeasurementIntervalMS > 0 ? 0.0 : 5.0; } streamURL = argv[1]; // Create our client object: ourClient = createClient(*env, streamURL, verbosityLevel, progName); if (ourClient == NULL) { *env << "Failed to create " << clientProtocolName << " client: " << env->getResultMsg() << "\n"; shutdown(); } if (sendOptionsRequest) { // Begin by sending an "OPTIONS" command: getOptions(continueAfterOPTIONS); } else { continueAfterOPTIONS(NULL, 0, NULL); } // All subsequent activity takes place within the event loop: env->taskScheduler().doEventLoop(); // does not return return 0; // only to prevent compiler warning }
int main(int argc, char **argv){ int ii=0, ans=0, nn=0; int det=0; char yn[100]="\0"; int mapLNfill; // shmSetup(); mapLNfill = mmapSetup(); if (mapLNfill == -1) return 0; /* Shared memory creation and attachment // shmKey = ftok("/Users/c4g/src/LNfill/include/lnfill.conf",'b'); // key unique identifier for shared memory, other programs use 'LN' tag // shmKey = ftok("/Users/c4g/src/LNfill/include/lnfill.conf",'b'); // key unique identifier for shared memory, other programs use include this shmKey = ftok("include/lnfill.conf",'b'); // key unique identifier for shared memory, other programs use include this // shmKey = ftok("SHM_PATH",'b'); // key unique identifier for shared memory, other programs use 'LN' tag // shmKey = ftok("/Users/gross/Desktop/LNfill/LNdata",'b'); // key unique identifier for shared memory, other programs use 'LN' tag shmid = shmget(shmKey, sizeof (struct lnfill), 0666); // gets the ID of shared memory, size, permissions, create if necessary by changing to 0666 | IPC_CREAT) lnptr = shmat (shmid, (void *)0, 0); // now link to area so it can be used; struct lnfill pointer char *lnptr if (lnptr == (struct lnfill *)(-1)){ // check for errors perror("shmat"); exit(EXIT_FAILURE); } */ // printf ("%li = %li\n",shmKey, shmid); /* */ // printf ("shm size = %li\n",sizeof (struct lnfill) ); // printf ("pid = %li\n", lnptr->pid); while (ans != 100){ menu(); scanf ("%i", &ans); // read in ans (pointer is indicated) switch (ans){ case 0: // end program but not lnfill if (munmap(lnptr, sizeof (struct lnfill*)) == -1) { perror("Error un-mmapping the file"); } //shmdt(lnptr); // detach from shared memory segment return 0; break; case 1: // display temps and limits if (lnptr->command == 8 || lnptr->command == 7 || lnptr->command == 18) break; // don't force an update lnptr->command = 1; // command (3) stored in SHM so lnfill can do something kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (1) break; case 2: // Change limit and timing parameters if (lnptr->command == 8 || lnptr->command == 7 || lnptr->command == 18) break; // don't force an update printf (" Which detector do you want to change? 1-20, outside this range to do nothing \n"); scanf("%i",&det); if ((det > 0) && (det < 21)){ parametersGe(det); } /* printf("Filling interval ? (usually 28800 s (8 hrs.)) \n"); scanf ("%lf",&zz.interval); printf("Filling time max ? (usually 420 s) \n"); scanf ("%lf",&zz.max); printf("Filling time min ? (usually 150 s) \n"); scanf ("%lf",&zz.min); printf("RTD temperature limit ? (usually ~90 or 6 K above coldest value) \n"); scanf ("%lf",&zz.limit); printf("Outlet temperature limit ? (usually ~90 or few degrees below value) \n"); scanf ("%lf",&zz.limit); lnptr->ge[det].interval = zz.interval; lnptr->ge[det].max = zz.max; lnptr->ge[det].min = zz.min; lnptr->ge[det].limit = zz.limit; lnptr->ge[det].olimit = zz.olimit; lnptr->ge[det].next = time(NULL) + lnptr->ge[det].interval; printf("Detector next fill time has been set to %.0lf s from now \n",lnptr->ge[det].interval); } */ break; case 3: // Add or remove detector from system activeList(); break; /* activemax = activeList(); printf (" Which detector do you want to change? 1-20, outside this range to do nothing \n"); scanf("%i",&det); if ((det > 0) && (det < 21)){ if (lnptr->ge[det].onoff == 0) { printf("RTD is which U6 channel? (0-13) \n"); scanf ("%i",&zz.chanRTD); printf("Overflo is which U6 channel? (0-13) \n"); scanf ("%i",&zz.chanOFLO); printf("Filling interval ? (usually 28800 s (8 hrs.)) \n"); scanf ("%i",&zz.interval); // scanf ("%i",&zz.interval); printf("Filling time max ? (usually 420 s) \n"); scanf ("%i",&zz.max); printf("Filling time min ? (usually 150 s) \n"); scanf ("%i",&zz.min); printf("RTD temperature limit ? (usually ~90 or 6 K above coldest value) \n"); scanf ("%lf",&zz.limit); printf("Outlet temperature limit ? (usually ~90 or few degrees below detector value) \n"); scanf ("%lf",&zz.olimit); printf(" %i %i %lf %lf \n", zz.chanRTD, zz.chanOFLO, zz.limit,zz.olimit); zz.onoff = 1; strcpy(zz.status,"OK"); lnptr->ge[det] = zz; lnptr->ge[det].next = time(NULL) + lnptr->ge[det].interval; printf("Detector next fill time has been set to %.0lf s from now \n",lnptr->ge[det].interval); } else { lnptr->ge[det].onoff = 0; // turn channel off lnptr->ge[det].chanOFLO = -1; // set U6 channels to -1 lnptr->ge[det].chanRTD = -1; // set U6 channels to -1 strcpy(lnptr->ge[det].status,"OFF"); } } // lnptr->command = 3; // command (3) stored in SHM so lnfill can do something not needed...user can force a fill // do I force an RTD read here or wait up to a minute for the natural read? break; */ case 4: // display temps and limits inactiveList(); break; case 5: // Save setup into lnfill.conf printf ("Saving current setup into lnfill.conf (hope you made a copy of the old one) ....\n"); saveSetup(); break; case 7: // force fill 1 detector if (lnptr->command == 8) { printf("Already started a fill ALL ..... returning to menu \n"); break; } if (lnptr->command == 7) { printf("Already filling a detector .... should have done a fill ALL ..... returning to menu \n"); break; } printf ("Which detector do you wish to fill .... <0 do nothing\n"); printf ("Det Name iBar \n"); printf ("--- ---- ---- \n"); for (ii=1; ii < 21; ii++){ if (lnptr->ge[ii-1].chanIbar >=0) printf ("%2i %3s %2i \n",ii, lnptr->ge[ii-1].name, lnptr->ge[ii-1].chanIbar); } scanf("%i",&nn); if (nn < 0) break; lnptr->com1 = nn-1; lnptr->command = 8; // command (8) stored in SHM to start a fill kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (8) // put in detector and value questions break; case 8: // force fill all detectors printf ("force fill ALL detectors here....\n"); if (lnptr->command == 8 || lnptr->command == 7) { printf("Already started a fill ALL ..... returning to menu \n"); break; } lnptr->com1 = -1; // fill all flag lnptr->command = 8; // command (8) stored in SHM so lnfill can do something kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (8) break; case 9: // do initial cool down of a detector printf ("Begin the initial cool down of detectors with next fill 1 hour....\n"); printf ("Which detector do you wish to fill .... <0 do nothing \n"); printf ("Det Name iBar \n"); printf ("--- ---- ---- \n"); printf (" 0 ALL -- \n"); for (ii=1; ii < 21; ii++){ if (lnptr->ge[ii-1].chanIbar >=0) printf ("%2i %3s %2i \n",ii, lnptr->ge[ii-1].name, lnptr->ge[ii-1].chanIbar); } scanf("%i",&nn); if (nn < 0 || nn > 6) break; // if (nn == 0) lnptr->com1 = -1; // else lnptr->com1 = nn-1; lnptr->command = 18; kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (3) // put in detector and value questions break; case 10: // Close all valves printf ("Closing valves and opening manifold ....\n"); lnptr->command = ans; kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (10) break; case 11: // Close tanl valve printf ("Closing tank ....\n"); lnptr->command = ans; kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (10) break; case 12: // Open tank valve printf ("Opening tank ....\n"); lnptr->command = ans; kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (10) break; case 13: // Close manifold printf ("Closing manifold ....\n"); lnptr->command = ans; kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (10) break; case 14: // Open manifold printf ("Opening manifold ....\n"); lnptr->command = ans; kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (10) break; case 15: // Close a detector valve printf ("Which detector valve do you wish to close ? (1-20 from 1st column) \n"); for (ii=1; ii < 21; ii++){ if (lnptr->ge[ii-1].chanIbar >=0) printf ("%2i %3s %2i \n",ii, lnptr->ge[ii-1].name, lnptr->ge[ii-1].chanIbar); } scanf("%i",&nn); lnptr->command = 20 + nn; kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (10) break; case 16: // Open a detector valve printf ("Which detector valve do you wish to open ? (1-20 from 1st column) \n"); for (ii=1; ii < 21; ii++){ if (lnptr->ge[ii-1].chanIbar >=0) printf ("%2i %3s %2i \n",ii, lnptr->ge[ii-1].name, lnptr->ge[ii-1].chanIbar); } scanf("%i",&nn); lnptr->command = 40 + nn; kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (10) break; case 17: // Get valve status directly from ibootbar printf ("ibootBar outlet status \n"); lnptr->command = 17; kill(lnptr->pid,SIGALRM); // send an alarm to let lnfill know it needs to do command (10) break; case 18: // do initial cool down of a detector printf (" Do you really want to reset all alarms? y/n \n"); scanf("%s",yn); if (strcmp(yn,"Y") == 0 || strcmp(yn,"y") == 0) { // if (yn == 'Y' || yn == 'y'){ for (ii=0; ii < 20; ii++){ if (lnptr->ge[det].onoff == 1) strcpy(lnptr->ge[ii].status,"OK"); else strcpy(lnptr->ge[ii].status,"OFF"); } } else printf ("No alarms were reset"); /* scanf("%1s",&zzz); if (strcmp(zzz,"Y") == 0 || strcmp(zzz,"y") == 0) { for (ii=0; ii < 20; ii++){ if (lnptr->ge[det].onoff == 1) strcpy(lnptr->ge[ii].status,"OK"); else strcpy(lnptr->ge[ii].status,"OFF"); } } */ break; case 19: if (lnptr->com2 == 0) { printf (" Do you really want to toggle the LN HV Emergency Shutdown ON? y/n \n"); scanf("%s",yn); if (strcmp(yn,"Y") == 0 || strcmp(yn,"y") == 0) { // if (yn == 'Y' || yn == 'y'){ // scanf("%1s",&zzz); printf (" Turning emergency shutdown ON \n If shutdown occurs you must run bash script to clear events and shutdown!\n"); lnptr->com2 = 1; printf (" Emergency shutdown is ON \n"); } else { printf (" Emergency shutdown is staying OFF \n"); } } else { printf (" Do you really want to toggle the LN Emergency Shutdown OFF? y/n \n"); scanf("%s",yn); if (strcmp(yn,"Y") == 0 || strcmp(yn,"y") == 0) { // char yn = getchar(); // if (yn == 'Y' || yn == 'y'){ // scanf("%1s",&zzz); printf (" Turning emergency shutdown OFF \n You better know that the Ge detectors are COLD! \n And remember to turn it back on when done !\n"); lnptr->com2 = 0; printf (" Emergency shutdown is OFF \n"); } else { printf (" Emergency shutdown is staying ON \n"); } } break; case 61: // Get valve status directly from ibootbar printf ("Input email addresses \n"); addresses(); if (lnptr->command == 61) kill(lnptr->pid,SIGALRM); break; case 100: // End ALL lnfill programs break; default: // Do nothing and go back to the list of options ans = 0; break; } } /* Wrap up the program ending the lnfill-u6, detaching and getting rid of the shared memory segment */ lnptr->command=-1; kill(lnptr->pid,SIGALRM); /* Release the shared memory and close the U3 */ if (munmap(lnptr, sizeof (struct lnfill*)) == -1) { perror("Error un-mmapping the file"); /* Decide here whether to close(fd) and exit() or not. Depends... */ } close(mapLNfill); /* shmdt(lnptr); // detach from shared memory segment shmctl(shmid, IPC_RMID, NULL); // remove the shared memory segment hopefully forever */ return 0; }
static UniValue getaddednodeinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "getaddednodeinfo ( \"node\" )\n" "\nReturns information about the given added node, or all added nodes\n" "(note that onetry addnodes are not listed here)\n" "\nArguments:\n" "1. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n" "\nResult:\n" "[\n" " {\n" " \"addednode\" : \"192.168.0.201\", (string) The node IP address or name (as provided to addnode)\n" " \"connected\" : true|false, (boolean) If connected\n" " \"addresses\" : [ (list of objects) Only when connected = true\n" " {\n" " \"address\" : \"192.168.0.201:8333\", (string) The globalboost server IP and port we're connected to\n" " \"connected\" : \"outbound\" (string) connection, inbound or outbound\n" " }\n" " ]\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddednodeinfo", "\"192.168.0.201\"") + HelpExampleRpc("getaddednodeinfo", "\"192.168.0.201\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); std::vector<AddedNodeInfo> vInfo = g_connman->GetAddedNodeInfo(); if (!request.params[0].isNull()) { bool found = false; for (const AddedNodeInfo& info : vInfo) { if (info.strAddedNode == request.params[0].get_str()) { vInfo.assign(1, info); found = true; break; } } if (!found) { throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); } } UniValue ret(UniValue::VARR); for (const AddedNodeInfo& info : vInfo) { UniValue obj(UniValue::VOBJ); obj.pushKV("addednode", info.strAddedNode); obj.pushKV("connected", info.fConnected); UniValue addresses(UniValue::VARR); if (info.fConnected) { UniValue address(UniValue::VOBJ); address.pushKV("address", info.resolvedAddress.ToString()); address.pushKV("connected", info.fInbound ? "inbound" : "outbound"); addresses.push_back(address); } obj.pushKV("addresses", addresses); ret.push_back(obj); } return ret; }
Boolean DarwinInjector ::setDestination(char const* remoteRTSPServerNameOrAddress, char const* remoteFileName, char const* sessionName, char const* sessionInfo, portNumBits remoteRTSPServerPortNumber, char const* remoteUserName, char const* remotePassword, char const* sessionAuthor, char const* sessionCopyright, int timeout) { char* sdp = NULL; char* url = NULL; Boolean success = False; // until we learn otherwise do { // Construct a RTSP URL for the remote stream: char const* const urlFmt = "rtsp://%s:%u/%s"; unsigned urlLen = strlen(urlFmt) + strlen(remoteRTSPServerNameOrAddress) + 5 /* max short len */ + strlen(remoteFileName); url = new char[urlLen]; sprintf(url, urlFmt, remoteRTSPServerNameOrAddress, remoteRTSPServerPortNumber, remoteFileName); // Begin by creating our RTSP client object: fRTSPClient = new RTSPClientForDarwinInjector(envir(), url, fVerbosityLevel, fApplicationName, this); if (fRTSPClient == NULL) break; // Get the remote RTSP server's IP address: struct in_addr addr; { NetAddressList addresses(remoteRTSPServerNameOrAddress); if (addresses.numAddresses() == 0) break; NetAddress const* address = addresses.firstAddress(); addr.s_addr = *(unsigned*)(address->data()); } AddressString remoteRTSPServerAddressStr(addr); // Construct a SDP description for the session that we'll be streaming: char const* const sdpFmt = "v=0\r\n" "o=- %u %u IN IP4 127.0.0.1\r\n" "s=%s\r\n" "i=%s\r\n" "c=IN IP4 %s\r\n" "t=0 0\r\n" "a=x-qt-text-nam:%s\r\n" "a=x-qt-text-inf:%s\r\n" "a=x-qt-text-cmt:source application:%s\r\n" "a=x-qt-text-aut:%s\r\n" "a=x-qt-text-cpy:%s\r\n"; // plus, %s for each substream SDP unsigned sdpLen = strlen(sdpFmt) + 20 /* max int len */ + 20 /* max int len */ + strlen(sessionName) + strlen(sessionInfo) + strlen(remoteRTSPServerAddressStr.val()) + strlen(sessionName) + strlen(sessionInfo) + strlen(fApplicationName) + strlen(sessionAuthor) + strlen(sessionCopyright) + fSubstreamSDPSizes; unsigned const sdpSessionId = our_random32(); unsigned const sdpVersion = sdpSessionId; sdp = new char[sdpLen]; sprintf(sdp, sdpFmt, sdpSessionId, sdpVersion, // o= line sessionName, // s= line sessionInfo, // i= line remoteRTSPServerAddressStr.val(), // c= line sessionName, // a=x-qt-text-nam: line sessionInfo, // a=x-qt-text-inf: line fApplicationName, // a=x-qt-text-cmt: line sessionAuthor, // a=x-qt-text-aut: line sessionCopyright // a=x-qt-text-cpy: line ); char* p = &sdp[strlen(sdp)]; SubstreamDescriptor* ss; for (ss = fHeadSubstream; ss != NULL; ss = ss->next()) { sprintf(p, "%s", ss->sdpLines()); p += strlen(p); } // Do a RTSP "ANNOUNCE" with this SDP description: Authenticator auth; Authenticator* authToUse = NULL; if (remoteUserName[0] != '\0' || remotePassword[0] != '\0') { auth.setUsernameAndPassword(remoteUserName, remotePassword); authToUse = &auth; } fWatchVariable = 0; (void)fRTSPClient->sendAnnounceCommand(sdp, genericResponseHandler, authToUse); // Now block (but handling events) until we get a response: envir().taskScheduler().doEventLoop(&fWatchVariable); delete[] fResultString; if (fResultCode != 0) break; // an error occurred with the RTSP "ANNOUNCE" command // Next, tell the remote server to start receiving the stream from us. // (To do this, we first create a "MediaSession" object from the SDP description.) fSession = MediaSession::createNew(envir(), sdp); if (fSession == NULL) break; ss = fHeadSubstream; MediaSubsessionIterator iter(*fSession); MediaSubsession* subsession; ss = fHeadSubstream; unsigned streamChannelId = 0; while ((subsession = iter.next()) != NULL) { if (!subsession->initiate()) break; fWatchVariable = 0; (void)fRTSPClient->sendSetupCommand(*subsession, genericResponseHandler, True /*streamOutgoing*/, True /*streamUsingTCP*/); // Now block (but handling events) until we get a response: envir().taskScheduler().doEventLoop(&fWatchVariable); delete[] fResultString; if (fResultCode != 0) break; // an error occurred with the RTSP "SETUP" command // Tell this subsession's RTPSink and RTCPInstance to use // the RTSP TCP connection: ss->rtpSink()->setStreamSocket(fRTSPClient->socketNum(), streamChannelId++); if (ss->rtcpInstance() != NULL) { ss->rtcpInstance()->setStreamSocket(fRTSPClient->socketNum(), streamChannelId++); } ss = ss->next(); } if (subsession != NULL) break; // an error occurred above // Tell the RTSP server to start: fWatchVariable = 0; (void)fRTSPClient->sendPlayCommand(*fSession, genericResponseHandler); // Now block (but handling events) until we get a response: envir().taskScheduler().doEventLoop(&fWatchVariable); delete[] fResultString; if (fResultCode != 0) break; // an error occurred with the RTSP "PLAY" command // Finally, make sure that the output TCP buffer is a reasonable size: increaseSendBufferTo(envir(), fRTSPClient->socketNum(), 100*1024); success = True; } while (0); delete[] sdp; delete[] url; return success; }
netAddressBits ourIPAddress(UsageEnvironment& env) { static netAddressBits ourAddress = 0; int sock = -1; struct in_addr testAddr; if (ReceivingInterfaceAddr != INADDR_ANY) { // Hack: If we were told to receive on a specific interface address, then // define this to be our ip address: ourAddress = ReceivingInterfaceAddr; } if (ourAddress == 0) { // We need to find our source address struct sockaddr_in fromAddr; fromAddr.sin_addr.s_addr = 0; // Get our address by sending a (0-TTL) multicast packet, // receiving it, and looking at the source address used. // (This is kinda bogus, but it provides the best guarantee // that other nodes will think our address is the same as we do.) do { loopbackWorks = 0; // until we learn otherwise testAddr.s_addr = our_inet_addr("228.67.43.91"); // arbitrary Port testPort(15947); // ditto sock = setupDatagramSocket(env, testPort); if (sock < 0) break; if (!socketJoinGroup(env, sock, testAddr.s_addr)) break; unsigned char testString[] = "hostIdTest"; unsigned testStringLength = sizeof testString; if (!writeSocket(env, sock, testAddr, testPort.num(), 0, testString, testStringLength)) break; // Block until the socket is readable (with a 5-second timeout): fd_set rd_set; FD_ZERO(&rd_set); FD_SET((unsigned)sock, &rd_set); const unsigned numFds = sock+1; struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; int result = select(numFds, &rd_set, NULL, NULL, &timeout); if (result <= 0) break; unsigned char readBuffer[20]; int bytesRead = readSocket(env, sock, readBuffer, sizeof readBuffer, fromAddr); if (bytesRead != (int)testStringLength || strncmp((char*)readBuffer, (char*)testString, testStringLength) != 0) { break; } // We use this packet's source address, if it's good: loopbackWorks = !badAddressForUs(fromAddr.sin_addr.s_addr); } while (0); if (sock >= 0) { socketLeaveGroup(env, sock, testAddr.s_addr); closeSocket(sock); } if (!loopbackWorks) do { // We couldn't find our address using multicast loopback, // so try instead to look it up directly - by first getting our host name, and then resolving this host name char hostname[100]; hostname[0] = '\0'; int result = gethostname(hostname, sizeof hostname); if (result != 0 || hostname[0] == '\0') { env.setResultErrMsg("initial gethostname() failed"); break; } // Try to resolve "hostname" to an IP address: NetAddressList addresses(hostname); NetAddressList::Iterator iter(addresses); NetAddress const* address; // Take the first address that's not bad: netAddressBits addr = 0; while ((address = iter.nextAddress()) != NULL) { netAddressBits a = *(netAddressBits*)(address->data()); if (!badAddressForUs(a)) { addr = a; break; } } // Assign the address that we found to "fromAddr" (as if the 'loopback' method had worked), to simplify the code below: fromAddr.sin_addr.s_addr = addr; } while (0); // Make sure we have a good address: netAddressBits from = fromAddr.sin_addr.s_addr; if (badAddressForUs(from)) { char tmp[100]; sprintf(tmp, "This computer has an invalid IP address: %s", AddressString(from).val()); env.setResultMsg(tmp); from = 0; } ourAddress = from; // Use our newly-discovered IP address, and the current time, // to initialize the random number generator's seed: struct timeval timeNow; gettimeofday(&timeNow, NULL); unsigned seed = ourAddress^timeNow.tv_sec^timeNow.tv_usec; our_srandom(seed); } return ourAddress; }
int CommandGenerate::execute(const std::vector<std::string>& p_args) { if(p_args.size() < 10) { help(); return -1; } unsigned int platformId = atol(p_args[1].c_str()); unsigned int deviceId = atol(p_args[2].c_str()); unsigned int staggerSize = atol(p_args[3].c_str()); unsigned int threadsNumber = atol(p_args[4].c_str()); unsigned int hashesNumber = atol(p_args[5].c_str()); unsigned int nonceSize = PLOT_SIZE * staggerSize; std::cerr << "Threads number: " << threadsNumber << std::endl; std::cerr << "Hashes number: " << hashesNumber << std::endl; unsigned int numjobs = (p_args.size() - 5)/4; std::cerr << numjobs << " plot(s) to do." << std::endl; unsigned int staggerMbSize = staggerSize / 4; std::cerr << "Non-GPU memory usage: " << staggerMbSize*numjobs << "MB" << std::endl; std::vector<std::string> paths(numjobs); std::vector<std::ofstream *> out_files(numjobs); std::vector<unsigned long long> addresses(numjobs); std::vector<unsigned long long> startNonces(numjobs); std::vector<unsigned long long> endNonces(numjobs); std::vector<unsigned int> noncesNumbers(numjobs); std::vector<unsigned char*> buffersCpu(numjobs); std::vector<bool> saving_thread_flags(numjobs); std::vector<std::future<void>> save_threads(numjobs); unsigned long long maxNonceNumber = 0; unsigned long long totalNonces = 0; int returnCode = 0; try { for (unsigned int i = 0; i < numjobs; i++) { std::cerr << "----" << std::endl; std::cerr << "Job number " << i << std::endl; unsigned int argstart = 6 + i*4; paths[i] = std::string(p_args[argstart]); addresses[i] = strtoull(p_args[argstart+1].c_str(), NULL, 10); startNonces[i] = strtoull(p_args[argstart+2].c_str(), NULL, 10); noncesNumbers[i] = atol(p_args[argstart+3].c_str()); maxNonceNumber = std::max(maxNonceNumber, (long long unsigned int)noncesNumbers[i]); totalNonces += noncesNumbers[i]; std::ostringstream outFile; outFile << paths[i] << "/" << addresses[i] << "_" << startNonces[i] << "_" << \ noncesNumbers[i] << "_" << staggerSize; std::ios_base::openmode file_mode = std::ios::out | std::ios::binary | std::ios::trunc; out_files[i] = new std::ofstream(outFile.str(), file_mode); assert(out_files[i]); if(noncesNumbers[i] % staggerSize != 0) { noncesNumbers[i] -= noncesNumbers[i] % staggerSize; noncesNumbers[i] += staggerSize; } endNonces[i] = startNonces[i] + noncesNumbers[i]; unsigned int noncesGbSize = noncesNumbers[i] / 4 / 1024; std::cerr << "Path: " << outFile.str() << std::endl; std::cerr << "Nonces: " << startNonces[i] << " to " << endNonces[i] << " (" << noncesGbSize << " GB)" << std::endl; std::cerr << "Creating CPU buffer" << std::endl; buffersCpu[i] = new unsigned char[nonceSize]; if(!buffersCpu[i]) { throw std::runtime_error("Unable to create the CPU buffer (probably out of host memory.)"); } saving_thread_flags[i] = false; std::cerr << "----" << std::endl; } cl_platform_id platforms[4]; cl_uint platformsNumber; cl_device_id devices[32]; cl_uint devicesNumber; cl_context context = 0; cl_command_queue commandQueue = 0; cl_mem bufferGpuGen = 0; cl_mem bufferGpuScoops = 0; cl_program program = 0; cl_kernel kernelStep1 = 0; cl_kernel kernelStep2 = 0; cl_kernel kernelStep3 = 0; int error; std::cerr << "Retrieving OpenCL platforms" << std::endl; error = clGetPlatformIDs(4, platforms, &platformsNumber); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to retrieve the OpenCL platforms"); } if(platformId >= platformsNumber) { throw std::runtime_error("No platform found with the provided id"); } std::cerr << "Retrieving OpenCL GPU devices" << std::endl; error = clGetDeviceIDs(platforms[platformId], CL_DEVICE_TYPE_CPU | CL_DEVICE_TYPE_GPU, 32, devices, &devicesNumber); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to retrieve the OpenCL devices"); } if(deviceId >= devicesNumber) { throw std::runtime_error("No device found with the provided id"); } std::cerr << "Creating OpenCL context" << std::endl; context = clCreateContext(0, 1, &devices[deviceId], NULL, NULL, &error); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to create the OpenCL context"); } std::cerr << "Creating OpenCL command queue" << std::endl; commandQueue = clCreateCommandQueue(context, devices[deviceId], 0, &error); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to create the OpenCL command queue"); } std::cerr << "Creating OpenCL GPU generation buffer" << std::endl; bufferGpuGen = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(cl_uchar) * GEN_SIZE * staggerSize, 0, &error); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to create the OpenCL GPU generation buffer"); } std::cerr << "Creating OpenCL GPU scoops buffer" << std::endl; bufferGpuScoops = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(cl_uchar) * nonceSize, 0, &error); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to create the OpenCL GPU scoops buffer"); } std::cerr << "Creating OpenCL program" << std::endl; std::string source = loadSource("kernel/nonce.cl"); const char* sources[] = {source.c_str()}; size_t sourcesLength[] = {source.length()}; program = clCreateProgramWithSource(context, 1, sources, sourcesLength, &error); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to create the OpenCL program"); } std::cerr << "Building OpenCL program" << std::endl; error = clBuildProgram(program, 1, &devices[deviceId], "-I kernel", 0, 0); if(error != CL_SUCCESS) { size_t logSize; clGetProgramBuildInfo(program, devices[deviceId], CL_PROGRAM_BUILD_LOG, 0, 0, &logSize); char* log = new char[logSize]; clGetProgramBuildInfo(program, devices[deviceId], CL_PROGRAM_BUILD_LOG, logSize, (void*)log, 0); std::cerr << log << std::endl; delete[] log; throw OpenclError(error, "Unable to build the OpenCL program"); } std::cerr << "Creating OpenCL step1 kernel" << std::endl; kernelStep1 = clCreateKernel(program, "nonce_step1", &error); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to create the OpenCL kernel"); } std::cerr << "Setting OpenCL step1 kernel static arguments" << std::endl; error = clSetKernelArg(kernelStep1, 2, sizeof(cl_mem), (void*)&bufferGpuGen); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to set the OpenCL kernel arguments"); } std::cerr << "Creating OpenCL step2 kernel" << std::endl; kernelStep2 = clCreateKernel(program, "nonce_step2", &error); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to create the OpenCL kernel"); } std::cerr << "Setting OpenCL step2 kernel static arguments" << std::endl; error = clSetKernelArg(kernelStep2, 1, sizeof(cl_mem), (void*)&bufferGpuGen); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to set the OpenCL kernel arguments"); } std::cerr << "Creating OpenCL step3 kernel" << std::endl; kernelStep3 = clCreateKernel(program, "nonce_step3", &error); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to create the OpenCL kernel"); } std::cerr << "Setting OpenCL step3 kernel static arguments" << std::endl; error = clSetKernelArg(kernelStep3, 0, sizeof(cl_uint), (void*)&staggerSize); error = clSetKernelArg(kernelStep3, 1, sizeof(cl_mem), (void*)&bufferGpuGen); error = clSetKernelArg(kernelStep3, 2, sizeof(cl_mem), (void*)&bufferGpuScoops); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to set the OpenCL kernel arguments"); } size_t globalWorkSize = staggerSize; size_t localWorkSize = (staggerSize < threadsNumber) ? staggerSize : threadsNumber; time_t startTime = time(0); unsigned int totalNoncesCompleted = 0; for (unsigned long long nonce_ordinal = 0; nonce_ordinal < maxNonceNumber; nonce_ordinal += staggerSize) { for (unsigned int jobnum = 0; jobnum < paths.size(); jobnum += 1) { unsigned long long nonce = startNonces[jobnum] + nonce_ordinal; if (nonce > endNonces[jobnum]) { break; } std::cout << "Running with start nonce " << nonce << std::endl; // Is a cl_ulong always an unsigned long long? unsigned int error = 0; error = clSetKernelArg(kernelStep1, 0, sizeof(cl_ulong), (void*)&addresses[jobnum]); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to set the OpenCL step1 kernel arguments"); } error = clSetKernelArg(kernelStep1, 1, sizeof(cl_ulong), (void*)&nonce); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to set the OpenCL step1 kernel arguments"); } error = clEnqueueNDRangeKernel(commandQueue, kernelStep1, 1, 0, &globalWorkSize, &localWorkSize, 0, 0, 0); if(error != CL_SUCCESS) { throw OpenclError(error, "Error in step1 kernel launch"); } unsigned int hashesSize = hashesNumber * HASH_SIZE; for(int hashesOffset = PLOT_SIZE ; hashesOffset > 0 ; hashesOffset -= hashesSize) { error = clSetKernelArg(kernelStep2, 0, sizeof(cl_ulong), (void*)&nonce); error = clSetKernelArg(kernelStep2, 2, sizeof(cl_uint), (void*)&hashesOffset); error = clSetKernelArg(kernelStep2, 3, sizeof(cl_uint), (void*)&hashesNumber); if(error != CL_SUCCESS) { throw OpenclError(error, "Unable to set the OpenCL step2 kernel arguments"); } error = clEnqueueNDRangeKernel(commandQueue, kernelStep2, 1, 0, &globalWorkSize, &localWorkSize, 0, 0, 0); if(error != CL_SUCCESS) { throw OpenclError(error, "Error in step2 kernel launch"); } error = clFinish(commandQueue); if(error != CL_SUCCESS) { throw OpenclError(error, "Error in step2 kernel finish"); } } totalNoncesCompleted += staggerSize; double percent = 100.0 * (double)totalNoncesCompleted / totalNonces; time_t currentTime = time(0); double speed = (double)totalNoncesCompleted / difftime(currentTime, startTime) * 60.0; double estimatedTime = (double)(totalNonces - totalNoncesCompleted) / speed; std::cerr << "\r" << percent << "% (" << totalNoncesCompleted << "/" << totalNonces << " nonces)"; std::cerr << ", " << speed << " nonces/minutes"; std::cerr << ", ETA: " << ((int)estimatedTime / 60) << "h" << ((int)estimatedTime % 60) << "m" << ((int)(estimatedTime * 60.0) % 60) << "s"; std::cerr << "... "; error = clEnqueueNDRangeKernel(commandQueue, kernelStep3, 1, 0, &globalWorkSize, &localWorkSize, 0, 0, 0); if(error != CL_SUCCESS) { throw OpenclError(error, "Error in step3 kernel launch"); } if (saving_thread_flags[jobnum]) { save_threads[jobnum].wait(); // Wait for last job to finish saving_thread_flags[jobnum] = false; } error = clEnqueueReadBuffer(commandQueue, bufferGpuScoops, CL_TRUE, 0, sizeof(cl_uchar) * nonceSize, buffersCpu[jobnum], 0, 0, 0); if(error != CL_SUCCESS) { throw OpenclError(error, "Error in synchronous read"); } saving_thread_flags[jobnum] = true; save_threads[jobnum] = std::async(std::launch::async, save_nonces, nonceSize, out_files[jobnum], buffersCpu[jobnum]); } } //Clean up for (unsigned int i = 0; i < paths.size(); i += 1) { if (saving_thread_flags[i]) { std::cerr << "waiting for final save to " << paths[i] << " to finish" << std::endl; save_threads[i].wait(); saving_thread_flags[i] = false; std::cerr << "done waiting for final save" << std::endl; if (buffersCpu[i]) { delete[] buffersCpu[i]; } } } if(kernelStep3) { clReleaseKernel(kernelStep3); } if(kernelStep2) { clReleaseKernel(kernelStep2); } if(kernelStep1) { clReleaseKernel(kernelStep1); } if(program) { clReleaseProgram(program); } if(bufferGpuGen) { clReleaseMemObject(bufferGpuGen); } if(bufferGpuScoops) { clReleaseMemObject(bufferGpuScoops); } if(commandQueue) { clReleaseCommandQueue(commandQueue); } if(context) { clReleaseContext(context); } time_t currentTime = time(0); double elapsedTime = difftime(currentTime, startTime) / 60.0; double speed = (double)totalNonces / elapsedTime; std::cerr << "\r100% (" << totalNonces << "/" << totalNonces << " nonces)"; std::cerr << ", " << speed << " nonces/minutes"; std::cerr << ", " << ((int)elapsedTime / 60) << "h" << ((int)elapsedTime % 60) << "m" << ((int)(elapsedTime * 60.0) % 60) << "s"; std::cerr << " " << std::endl; } catch(const OpenclError& ex) { std::cerr << "[ERROR] [" << ex.getCode() << "] " << ex.what() << std::endl; returnCode = -1; } catch(const std::exception& ex) { std::cerr << "[ERROR] " << ex.what() << std::endl; returnCode = -1; } return returnCode; }