Example #1
0
File: cast.cpp Project: Adatan/vlc
/*****************************************************************************
 * Close: destroy interface
 *****************************************************************************/
static void Close(vlc_object_t *p_this)
{
    sout_stream_t *p_stream = (sout_stream_t *)p_this;
    sout_stream_sys_t *p_sys = p_stream->p_sys;

    vlc_cancel(p_sys->chromecastThread);
    vlc_join(p_sys->chromecastThread, NULL);

    switch (p_sys->i_status)
    {
    case CHROMECAST_MEDIA_LOAD_SENT:
    case CHROMECAST_APP_STARTED:
        // Generate the close messages.
        msgClose(p_stream, p_sys->appTransportId);
        // ft
    case CHROMECAST_AUTHENTICATED:
        msgClose(p_stream, "receiver-0");
        // Send the just added close messages.
        sendMessages(p_stream);
        // ft
    default:
        break;
    }

    Clean(p_stream);
}
Example #2
0
KNSingletonApplication::KNSingletonApplication(int &argc,
                                               char **argv,
                                               const QString uniqueKey) :
    QApplication(argc, argv),
    m_messageServer(nullptr),
    m_uniqueKeyMemeory(new QSharedMemory(uniqueKey, this)),
    m_isInstanceRunning(false)
{
    //We used the QSharedMemory for singleton detecting. Give the QSharedMemory
    //the unique key, check the shared memory and we will know whether this is
    //first instance.
    if(m_uniqueKeyMemeory->attach())
    {
        //We detect another instance running.
        m_isInstanceRunning=false;
        //Get the arguments.
        QStringList &&pendingMessages=arguments();
        //Check out the pending message. If there's valid file path, then it
        //will be send to the main instance.
        //Send the messages.
        if(pendingMessages.size()>1 && sendMessages(uniqueKey, pendingMessages))
        {
            //Complete the mission.
            return;
        }
    }
    //If we could go here, then means we couldn't send the message to the
    //previous instance.
    //Set running instance
    m_isInstanceRunning=true;
    //Create a small part of shared memory for instance flag.
    if(m_uniqueKeyMemeory->size()==0 && (!m_uniqueKeyMemeory->create(1)))
    {
        //Unable to create single instance.
        qDebug("Unable to create the single instance.");
        return;
    }
    //Create a local server for listening incoming message.
    m_messageServer=new QLocalServer(this);
    //When there's another instance which is being created, it will send the
    //arguments to message server from the other instance.
    connect(m_messageServer, &QLocalServer::newConnection,
            this, &KNSingletonApplication::onMessageReceive,
            Qt::QueuedConnection);
    //The unique key will be used as the connections name as well.
    if(!m_messageServer->listen(uniqueKey))
    {
        //If we are failed to start listening, and it was caused by address has
        //been taken, it must be a previous instance crashed and left those data
        //there. Remove it and listen again.
        if(QAbstractSocket::AddressInUseError==m_messageServer->serverError())
        {
            //Remove the server and start listen again.
            QLocalServer::removeServer(uniqueKey);
            //Start listen once more.
            m_messageServer->listen(uniqueKey);
        }
    }
}
Example #3
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void QcPlugin::update() {
	QcParameter *qcp = _qcProcessor->getState();

	if ( _qcProcessor->isValid() )
		_qcBuffer->push_back(qcp);

	sendMessages(qcp->recordEndTime);
}
// Extreme laziness function to send a NACK to the other side
void sendNACK( zmq::socket_t * sock, zmq::message_t * routing ) {
    // Send back failure, we couldn't find that node!
    zmq::message_t nackMsg;
    buildTypeMsg( ShinyFilesystemMediator::NACK, &nackMsg );
    
    zmq::message_t blankMsg;
    sendMessages(sock, 3, routing, &blankMsg, &nackMsg );
}
Example #5
0
void SenderThread::iterate(lethe::Handle handle)
{
  if(handle == m_channel.getHandle())
    receiveMessage();

  if(m_messagesSent == m_messagesReleased)
    sendMessages();
  else if(handle == INVALID_HANDLE_VALUE)
    LogInfo("Sender timed out waiting for all responses");

  ++m_iterationCount;
}
Example #6
0
int connectionSendFrameEnd (int connSock) {
	assert (connSock != -1);
	wireworld_message_t message = A_FRAME_END;
	int res = sendMessages (connSock, &message, 1);
	if (res == -1) {
		fprintf (stderr, "Error while sending A_FRAME_END\n");
		return -1;
	} else if (res == 1) {
		return 1; // End of connection
	} else {
		return 0;
	}
}
ShinyFilesystemMediator::~ShinyFilesystemMediator() {
    zmq::socket_t * killSock = this->getMediator();
    
    // build a message that says "destroy" and send it
    zmq::message_t destroyMsg; buildTypeMsg( ShinyFilesystemMediator::DESTROY, &destroyMsg );
    sendMessages(killSock, 1, &destroyMsg );
    
    if( pthread_join( this->thread, NULL ) != 0 ) {
        ERROR( "pthread_join() failed on destruction of mediator thread!" );
    }
    
    // Lol, can't believe I forgot this
    delete( killSock );
}
void QQmlProfilerService::stateAboutToBeChanged(QQmlDebugService::State newState)
{
    QMutexLocker lock(&m_initializeMutex);

    if (state() == newState)
        return;

    if (state() == Enabled
            && m_enabled) {
        stopProfilingImpl();
        sendMessages();
    }

    if (state() != Enabled) {
        // wake up constructor in blocking mode
        // (we might got disabled before first message arrived)
        m_initializeCondition.wakeAll();
    }
}
void QQmlProfilerService::messageReceived(const QByteArray &message)
{
    QMutexLocker lock(&m_initializeMutex);

    QByteArray rwData = message;
    QQmlDebugStream stream(&rwData, QIODevice::ReadOnly);

    bool enabled;
    stream >> enabled;

    if (enabled) {
        startProfilingImpl();
    } else {
        if (stopProfilingImpl())
            sendMessages();
    }

    // wake up constructor in blocking mode
    m_initializeCondition.wakeAll();
}
Example #10
0
void update(int sockfd) {
	int from, to, cost, numbytes;
	struct top_edge new_edge;
	while (scanf("%d %d %d", &from, &to, &cost)) {
	  printf("new topology edge: from %d to %d with a distance of %d", from, to, cost);
	        topology[from-1][to-1] = cost;
			topology[to-1][from-1] = cost;
			new_edge.from = from;
			new_edge.cost = cost;
			new_edge.to = to;
			for (int i = 0; i < 16; i ++) {
				if (numbytes = sendto(sockfd, &new_edge, sizeof(new_edge), 0,
						      (struct sockaddr *)     &(router_addr[i]), sizeof(router_addr[i])) == -1) {
				perror("sendto");
				exit(1);
				}	
			}
		sendMessages(sockfd);
	}
}
Example #11
0
void BehaviorsModule::run_ ()
{
    PROF_ENTER(P_BEHAVIORS);
    static unsigned int num_crashed = 0;
    if (error_state && num_crashed < NUM_PYTHON_RESTARTS_MAX) {
        this->reload_hard();
        error_state = false;
        num_crashed++;
    }

    // Latch incoming messages and prepare outgoing messages
    prepareMessages();

    PROF_ENTER(P_PYTHON);

    // Call main run() method of Brain
    if (brain_instance != NULL) {
        PyObject *result = PyObject_CallMethod(brain_instance, "run", NULL);
        if (result == NULL) {
            // set BehaviorsModule in error state
            error_state = true;
            // report error
            std::cout << "Error occurred in Brain.run() method" << std::endl;
            if (PyErr_Occurred()) {
                PyErr_Print();
            } else {
                std::cout << "  No Python exception information available"
                          << std::endl;
            }
        } else {
            Py_DECREF(result);
        }
    }
    PROF_EXIT(P_PYTHON);

    // Send outgoing messages
    sendMessages();

    PROF_EXIT(P_BEHAVIORS);
}
bool ShinyFilesystemMediator::handleMessage( zmq::socket_t * sock, std::vector<zmq::message_t *> & msgList ) {
    zmq::message_t * fuseRoute = msgList[0];
    zmq::message_t * blankMsg = msgList[1];
    
    // Following the protocol (briefly) laid out in ShinyFuse.h;
    uint8_t type = parseTypeMsg(msgList[2]);
    switch( type ) {
        case ShinyFilesystemMediator::DESTROY: {
            // No actual response data, just sending response just to be polite
            sendACK( sock, fuseRoute );
            // return false as we're signaling to mediator that it's time to die.  >:}
            return false;
        }
        case ShinyFilesystemMediator::GETATTR: {
            // Let's actually get the data fuse wants!
            char * path = parseStringMsg( msgList[3] );
            
            // If the node even exists;
            ShinyMetaNode * node = fs->findNode( path );
            if( node ) {
                // we're just going to serialize it and send it on it's way!
                // Opportunity for zero-copy here!
                uint64_t len = node->serializedLen();
                char * buff = new char[len];
                node->serialize(buff);
                
                zmq::message_t ackMsg; buildTypeMsg( ShinyFilesystemMediator::ACK, &ackMsg );
                zmq::message_t nodeTypeMsg; buildTypeMsg( node->getNodeType(), &nodeTypeMsg );
                zmq::message_t nodeMsg; buildDataMsg( buff, len, &nodeMsg );
                
                sendMessages( sock, 5, fuseRoute, blankMsg, &ackMsg, &nodeTypeMsg, &nodeMsg );
                delete( buff );
            } else
                sendNACK( sock, fuseRoute );
            
            // cleanup after the parseStringMsg()
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::SETATTR: {
            char * path = parseStringMsg( msgList[3] );
            
            ShinyMetaNode * node = fs->findNode( path );
            if( node ) {
                const char * data = (const char *) msgList[4]->data();
                
                // Apply the data to the node
                node->unserialize( &data );
                
                // Send back ACK
                sendACK( sock, fuseRoute );
            } else
                sendNACK( sock, fuseRoute );
            
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::READDIR: {
            char * path = parseStringMsg( msgList[3] );
            
            // If the node even exists;
            ShinyMetaNode * node = fs->findNode( path );
            if( node && (node->getNodeType() == ShinyMetaNode::TYPE_DIR || node->getNodeType() == ShinyMetaNode::TYPE_ROOTDIR) ) {
                const std::vector<ShinyMetaNode *> * children = ((ShinyMetaDir *) node)->getNodes();
                
                // Here is my crucible, to hold data to be pummeled out of the networking autocannon, ZMQ
                std::vector<zmq::message_t *> list( 1 + 1 + 1 + children->size() );
                list[0] = fuseRoute;
                list[1] = blankMsg;
                
                zmq::message_t ackMsg; buildTypeMsg( ShinyFilesystemMediator::ACK, &ackMsg );
                list[2] = &ackMsg;
                
                for( uint64_t i=0; i<children->size(); ++i ) {
                    zmq::message_t * childMsg = new zmq::message_t(); buildStringMsg( (*children)[i]->getName(), childMsg );
                    list[3+i] = childMsg;
                }
                
                sendMessages( sock, list );
                
                // Free up those childMsg structures and ackMsg while we're at it (ackMsg is list[1])
                for( uint64_t i=3; i<list.size(); ++i ) {
                    delete( list[i] );
                }
            } else
                sendNACK( sock, fuseRoute );
            
            // cleanup, cleanup everybody everywhere!
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::OPEN: {
            // Grab the path, shove it into an std::string for searching openFiles
            char * path = parseStringMsg( msgList[3] );
            std::string pathStr( path );
            
            // This is our file that we'll eventually send back, or not, if we can't find the file
            ShinyMetaNode * node = NULL;
            
            // First, make sure that there is not already an OpenFileInfo corresponding to this path:
            std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );
            
            // If there isn't, let's get one! (if it exists)
            if( itty == this->openFiles.end() ) {
                node = fs->findNode( path );
                if( node && node->getNodeType() == ShinyMetaNode::TYPE_FILE ) {
                    // Create the new OpenFileInfo, initialize it to 1 opens, so only 1 close required to
                    // flush this data out of the map
                    OpenFileInfo * ofi = new OpenFileInfo();
                    ofi->file = (ShinyMetaFile *) node;
                    ofi->opens = 1;
                    
                    // Aaaand, put it into the list!
                    this->openFiles[pathStr] = ofi;
                }
            } else {
                // Check to make sure this guy isn't on death row 'cause of an unlink()
                if( !(*itty).second->shouldDelete ) {
                    // Otherwise, it's in the list, so let's return the cached copy!
                    node = (ShinyMetaNode *) (*itty).second->file;
                    
                    // Increment the number of times this file has been opened...
                    (*itty).second->opens++;
                    
                    // If it was going to be closed, let's stop that from happening now
                    (*itty).second->shouldClose = false;
                }
            }
            
            // If we were indeed able to find the file; write back an ACK, otherwise, NACK it up!
            if( node )
                sendACK( sock, fuseRoute );
            else
                sendNACK( sock, fuseRoute );
            
            // Don't forget this too!
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::CLOSE: {
            // Grab the path, just like in open
            char * path = parseStringMsg( msgList[3] );
            std::string pathStr( path );

            // This time, we _only_ check openFiles
            std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );
            
            // If it's there,
            if( itty != this->openFiles.end() ) {
                OpenFileInfo * ofi = (*itty).second;
                
                // decrement the opens!
                ofi->opens--;
                
                // Should we purge this ofi from the cache?
                if( ofi->opens == 0 ) {
                    // If we are currently write locked, or we have reads ongoing, we must
                    // wait 'till those are exuahsted, and so we will just mark ourselves as suicidal
                    if( ofi->writeLocked || ofi->reads > 0 ) {
                        // This will cause it to be closed once all READs and WRITEs are finished
                        ofi->shouldClose = true;
                    } else
                        this->closeOFI( itty );
                }
                
                // Aaaand, send an ACK, just for fun
                sendACK( sock, fuseRoute );
            } else {
                // NACK!  NACK I SAY!
                sendNACK( sock, fuseRoute );
            }
            
            // You just gotta free it up, fre-fre-free it all up now, 'come on!
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::READREQ:
        case ShinyFilesystemMediator::WRITEREQ:
        case ShinyFilesystemMediator::TRUNCREQ: {
            // Grab the path, and the itty
            char * path = parseStringMsg( msgList[3] );
            std::string pathStr( path );
            std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );
            
            // If it is in openFiles,
            if( itty != this->openFiles.end() ) {
                OpenFileInfo * ofi = (*itty).second;
                
                // first, we put it into our queue of file operations,
                zmq::message_t * savedRoute = new zmq::message_t();
                savedRoute->copy( fuseRoute );
                
                // Queue this request for later
                ofi->queuedFileOperations.push_back( QueuedFO( savedRoute, type ) );
                
                // Then, we try to start up more file operations. the subroutine will check to see
                // if we actually can or not.  It's amazing!  Magical, even.
                this->startQueuedFO( sock, ofi );
            } else
                sendNACK( sock, fuseRoute );
            
            // darn all these paths.  :P
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::READDONE:
        case ShinyFilesystemMediator::WRITEDONE:
        case ShinyFilesystemMediator::TRUNCDONE: {
            // Grab the path, and the itty
            char * path = parseStringMsg( msgList[3] );
            std::string pathStr( path );
            std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );

            // If it is in openFiles,
            if( itty != this->openFiles.end() ) {
                OpenFileInfo * ofi = (*itty).second;
                
                if( type == ShinyFilesystemMediator::WRITEDONE || type == ShinyFilesystemMediator::TRUNCDONE ) {
                    // We're not writelocked!  (at least, util we start writing again. XD)
                    ofi->writeLocked = false;
                } else if( type == ShinyFilesystemMediator::READDONE ) {
                    // Decrease the number of concurrently running READS!
                    ofi->reads--;
                }
                
                // Update the file with the serialized version sent back
                //LOG( "Updating %s due to a %s", path, (type == READDONE ? "READDONE" : (type == WRITEDONE ? "WRITEDONE" : "TRUNCDONE")) );
                const char * data = (const char *) msgList[4]->data();
                ofi->file->unserialize(&data);
                //delete( fs );
                
                if( !ofi->writeLocked || ofi->reads == 0 ) {
                    // Check to see if there's stuff queued, and if the conditions are right, start that queued stuff!
                    if( !ofi->queuedFileOperations.empty() )
                        this->startQueuedFO( sock, ofi );
                    else {
                        // If there is nothing queued, and we should close this file, CLOSE IT!
                        if( ofi->shouldClose )
                            this->closeOFI( itty );
                    }
                }
            }
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::CREATEFILE:
        case ShinyFilesystemMediator::CREATEDIR: {
            // Grab the path,
            char * path = parseStringMsg( msgList[3] );
            
            // See if the file already exists
            ShinyMetaNode * node = fs->findNode( path );
            if( node ) {
                // If it does, I can't very well create a file here, now can I?
                sendNACK( sock, fuseRoute );
            } else {
                // If not, check that the parent exists;
                ShinyMetaDir * parent = fs->findParentNode(path);
                
                if( !parent ) {
                    // If it doesn't, send a NACK!
                    sendNACK( sock, fuseRoute );
                } else {
                    // Otherwise, let's create the dir/file
                    if( type == ShinyFilesystemMediator::CREATEFILE )
                        node = new ShinyMetaFile( ShinyMetaNode::basename( path ), parent );
                    else
                        node = new ShinyMetaDir( ShinyMetaNode::basename( path), parent );
                    
                    // If they have included it, set the permissions away from the defaults
                    if( msgList.size() > 4 ) {
                        uint16_t mode = *((uint16_t *) parseDataMsg( msgList[4] ));
                        node->setPermissions( mode );
                    }
                    
                    // And send back an ACK
                    sendACK( sock, fuseRoute );
                }
            }
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::DELETE: {
            // Grab the path,
            char * path = parseStringMsg( msgList[3] );
            
            // Check to make sure the file exists
            ShinyMetaNode * node = fs->findNode( path );
            if( !node ) {
                // If it doesn'y, I can't very well delete it, can I?
                sendNACK( sock, fuseRoute );
            } else {
                // Since it exists, let's make sure it's not open right now
                std::string pathStr( path );
                std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );
                
                // If it is open, queue the deletion for later
                if( itty != this->openFiles.end() ) {
                    OpenFileInfo * ofi = (*itty).second;
                    ofi->shouldDelete = true;
                } else {
                    // Tell the db to delete him, if it's a file
                    if( node->getNodeType() == ShinyMetaNode::TYPE_FILE )
                        ((ShinyMetaFile *)node)->setLen( 0 );
                    
                    // actually delete the sucker
                    delete( node );
                }
            
                // AFFLACK.  AFFFFFLAACK.
                sendACK( sock, fuseRoute );
            }
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::RENAME: {
            // Grab the path, and the new path
            char * path = parseStringMsg( msgList[3] );
            char * newPath = parseStringMsg( msgList[4] );
            
            // Check that their parents actually exist
            ShinyMetaDir * oldParent = fs->findParentNode( path );
            ShinyMetaDir * newParent = fs->findParentNode( newPath );
            
            if( oldParent && newParent ) {
                // Now that we know the parents are real, find the child
                const char * oldName = ShinyMetaNode::basename( path );
                const char * newName = ShinyMetaNode::basename( newPath );
                ShinyMetaNode * node = oldParent->findNode( oldName );
                
                if( node ) {
                    // Check to make sure we need to move it at all
                    if( oldParent != newParent ) {
                        oldParent->delNode( node );
                        newParent->addNode( node );
                    }
                    
                    // Don't setName to the same thing we had before, lol
                    if( strcmp( oldName, newName) != 0 )
                        node->setName( newName );
                    
                    // Send an ACK, for a job well done
                    sendACK( sock, fuseRoute );
                } else {
                    // We cannae faind tha node cap'n!
                    sendNACK( sock, fuseRoute );
                }

            } else {
                // Oh noes, we couldn't find oldParent or we couldn't find newParent!
                sendNACK( sock, fuseRoute );
            }
            
            delete( path );
            delete( newPath );
            break;
        }
        case ShinyFilesystemMediator::CHMOD: {
            // Grab the path, and the new path
            char * path = parseStringMsg( msgList[3] );
            uint16_t mode = *((uint16_t *) parseDataMsg( msgList[4] ));
            
            // Find node
            ShinyMetaNode * node = fs->findNode( path );
            if( node ) {
                // Set the permissionse
                node->setPermissions( mode );
                
                // ACK
                sendACK( sock, fuseRoute );
            } else
                sendNACK( sock, fuseRoute );

            delete( path );
            break;
        }
        default: {
            WARN( "Unknown ShinyFuse message type! (%d) Sending NACK:", type );
            sendNACK( sock, fuseRoute );
            break;
        }
    }
    
    return true;
}
Example #13
0
void intf_sys_t::handleMessages()
{
    unsigned i_received = 0;
    uint8_t p_packet[PACKET_MAX_LEN];
    bool b_pingTimeout = false;

    int i_waitdelay = PING_WAIT_TIME;
    int i_retries = PING_WAIT_RETRIES;

    bool b_msgReceived = false;
    uint32_t i_payloadSize = 0;
    int i_ret = recvPacket(p_stream, b_msgReceived, i_payloadSize, i_sock_fd,
                           p_tls, &i_received, p_packet, &b_pingTimeout,
                           &i_waitdelay, &i_retries);

    int canc = vlc_savecancel();
    // Not cancellation-safe part.

#if defined(_WIN32)
    if ((i_ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_ret == 0))
#else
    if ((i_ret < 0 && errno != EAGAIN) || i_ret == 0)
#endif
    {
        msg_Err(p_stream, "The connection to the Chromecast died (receiving).");
        vlc_mutex_locker locker(&lock);
        setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
        vlc_restorecancel(canc);
        return;
    }

    if (b_pingTimeout)
    {
        msgPing();
        msgReceiverGetStatus();
    }

    if (b_msgReceived)
    {
        castchannel::CastMessage msg;
        msg.ParseFromArray(p_packet + PACKET_HEADER_LEN, i_payloadSize);
        processMessage(msg);
    }

    // Send the answer messages if there is any.
    if (!messagesToSend.empty())
    {
        i_ret = sendMessages();
#if defined(_WIN32)
        if ((i_ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_ret == 0))
#else
        if ((i_ret < 0 && errno != EAGAIN) || i_ret == 0)
#endif
        {
            msg_Err(p_stream, "The connection to the Chromecast died (sending).");
            vlc_mutex_locker locker(&lock);
            setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
        }
    }

    vlc_restorecancel(canc);
}
Example #14
0
void QQmlDebugService::sendMessage(const QByteArray &message)
{
    sendMessages(QList<QByteArray>() << message);
}
Example #15
0
int main(int argc, char *argv[])
{
	if (argc != 3) {
		perror("usage: manager topologyfile messagefile"); 
	}
	router_addr = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_storage) * 16);
	for (int i = 0; i < 16; i ++) {
	  online[i] = false;
	  exist[i] = false;
	}
	int sockfd;
	struct addrinfo hints, *servinfo, *p;
	int rv;
	int numbytes;
	struct sockaddr_storage their_addr;
	char buf[MAXBUFLEN];
	socklen_t addr_len;
	char s[INET6_ADDRSTRLEN];

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_flags = AI_PASSIVE; // use my IP

	if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		return 1;
	}

	// loop through all the results and bind to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
				p->ai_protocol)) == -1) {
			perror("manager: socket");
			continue;
		}

		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("manager: bind");
			continue;
		}

		break;
	}

	if (p == NULL) {
		fprintf(stderr, "manager: failed to bind socket\n");
		return 2;
	}

	freeaddrinfo(servinfo);

	
	
	readFiles(argv[1], argv[2]);
	
	//start to build topology
	addr_len = sizeof (router_addr[0]);
	int id;
	int terminator = 77;
	
	//char adjacent[16];
	//int pos = 0;
	for (int i = 0; i < numNode; i ++) {
	        id = i + 1;
	        if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
					 (struct sockaddr *) &(router_addr[id-1]), &addr_len)) == -1) {
			perror("recvfrom");
			exit(1);
		}
		
		//send node ID to node and set it to online
		online[id-1] = true;
		
		if (numbytes = sendto(sockfd, &id, sizeof(id), 0,
				      (struct sockaddr *) &(router_addr[id - 1]), sizeof(router_addr[id - 1])) == -1) {
			perror("sendto");
			exit(1);
		}
		    printf("set new node with ID %d\n", id);
		
		//send adjacent node information to nodes
		int adjacentnum = 0;
		for (int i = 0; i < 16; i ++) {
			if (exist[i] && topology[i][id-1] > 0 && i != id - 1) {
				adjacentnum ++;
			}
		}

	       	if (numbytes = sendto(sockfd, &numNode, sizeof(int), 0,
				      (struct sockaddr *)  &(router_addr[id-1]), sizeof(router_addr[id-1])) == -1) {
       		       	perror("sendto");
	 	       	exit(1);
		}

	       if (numbytes = sendto(sockfd, &adjacentnum, sizeof(int), 0,
				     (struct sockaddr *)  &(router_addr[id-1]), sizeof(router_addr[id-1])) == -1) {
       		       	perror("sendto");
	      	       	exit(1);
		}
		
		
		    printf("start sending node %d its neignbor information\n", id);
		struct adjacent_node n;
		
		for (int i = 0; i < 16; i ++) {
			if (exist[i] && topology[i][id-1] > 0 && i != id - 1) {
				
				//set adjacent node values
				n.id = i + 1;
				if(online[i]) {
				  memcpy(&(n.router_addr),&(router_addr[i]), sizeof(struct sockaddr_storage));
					n.online = true;
				}
				else {
				  //	n.router_addr = NULL;
					n.online = false;
				}
				n.cost = topology[i][id-1];
				
				//send adjacent node value information to nodes
				if (numbytes = sendto(sockfd, &n, sizeof(n), 0,
						      (struct sockaddr *)    &(router_addr[id-1]), sizeof(router_addr[id-1])) == -1) {
					perror("sendto");
					exit(1);
				}
			}
		}
			printf("finish sending neighbor information\n");
		
		       
		//if a new node is online, should send this update to all adjacent nodes that are already online
		
		n.id = id;
		n.online = true;
		//	n.router_addr = router_addr[id-1];
		 memcpy(&(n.router_addr),&(router_addr[id-1]), sizeof(struct sockaddr_storage));
		for (int i = 0; i < 16 ; i ++) {
			if(exist[i] && topology[i][id-1] > 0 && i != id-1 && online[i]) {
			  //n.cost = topology[i][id-1];
			  if (numbytes = sendto(sockfd, &id, sizeof(id), 0, (struct sockaddr *) &(router_addr[i]), sizeof(router_addr[i])) == -1) {
			    perror("sendto");
			    exit(1);
			  }
			  if (numbytes = sendto(sockfd, &(router_addr[id-1]), sizeof(router_addr[id-1]), 0, (struct sockaddr *) &(router_addr[i]), sizeof(router_addr[i])) == -1) {
			    perror("sendto");
			    exit(1);
			  }
			  
				/*
				if (numbytes = sendto(sockfd, &n, sizeof(n), 0,
						      (struct sockaddr *) &(router_addr[i]), sizeof(router_addr[i])) == -1) {
					perror("sendto");
					exit(1);
				}
				*/
			}
		}
	
		/*
		if ((numbytes = sendto(sockfd, &terminator, sizeof(terminator), 0,
			router_addr[id-1], sizeof(router_addr[id-1])) == -1) {
			perror("sendto");
			exit(1);
		}
		*/
		
		
	}
		  printf("All nodes are online now!\n");
		  
	//broadcast information that all nodes are online
	
	char temp[2];
	temp[0] = 's';
	temp[1] = '\0';
	for (int i = 0; i < 16; i ++) {
		if(exist[i] && online[i]) {
			if (numbytes = sendto(sockfd, temp, sizeof(temp), 0,
					      (struct sockaddr *)    &(router_addr[i]), sizeof(router_addr[i])) == -1) {
			perror("sendto");
			exit(1);
			}	
		}
	}
	
	//wait for all nodes to announce convergence
	int finished = 0;
	temp[0] = 'f';
	temp[1] = '\0';
	while (finished != numNode) {
	if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
			(struct sockaddr *)&their_addr, &addr_len)) == -1) {
			perror("recvfrom");
			exit(1);
		}
	
	if(!strcmp(temp, buf)) finished ++;
	
	}
	
	//send messgae information to corresponding nodes
	sendMessages(sockfd);
	
	update(sockfd);
	
	close(sockfd);

	return 0;
}
Example #16
0
MessageModel::StatusCode MessageModel::sendMessages(const QList<SendMessagesRecipient> &recipients)
{
    return sendMessages(recipients, "anon");
}
Example #17
0
File: cast.cpp Project: Adatan/vlc
/*****************************************************************************
 * Chromecast thread
 *****************************************************************************/
static void* chromecastThread(void* p_data)
{
    int canc = vlc_savecancel();
    // Not cancellation-safe part.
    sout_stream_t* p_stream = (sout_stream_t*)p_data;
    sout_stream_sys_t* p_sys = p_stream->p_sys;

    unsigned i_received = 0;
    char p_packet[PACKET_MAX_LEN];
    bool b_pingTimeout = false;

    int i_waitdelay = PING_WAIT_TIME;
    int i_retries = PING_WAIT_RETRIES;

    msgAuth(p_stream);
    sendMessages(p_stream);
    vlc_restorecancel(canc);

    while (1)
    {
        bool b_msgReceived = false;
        uint32_t i_payloadSize = 0;
        int i_ret = recvPacket(p_stream, b_msgReceived, i_payloadSize, p_sys->i_sock_fd,
                               p_sys->p_tls, &i_received, p_packet, &b_pingTimeout,
                               &i_waitdelay, &i_retries);

        canc = vlc_savecancel();
        // Not cancellation-safe part.

#if defined(_WIN32)
        if ((i_ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_ret == 0))
#else
        if ((i_ret < 0 && errno != EAGAIN) || i_ret == 0)
#endif
        {
            msg_Err(p_stream, "The connection to the Chromecast died.");
            vlc_mutex_locker locker(&p_sys->lock);
            p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
            atomic_store(&p_sys->ab_error, true);
            break;
        }

        if (b_pingTimeout)
        {
            msgPing(p_stream);
            msgStatus(p_stream);
        }

        if (b_msgReceived)
        {
            castchannel::CastMessage msg;
            msg.ParseFromArray(p_packet + PACKET_HEADER_LEN, i_payloadSize);
            processMessage(p_stream, msg);
        }

        // Send the answer messages if there is any.
        if (!p_sys->messagesToSend.empty())
        {
            i_ret = sendMessages(p_stream);
#if defined(_WIN32)
            if ((i_ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_ret == 0))
#else
            if ((i_ret < 0 && errno != EAGAIN) || i_ret == 0)
#endif
            {
                msg_Err(p_stream, "The connection to the Chromecast died.");
                vlc_mutex_locker locker(&p_sys->lock);
                p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
            }
        }

        vlc_mutex_lock(&p_sys->lock);
        if ( p_sys->i_status == CHROMECAST_CONNECTION_DEAD )
        {
            atomic_store(&p_sys->ab_error, true);
            vlc_mutex_unlock(&p_sys->lock);
            break;
        }
        vlc_mutex_unlock(&p_sys->lock);

        vlc_restorecancel(canc);
    }

    return NULL;
}
Example #18
0
void OscService::update(){
	if(connected){
		sendMessages();
	}
}
Example #19
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void QcPlugin::done() {
	sendMessages(Core::Time());
}
static void negotiate(SecOTRSessionRef* aliceSession, SecOTRSessionRef* bobSession, bool serializeNegotiating, bool serializeMessaging, bool textMode, bool compact)
{
    const int kEmptyMessageSize = textMode ? 6 : 0;

    // Step 1: Create a start packet for each side of the transaction
    CFMutableDataRef bobStartPacket = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSAppendStartPacket(*bobSession, bobStartPacket), "Bob start packet");
    
    if (serializeNegotiating)
        serializeAndDeserialize(bobSession);
    
    CFMutableDataRef aliceStartPacket = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSAppendStartPacket(*aliceSession, aliceStartPacket), "Alice start packet");
    
    if (serializeNegotiating)
        serializeAndDeserialize(aliceSession);
    
    // Step 2: Exchange the start packets, forcing the DH commit messages to collide
    CFMutableDataRef aliceDHKeyResponse = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSProcessPacket(*aliceSession, bobStartPacket, aliceDHKeyResponse),
              "Bob DH packet failed");
    
    if (serializeNegotiating)
        serializeAndDeserialize(aliceSession);    
    
    CFReleaseNull(bobStartPacket);
    
    CFMutableDataRef bobDHKeyResponse = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSProcessPacket(*bobSession, aliceStartPacket, bobDHKeyResponse),
              "Alice DH packet failed");
    
    if (serializeNegotiating)
        serializeAndDeserialize(bobSession);
    
    CFReleaseNull(aliceStartPacket);
    
    // Step 3: With one "real" DH key message, and one replayed DH commit message, try to get a "reveal sig" out of one side
    
    CFMutableDataRef bobRevealSigResponse = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSProcessPacket(*bobSession, aliceDHKeyResponse, bobRevealSigResponse),
              "Alice DH Key packet failed");
    
    if (serializeNegotiating)
        serializeAndDeserialize(bobSession);
    
    CFReleaseNull(aliceDHKeyResponse);
    
    CFMutableDataRef aliceRevealSigResponse = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSProcessPacket(*aliceSession, bobDHKeyResponse, aliceRevealSigResponse),
              "Bob DH Key packet failed");
    
    if (serializeNegotiating)
        serializeAndDeserialize(aliceSession);
    
    CFReleaseNull(bobDHKeyResponse);
    
    // Step 4: Having gotten the reveal signature, now work for the signature
    
    CFMutableDataRef aliceSigResponse = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSProcessPacket(*aliceSession, bobRevealSigResponse, aliceSigResponse),
              "Bob Reveal sig failed");
    
    if (serializeNegotiating)
        serializeAndDeserialize(aliceSession);
    
    CFReleaseNull(bobRevealSigResponse);
    
    CFMutableDataRef bobSigResponse = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSProcessPacket(*bobSession, aliceRevealSigResponse, bobSigResponse),
              "Alice Reveal sig failed");
    
    if (serializeNegotiating)
        serializeAndDeserialize(bobSession);
    
    CFReleaseNull(aliceRevealSigResponse);
    
    // Step 5: All the messages have been sent, now deal with any replays from the collision handling
    CFMutableDataRef bobFinalResponse = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSProcessPacket(*bobSession, aliceSigResponse, bobFinalResponse),
              "Alice Final Sig failed");
    
    if (serializeNegotiating)
        serializeAndDeserialize(bobSession);
    
    CFMutableDataRef aliceFinalResponse = CFDataCreateMutable(kCFAllocatorDefault, 0);
    
    ok_status(SecOTRSProcessPacket(*aliceSession, bobSigResponse, aliceFinalResponse),
              "Bob Final Sig failed");

    is(kEmptyMessageSize, CFDataGetLength(aliceFinalResponse), "Alice had nothing left to say");
    CFReleaseNull(aliceFinalResponse);
    CFReleaseNull(bobSigResponse);

    if (serializeNegotiating)
        serializeAndDeserialize(aliceSession);
    
    is(kEmptyMessageSize, CFDataGetLength(bobFinalResponse), "Bob had nothing left to say");
    ok(SecOTRSGetIsReadyForMessages(*bobSession), "Bob is ready");
    ok(SecOTRSGetIsReadyForMessages(*aliceSession), "Alice is ready");

    CFReleaseNull(aliceSigResponse);
    CFReleaseNull(bobFinalResponse);

    sendMessages(5, bobSession, aliceSession, serializeMessaging);
    
    const char* aliceToBob = "deferredMessage";
    CFDataRef rawAliceToBob = CFDataCreate(kCFAllocatorDefault, (const uint8_t*)aliceToBob, (CFIndex) strlen(aliceToBob));
    CFMutableDataRef protectedAliceToBob = CFDataCreateMutable(kCFAllocatorDefault, 0);
    CFMutableDataRef bobDecode = CFDataCreateMutable(kCFAllocatorDefault, 0);

    ok_status(SecOTRSSignAndProtectMessage(*aliceSession, rawAliceToBob, protectedAliceToBob), "encode message");


    sendMessages(1, bobSession, aliceSession, serializeMessaging);

    is(SecOTRSVerifyAndExposeMessage(*bobSession, protectedAliceToBob, bobDecode), errSecOTRTooOld, "Decode old message");

    sendMessages(1, bobSession, aliceSession, serializeMessaging);

    is(SecOTRSVerifyAndExposeMessage(*bobSession, protectedAliceToBob, bobDecode), errSecOTRTooOld, "Decode excessively old message");

    sendMessages(3, bobSession, aliceSession, serializeMessaging);

    CFReleaseNull(rawAliceToBob);
    CFReleaseNull(protectedAliceToBob);
    CFReleaseNull(bobDecode);
}