예제 #1
0
void Server::updateNet() {
	ENetEvent event;
	while (enet_host_service(host, &event, 0) > 0) {
		switch (event.type) {
		case ENET_EVENT_TYPE_CONNECT:
			handleConnect(event.peer);
			break;
		case ENET_EVENT_TYPE_DISCONNECT:
			handleDisconnect(event.peer, (DisconnectReason) event.data);
			break;
		case ENET_EVENT_TYPE_RECEIVE:
			handlePacket(
				event.packet->data,
				event.packet->dataLength,
				event.channelID,
				event.peer
				);
			enet_packet_destroy(event.packet);
			break;
		default:
			LOG_WARNING(logger) << "Received unknown ENetEvent type << event.type";
			break;
		}
	}
}
 void TcpSymbianSerial::decodedConnectionCtrl(enum ConnectionCtrl ctrl, 
                                              const char *method, uint32 src)
 {
    if (!rootPublic() || m_shutdownPrepared || m_tcpThreadPanicked) {
       WARN("Won't handle connectioncontrol.");
       return;
    }
    switch(ctrl){
    case CONNECT:
       DBG("CONNECT %s", method);
       handleConnect(method, src);
       break;
    case DISCONNECT:
       DBG("DISCONNECT %s", method);
       handleDisconnect(method, src);
       break;
    case QUERY:
       DBG("QUERY %s", method);
       {
          enum ConnectionNotifyReason reason = UNSPECIFIED;
          //no lastsent check here. This is after all an explicit request.
          rootPublic()->connectionNotify(m_state, reason, src);
       }
       break;
    default:
       ERR("ConnectionCtrl: Unknown ctrl value: %d", ctrl);
    }
    DBG("end of decodedConnectionCtrl");
 }
예제 #3
0
void NetInterface::processPacket(const Address &sourceAddress, BitStream *pStream)
{

   // Determine what to do with this packet:

   if(pStream->getBuffer()[0] & 0x80) // it's a protocol packet...
   {
      // if the LSB of the first byte is set, it's a game data packet
      // so pass it to the appropriate connection.

      // lookup the connection in the addressTable
      // if this packet causes a disconnection, keep the conn around until this function exits
      RefPtr<NetConnection> conn = findConnection(sourceAddress);
      if(conn)
         conn->readRawPacket(pStream);
   }
   else
   {
      // Otherwise, it's either a game info packet or a
      // connection handshake packet.

      U8 packetType;
      pStream->read(&packetType);

      if(packetType >= FirstValidInfoPacketId)
         handleInfoPacket(sourceAddress, packetType, pStream);
      else
      {
         // check if there's a connection already:
         switch(packetType)
         {
            case ConnectChallengeRequest:
               handleConnectChallengeRequest(sourceAddress, pStream);
               break;
            case ConnectChallengeResponse:
               handleConnectChallengeResponse(sourceAddress, pStream);
               break;
            case ConnectRequest:
               handleConnectRequest(sourceAddress, pStream);
               break;
            case ConnectReject:
               handleConnectReject(sourceAddress, pStream);
               break;
            case ConnectAccept:
               handleConnectAccept(sourceAddress, pStream);
               break;
            case Disconnect:
               handleDisconnect(sourceAddress, pStream);
               break;
            case Punch:
               handlePunch(sourceAddress, pStream);
               break;
            case ArrangedConnectRequest:
               handleArrangedConnectRequest(sourceAddress, pStream);
               break;
         }
      }
   }
}
TinySqlApiRequestMsg::TinySqlApiRequestMsg(QObject *parent, QLocalSocket *socket) :
    QObject(parent), mClientConnection(socket)
{
    mId = -1;
    mState = NotConnected;
    connect(mClientConnection, SIGNAL(readyRead()), this, SLOT(handleRequest()));

    connect(mClientConnection, SIGNAL(disconnected()), this, SLOT(handleDisconnect()));
    connect(mClientConnection, SIGNAL(error(QLocalSocket::LocalSocketError)),
            this, SLOT(handleError(QLocalSocket::LocalSocketError)));
}
예제 #5
0
IpcChannel::IpcChannel(QLocalSocket* socket, QObject* parent)
    : QObject(parent),
    m_socket(socket),
    m_messageSize(0)
{
    m_socket->setParent(this);
    connect(m_socket, SIGNAL(readyRead()), this, SLOT(readReadyData()));
    connect(m_socket, SIGNAL(disconnected()), this, SLOT(handleDisconnect()));
    connect(m_socket, SIGNAL(error(QLocalSocket::LocalSocketError)),
            this, SLOT(handleError(QLocalSocket::LocalSocketError)));
}
예제 #6
0
void
DebugNet::networkThread()
{
#ifdef PLATFORM_WINDOWS
   SOCKET sock = (SOCKET)mSocket;
   std::vector<uint8_t> buffer;

   while (true) {
      buffer.resize(sizeof(DebugNetHeader));
      int recvd = recv(sock, (char*)&buffer[0], sizeof(DebugNetHeader), 0);
      if (recvd <= 0) {
         // Disconnected
         handleDisconnect();
         break;
      }
      assert(recvd == sizeof(DebugNetHeader));

      DebugNetHeader *header = (DebugNetHeader*)buffer.data();
      if (header->size > (uint32_t)buffer.size()) {
         buffer.resize(header->size);

         recvd = recv(sock,
            (char*)&buffer[sizeof(DebugNetHeader)],
            (int)buffer.size() - sizeof(DebugNetHeader),
            0);
         if (recvd <= 0) {
            handleDisconnect();
            break;
         }
         assert(recvd == buffer.size() - sizeof(DebugNetHeader));
      }

      DebugPacket *packet = nullptr;
      deserializePacket(buffer, packet);
      handlePacket(packet);
   }
#endif
}
TinySqlApiRequestMsg::~TinySqlApiRequestMsg()
{
    DPRINT << "SQLITEAPISRV:~TinySqlApiRequestMsg";

    disconnect(mClientConnection, SIGNAL(readyRead()), this, SLOT(handleRequest()));

    disconnect(mClientConnection, SIGNAL(disconnected()), this, SLOT(handleDisconnect()));
    disconnect(mClientConnection, SIGNAL(error(QLocalSocket::LocalSocketError)),
            this, SLOT(handleError(QLocalSocket::LocalSocketError)));

    // We actually don't need to delete socket, system takes care of it, but it is recommended
    if( mClientConnection && mClientConnection->isOpen()){
        DPRINT << "SQLITEAPISRV:closing client socket..";
        mClientConnection->close();
        mClientConnection->deleteLater();        
        DPRINT << "SQLITEAPISRV:..closed";
    }
}
예제 #8
0
static int handleNextMessage(sender_state_t sendst,
                             struct slice *xmitSlice,
                             struct slice *rexmitSlice)
{
    int pos = pc_getConsumerPosition(sendst->rc.incoming);
    union message *msg = &sendst->rc.q[pos].msg;
    int clNo = sendst->rc.q[pos].clNo;

#if DEBUG
    flprintf("handle next message\n");
#endif

    pc_consumeAny(sendst->rc.incoming);
    switch(ntohs(msg->opCode)) {
        case CMD_OK:
            handleOk(sendst, 
                     findSlice(xmitSlice, rexmitSlice, ntohl(msg->ok.sliceNo)),
                     clNo);
            break;
        case CMD_DISCONNECT:
            handleDisconnect(sendst->rc.participantsDb, 
                             xmitSlice, rexmitSlice, clNo);
            break;          
        case CMD_RETRANSMIT:
#if DEBUG
            flprintf("Received retransmittal request for %ld from %d:\n",
                     (long) xtohl(msg->retransmit.sliceNo), clNo);
#endif
            handleRetransmit(sendst,
                             findSlice(xmitSlice, rexmitSlice,
                                       ntohl(msg->retransmit.sliceNo)),
                             clNo,
                             msg->retransmit.map,
                             msg->retransmit.rxmit);
            break;
        default:
            udpc_flprintf("Bad command %04x\n", 
                          (unsigned short) msg->opCode);
            break;
    }
    pc_consumed(sendst->rc.incoming, 1);
    pc_produce(sendst->rc.freeSpace, 1);
    return 0;
}
예제 #9
0
void GameHandler::processMessage(NetComputer *computer, MessageIn &message)
{
    GameClient &client = *static_cast<GameClient *>(computer);

    if (client.status == CLIENT_LOGIN)
    {
        if (message.getId() != PGMSG_CONNECT)
            return;

        std::string magic_token = message.readString(MAGIC_TOKEN_LENGTH);
        client.status = CLIENT_QUEUED; // Before the addPendingClient
        mTokenCollector.addPendingClient(magic_token, &client);
        return;
    }
    else if (client.status != CLIENT_CONNECTED)
    {
        return;
    }

    switch (message.getId())
    {
        case PGMSG_SAY:
            handleSay(client, message);
            break;

        case PGMSG_NPC_TALK:
        case PGMSG_NPC_TALK_NEXT:
        case PGMSG_NPC_SELECT:
        case PGMSG_NPC_NUMBER:
        case PGMSG_NPC_STRING:
            handleNpc(client, message);
            break;

        case PGMSG_PICKUP:
            handlePickup(client, message);
            break;

        case PGMSG_USE_ITEM:
            handleUseItem(client, message);
            break;

        case PGMSG_DROP:
            handleDrop(client, message);
            break;

        case PGMSG_WALK:
            handleWalk(client, message);
            break;

        case PGMSG_EQUIP:
            handleEquip(client, message);
            break;

        case PGMSG_UNEQUIP:
            handleUnequip(client, message);
            break;

        case PGMSG_MOVE_ITEM:
            handleMoveItem(client, message);
            break;

        case PGMSG_ATTACK:
            handleAttack(client, message);
            break;

        case PGMSG_USE_SPECIAL_ON_BEING:
            handleUseSpecialOnBeing(client, message);
            break;

        case PGMSG_USE_SPECIAL_ON_POINT:
            handleUseSpecialOnPoint(client, message);
            break;

        case PGMSG_ACTION_CHANGE:
            handleActionChange(client, message);
            break;

        case PGMSG_DIRECTION_CHANGE:
            handleDirectionChange(client, message);
            break;

        case PGMSG_DISCONNECT:
            handleDisconnect(client, message);
            break;

        case PGMSG_TRADE_REQUEST:
            handleTradeRequest(client, message);
            break;

        case PGMSG_TRADE_CANCEL:
        case PGMSG_TRADE_AGREED:
        case PGMSG_TRADE_CONFIRM:
        case PGMSG_TRADE_ADD_ITEM:
        case PGMSG_TRADE_SET_MONEY:
            handleTrade(client, message);
            break;

        case PGMSG_NPC_BUYSELL:
            handleNpcBuySell(client, message);
            break;

        case PGMSG_RAISE_ATTRIBUTE:
            handleRaiseAttribute(client, message);
            break;

        case PGMSG_LOWER_ATTRIBUTE:
            handleLowerAttribute(client, message);
            break;

        case PGMSG_RESPAWN:
            // plausibility check is done by character class
            client.character->respawn();
            break;

        case PGMSG_NPC_POST_SEND:
            handleNpcPostSend(client, message);
            break;

        case PGMSG_PARTY_INVITE:
            handlePartyInvite(client, message);
            break;

        case PGMSG_BEING_EMOTE:
            handleTriggerEmoticon(client, message);
            break;

        default:
            LOG_WARN("Invalid message type");
            client.send(MessageOut(XXMSG_INVALID));
            break;
    }
}
예제 #10
0
/*
 *    This function is called by the handleConnection() function in
 *    rwtransfer.c once the connection has been established.  This
 *    function returns -1 on error, 0 if no files were transferred, or
 *    1 if one or more files were successfully received.
 */
int
transferFiles(
    sk_msg_queue_t     *q,
    skm_channel_t       channel,
    transfer_t         *sndr)
{
    static pthread_mutex_t open_file_mutex = PTHREAD_MUTEX_INITIALIZER;
    int fd = -1;
    uint64_t size = 0;
    uint64_t pa_size = 0;
    uint8_t *map = NULL;
    char *name = NULL;
    char *dotname = NULL;
    char dotpath[PATH_MAX];
    char destpath[sizeof(dotpath)-1];
    struct stat st;
    ino_t *inode;
    int proto_err;
    int rv;
    sk_dll_iter_t iter;
    const char *duplicate_dir;
    enum transfer_state {File_info, File_info_ack,
                         Send_file, Complete_ack, Error} state;
    int thread_exit;
    int transferred_file = 0;

    state = File_info;
    proto_err = 0;
    thread_exit = 0;
    destpath[0] = '\0';
    dotpath[0] = '\0';
    memset(&st, 0, sizeof(st));

    while (!shuttingdown && !proto_err && !thread_exit && !sndr->disconnect
           && (state != Error))
    {
        sk_msg_t *msg;

        /* Handle reads */
        switch (state) {
          case File_info:
          case Send_file:
            rv = skMsgQueueGetMessage(q, &msg);
            if (rv == -1) {
                ASSERT_ABORT(shuttingdown);
                continue;
            }
            if (handleDisconnect(msg, sndr->ident)) {
                state = Error;
            }
            break;
          case Error:
            ASSERT_ABORT(0);
            break;
          default:
            msg = NULL;
        }

        /* Handle all states */
        switch (state) {
          case File_info:
            /* Create the placeholder and dot files and mmap() the
             * space. */
            {
                file_info_t *finfo;
                uint32_t len;
                mode_t mode;
                off_t offrv;

                if ((proto_err = checkMsg(msg, q, CONN_NEW_FILE))) {
                    break;
                }
                DEBUG_PRINT1("Received CONN_NEW_FILE");
                finfo = (file_info_t *)skMsgMessage(msg);
                size = (uint64_t)ntohl(finfo->high_filesize) << 32 |
                       ntohl(finfo->low_filesize);
                pa_size = size;
                /* blocksize = ntohl(finfo->block_size); --- UNUSED */
                mode = ntohl(finfo->mode) & 0777;
                len = skMsgLength(msg) - offsetof(file_info_t, filename);
                dotname = (char *)calloc(1, len + 1);
                CHECK_ALLOC(dotname);
                name = dotname + 1;
                dotname[0] = '.';
                memcpy(name, finfo->filename, len);
                if (!memchr(name, '\0', len)) {
                    sendString(q, channel, EXTERNAL, SEND_CONN_REJECT(sndr),
                               LOG_WARNING, "Illegal filename (from %s)",
                               sndr->ident);
                    state = FILE_INFO_ERROR_STATE(sndr);
                    break;
                }

                INFOMSG("Receiving from %s: '%s' (%" PRIu64 " bytes)",
                        sndr->ident, name, size);

                /* Check filesystem for enough space for file */
                if (CHECK_DISK_SPACE(pa_size)) {
                    WARNINGMSG(("Not enough space on filesystem for %" PRIu64
                                " byte file '%s'"),
                               pa_size, name);
                    pa_size = 0;
                    state = FILESYSTEM_FULL_ERROR_STATE(sndr);
                    break;
                }

                /* Create the placeholder file */
                rv = snprintf(destpath, sizeof(destpath), "%s/%s",
                              destination_dir, name);
                if ((size_t)rv >= sizeof(destpath)) {
                    sendString(q, channel, EXTERNAL,
                               SEND_CONN_REJECT(sndr),
                               LOG_WARNING, "Filename too long (from %s)",
                               sndr->ident);
                    state = FILE_INFO_ERROR_STATE(sndr);
                    destpath[0] = '\0';
                    break;
                }

                assert((size_t)rv < sizeof(destpath));

                pthread_mutex_lock(&open_file_mutex);
              reopen:
                fd = open(destpath, O_CREAT | O_EXCL | O_WRONLY, 0);
                if (fd == -1) {
                    if (errno != EEXIST) {
                        CRITMSG("Could not create '%s': %s",
                                destpath, strerror(errno));
                        thread_exit = 1;
                        pthread_mutex_unlock(&open_file_mutex);
                        break;
                    }

                    if (stat(destpath, &st) == -1) {
                        WARNINGMSG("Unable to stat '%s': %s",
                                   destpath, strerror(errno));
                    } else if (S_ISREG(st.st_mode)
                               && ((st.st_mode & 0777) == 0)
                               && ((st.st_size == 0)))
                    {
                        /* looks like a placeholder file.  are we
                         * receiving a file with the same name from a
                         * different rwsender? */
                        int found = 0;
                        skDLLAssignIter(&iter, open_file_list);
                        while (skDLLIterForward(&iter, (void **)&inode) == 0) {
                            if (st.st_ino == *inode) {
                                WARNINGMSG(("Multiple rwsenders attempting"
                                            " to send file '%s'"),
                                           name);
                                found = 1;
                                break;
                            }
                        }
                        if (!found) {
                            WARNINGMSG(("Filename already exists (from a"
                                        " previous run?). Removing '%s'"),
                                       destpath);
                            if (unlink(destpath) == 0) {
                                goto reopen;
                            }
                            WARNINGMSG("Failed to unlink '%s': %s",
                                       destpath, strerror(errno));
                            /* treat file as a duplicate */
                        }
                    }
                    /* else file is a duplicate */
                    st.st_ino = 0;
                    destpath[0] = dotpath[0] = '\0';
                    sendString(q, channel, EXTERNAL,
                               SEND_CONN_DUPLICATE(sndr),
                               LOG_WARNING,
                               "Filename already exists (from %s)",
                               sndr->ident);
                    state = FILE_INFO_ERROR_STATE(sndr);
                    pthread_mutex_unlock(&open_file_mutex);
                    break;
                }
                /* else, successfully opened placeholder file */
                if (fstat(fd, &st) == -1) {
                    CRITMSG("Could not fstat newly created file '%s': %s",
                            destpath, strerror(errno));
                    st.st_ino = 0;
                    thread_exit = 1;
                    pthread_mutex_unlock(&open_file_mutex);
                    break;
                }
                if (skDLListPushTail(open_file_list, &st.st_ino)) {
                    CRITMSG("Unable to grow open file list");
                    st.st_ino = 0;
                    thread_exit = 1;
                    pthread_mutex_unlock(&open_file_mutex);
                    break;
                }
                pthread_mutex_unlock(&open_file_mutex);

                DEBUGMSG("Created '%s'", destpath);

                rv = close(fd);
                fd = -1;
                if (rv == -1) {
                    CRITMSG("Could not close file '%s': %s",
                            destpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }

                /* Create the dotfile */
                rv = snprintf(dotpath, sizeof(dotpath), "%s/%s",
                              destination_dir, dotname);
              reopen2:
                fd = open(dotpath, O_RDWR | O_CREAT | O_EXCL, mode);
                if (fd == -1) {
                    int saveerrno = errno;
                    if (errno == EEXIST) {
                        WARNINGMSG("Filename already exists. Removing '%s'",
                                   dotpath);
                        if (unlink(dotpath) == 0) {
                            goto reopen2;
                        }
                        WARNINGMSG("Failed to unlink '%s': %s",
                                   dotpath, strerror(errno));
                    }
                    CRITMSG("Could not create '%s': %s",
                            dotpath, strerror(saveerrno));
                    thread_exit = 1;
                    dotpath[0] = '\0';
                    break;
                }
                DEBUGMSG("Created '%s'", dotpath);

                /* Allocate space on disk */
                offrv = lseek(fd, size - 1, SEEK_SET);
                if (offrv == -1) {
                    CRITMSG("Could not allocate disk space for '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }
                rv = write(fd, "", 1);
                if (rv == -1) {
                    CRITMSG("Could not allocate disk space for '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }

                /* Map space */
                map = (uint8_t *)mmap(0, size, PROT_READ | PROT_WRITE,
                                      MAP_SHARED, fd, 0);
                if ((void *)map == MAP_FAILED) {
                    CRITMSG("Could not map '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }
                rv = close(fd);
                fd = -1;
                if (rv == -1) {
                    CRITMSG("Could not close file '%s': %s",
                            dotpath, strerror(errno));
                    thread_exit = 1;
                    break;
                }
                GOT_DISK_SPACE(pa_size);
                pa_size = 0;
                state = File_info_ack;
            }
            break;

          case File_info_ack:
            DEBUG_PRINT1("Sending CONN_NEW_FILE_READY");
            proto_err = skMsgQueueSendMessage(q, channel,
                                              CONN_NEW_FILE_READY, NULL, 0);
            state = Send_file;
            break;

          case Send_file:
            /* Get the content of the file and write into the dot file */
            {
                block_info_t *block;
                uint64_t offset;
                uint32_t len;

                if (skMsgType(msg) != CONN_FILE_BLOCK) {
                    if ((proto_err = checkMsg(msg, q, CONN_FILE_COMPLETE))) {
                        break;
                    }
                    DEBUG_PRINT1("Received CONN_FILE_COMPLETE");
                    state = Complete_ack;
                    break;
                }

                block = (block_info_t *)skMsgMessage(msg);
                len = skMsgLength(msg) - offsetof(block_info_t, block);
                offset = (uint64_t)ntohl(block->high_offset) << 32 |
                         ntohl(block->low_offset);
                DEBUG_CONTENT_PRINT("Receiving offset=%" PRIu64 " len=%" PRIu32,
                                    offset, len);
                if (offset + len > size) {
                    sendString(q, channel, EXTERNAL, CONN_DISCONNECT,
                               LOG_WARNING,
                               ("Illegal block (offset/size %" PRIu64
                                "/%" PRIu32 ")"), offset, len);
                    state = Error;
                    break;
                }
                memcpy(map + offset, block->block, len);
            }
            break;

          case Complete_ack:
            /* Un-mmap() the file, create any duplicate files, and
             * move the dotfile over the placeholder file */
            rv = munmap(map, size);
            map = NULL;
            if (rv == -1) {
                CRITMSG("Could not unmap file '%s': %s",
                        dotpath, strerror(errno));
                thread_exit = 1;
                break;
            }

            /* Handle duplicate-destinations. Any errors here are
             * simply logged and processing continues. */
            skDLLAssignIter(&iter, duplicate_dirs);
            while (skDLLIterForward(&iter, (void **)&duplicate_dir) == 0) {
                char path[sizeof(destpath)];

                snprintf(path, sizeof(path), "%s/%s", duplicate_dir, name);
                if (unique_duplicates) {
                    rv = skCopyFile(dotpath, path);
                    if (rv != 0) {
                        WARNINGMSG("Could not copy '%s' to '%s': %s",
                                   dotpath, path, strerror(rv));
                    }
                } else {
                    DEBUGMSG("Linking '%s' as '%s'", dotpath, path);
                    rv = link(dotpath, path);
                    if (EXDEV == errno) {
                        DEBUGMSG("Link failed EXDEV; copying '%s' to '%s'",
                                 dotpath, path);
                        rv = skCopyFile(dotpath, path);
                        if (rv != 0) {
                            WARNINGMSG("Could not copy '%s' to '%s': %s",
                                       dotpath, path, strerror(rv));
                        }
                    } else if (rv != 0) {
                        WARNINGMSG("Could not link '%s' as '%s': %s",
                                   dotpath, path, strerror(errno));
                    }
                }
            }

            DEBUGMSG("Renaming '%s' to '%s'", dotpath, destpath);
            rv = rename(dotpath, destpath);
            if (rv != 0) {
                CRITMSG("Failed rename of '%s' to '%s': %s",
                        dotpath, destpath, strerror(errno));
                thread_exit = 1;
                break;
            }

            /* remove the file from the open_file_list */
            pthread_mutex_lock(&open_file_mutex);
            skDLLAssignIter(&iter, open_file_list);
            while (skDLLIterForward(&iter, (void **)&inode) == 0) {
                if (st.st_ino == *inode) {
                    skDLLIterDel(&iter);
                    break;
                }
            }
            st.st_ino = 0;
            pthread_mutex_unlock(&open_file_mutex);

            DEBUG_PRINT1("Sending CONN_FILE_COMPLETE");
            proto_err = skMsgQueueSendMessage(q, channel,
                                              CONN_FILE_COMPLETE, NULL, 0);
            if (proto_err == 0) {
                /* Run the post command on the file */
                if (post_command) {
                    runPostCommand(post_command, destpath, sndr->ident);
                }
                destpath[0] = '\0';
                INFOMSG("Finished receiving from %s: '%s'", sndr->ident, name);
                free(dotname);
                dotname = NULL;
            }

            destpath[0] = dotpath[0] = '\0';
            transferred_file = 1;

            state = File_info;
            break;

          case Error:
            break;
        }

        if (msg != NULL) {
            skMsgDestroy(msg);
        }
    }

    if (fd != -1) {
        close(fd);
    }
    if (map != NULL) {
        munmap(map, size);
    }
    if (dotname != NULL) {
        free(dotname);
    }
    if (dotpath[0] != '\0') {
        DEBUGMSG("Removing '%s'", dotpath);
        unlink(dotpath);
    }
    if (destpath[0] != '\0') {
        DEBUGMSG("Removing '%s'", destpath);
        unlink(destpath);
    }
    if (st.st_ino != 0) {
        skDLLAssignIter(&iter, open_file_list);
        while (skDLLIterForward(&iter, (void **)&inode) == 0) {
            if (st.st_ino == *inode) {
                skDLLIterDel(&iter);
                break;
            }
        }
    }
    if (pa_size) {
        GOT_DISK_SPACE(pa_size);
    }
    if (thread_exit) {
        return -1;
    }

    return transferred_file;
}
예제 #11
0
void GatewayControlTask::run(){
	Timer advertiseTimer;
	Timer sendUnixTimer;
	Event* ev = 0;

	_gatewayId = atoi(_res->getArgv('i'));
	if (_gatewayId == 0 || _gatewayId > 255){
		THROW_EXCEPTION(ExFatal, ERRNO_SYS_05, "Invalid Gateway Id");  // ABORT
	}

	int keepAlive = KEEP_ALIVE_TIME;
	if(_res->getArgv('k') != 0){
		keepAlive =atoi( _res->getArgv('k'));
		if (keepAlive > 65536){
				THROW_EXCEPTION(ExFatal, ERRNO_SYS_06, "KeepAliveTime is grater than 65536 Secs");  // ABORT
		}
	}

	if(_res->getArgv('l') != 0){
		_loginId = _res->getArgv('l');
	}
	if(_res->getArgv('w') != 0){
		_password = _res->getArgv('w');
	}

	_eventQue = _res->getGatewayEventQue();

	advertiseTimer.start(keepAlive * 1000UL);

	printf("%s TomyGateway start\n", currentDateTime());


	while(true){

		ev = _eventQue->timedwait(TIMEOUT_PERIOD);

		/*------     Check Client is Lost    ---------*/
		if(ev->getEventType() == EtTimeout){
			ClientList* clist = _res->getClientList();

			for( int i = 0; i < clist->getClientCount(); i++){
				if((*clist)[i]){
					(*clist)[i]->checkTimeover();
				}else{
					break;
				}
			}

			/*------ Check Keep Alive Timer & send Advertise ------*/
			if(advertiseTimer.isTimeup()){
				MQTTSnAdvertise* adv = new MQTTSnAdvertise();
				adv->setGwId(_gatewayId);
				adv->setDuration(keepAlive);
				Event* ev1 = new Event();
				ev1->setEvent(adv);  //broadcast
				printf(YELLOW_FORMAT2, currentDateTime(), "ADVERTISE", LEFTARROW, GATEWAY, msgPrint(adv));

				_res->getClientSendQue()->post(ev1);
				advertiseTimer.start(keepAlive * 1000UL);
				sendUnixTimer.start(SEND_UNIXTIME_TIME * 1000UL);
			}

			/*------ Check Timer & send UixTime ------*/
			if(sendUnixTimer.isTimeup()){
				uint8_t buf[4];
				uint32_t tm = time(0);
				setUint32(buf,tm);

				MQTTSnPublish* msg = new MQTTSnPublish();

				msg->setTopicId(MQTTSN_TOPICID_PREDEFINED_TIME);
				msg->setTopicIdType(MQTTSN_TOPIC_TYPE_PREDEFINED);
				msg->setData(buf, 4);
				msg->setQos(0);

				Event* ev1 = new Event();
				ev1->setEvent(msg);
				printf(YELLOW_FORMAT2, currentDateTime(), "PUBLISH", LEFTARROW, GATEWAY, msgPrint(msg));

				_res->getClientSendQue()->post(ev1);
				sendUnixTimer.stop();
			}
		}

		/*------   Check  SEARCHGW & send GWINFO      ---------*/
		else if(ev->getEventType() == EtBroadcast){
			MQTTSnMessage* msg = ev->getMqttSnMessage();
			printf(YELLOW_FORMAT2, currentDateTime(), "SERCHGW", LEFTARROW, CLIENT, msgPrint(msg));

			if(msg->getType() == MQTTSN_TYPE_SEARCHGW){
				if(_res->getClientList()->getClientCount() <  MAX_CLIENT_NODES ){
					MQTTSnGwInfo* gwinfo = new MQTTSnGwInfo();
					gwinfo->setGwId(_gatewayId);
					Event* ev1 = new Event();
					ev1->setEvent(gwinfo);
					printf(YELLOW_FORMAT1, currentDateTime(), "GWINFO", RIGHTARROW, CLIENT, msgPrint(gwinfo));

					_res->getClientSendQue()->post(ev1);
				}
			}

		}
		
		/*------   Message form Clients      ---------*/
		else if(ev->getEventType() == EtClientRecv){

			ClientNode* clnode = ev->getClientNode();
			MQTTSnMessage* msg = clnode->getClientRecvMessage();
			clnode->updateStatus(msg);
			
			if(msg->getType() == MQTTSN_TYPE_PUBLISH){
				handleSnPublish(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_SUBSCRIBE){
				handleSnSubscribe(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_UNSUBSCRIBE){
				handleSnUnsubscribe(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_PINGREQ){
				handleSnPingReq(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_PUBACK){
				handleSnPubAck(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_CONNECT){
				handleSnConnect(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_WILLTOPIC){
				handleSnWillTopic(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_WILLMSG){
				handleSnWillMsg(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_DISCONNECT){
				handleSnDisconnect(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_REGISTER){
				handleSnRegister(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_PUBREC){
				handleSnPubRec(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_PUBREL){
				handleSnPubRel(ev, clnode, msg);
			}else if(msg->getType() == MQTTSN_TYPE_PUBCOMP){
				handleSnPubComp(ev, clnode, msg);
			}else{
				printf("%s   Irregular ClientRecvMessage\n", currentDateTime());
			}

		}
		/*------   Message form Broker      ---------*/
		else if(ev->getEventType() == EtBrokerRecv){

			ClientNode* clnode = ev->getClientNode();
			MQTTMessage* msg = clnode->getBrokerRecvMessage();
			
			if(msg->getType() == MQTT_TYPE_PUBACK){
				handlePuback(ev, clnode, msg);
			}else if(msg->getType() == MQTT_TYPE_PINGRESP){
				handlePingresp(ev, clnode, msg);
			}else if(msg->getType() == MQTT_TYPE_SUBACK){
				handleSuback(ev, clnode, msg);
			}else if(msg->getType() == MQTT_TYPE_UNSUBACK){
				handleUnsuback(ev, clnode, msg);
			}else if(msg->getType() == MQTT_TYPE_CONNACK){
				handleConnack(ev, clnode, msg);
			}else if(msg->getType() == MQTT_TYPE_PUBLISH){
				handlePublish(ev, clnode, msg);
			}else if(msg->getType() == MQTT_TYPE_DISCONNECT){
				handleDisconnect(ev, clnode, msg);
			}else if(msg->getType() == MQTT_TYPE_PUBREC){
				handlePubRec(ev, clnode, msg);
			}else if(msg->getType() == MQTT_TYPE_PUBREL){
				handlePubRel(ev, clnode, msg);
			}else if(msg->getType() == MQTT_TYPE_PUBCOMP){
				handlePubComp(ev, clnode, msg);
			}else{
				printf("%s   Irregular BrokerRecvMessage\n", currentDateTime());
			}
		}

		delete ev;
	}
}
예제 #12
0
PlayerWidget::PlayerWidget( int index, Database *database,
                            ControlWidget *controlWidget, Qt::WindowFlags flags )
: QWidget( controlWidget, flags )
, mPlayer( index )
, mpDatabase( database )
, mpControlWidget( controlWidget )
, mpScrollLine( new ScrollLine( this ) )
, mpStatusDisplay( new QLabel( this ) )
, mpTimeDisplay( new QLabel( this ) )
, mpPlayPosition( new TimeSlider( Qt::Horizontal, this ) )
, mpSocket( new QTcpSocket( this ) )
, mpFSM( new PlayerFSM( this ) )
, mStartOther( false )
, mAutoPlay( false )
, mTotalTime( 0 )
, mFrequency( 44100 )
, mSamples( 0 )
, mHeadStart( 10 )
, mUpdateSlider( true )
, mKioskMode( false )
, mDisplayPattern()
, mTrackInfo()
{
   QVBoxLayout *mainLayout = new QVBoxLayout( this );

   mainLayout->setContentsMargins( 0, 0, 0, 0 );
   mainLayout->setSpacing( 5 );
   mainLayout->addWidget( mpScrollLine );
   mainLayout->addWidget( mpTimeDisplay );
   mainLayout->addWidget( mpStatusDisplay );
   mainLayout->addWidget( mpPlayPosition );
   setLayout( mainLayout );

   mpStatusDisplay->setAlignment( Qt::AlignLeft );
   mpStatusDisplay->setFrameShape( QFrame::Box );
   mpStatusDisplay->setContextMenuPolicy( Qt::CustomContextMenu );
   mpStatusDisplay->setObjectName( QString("StatusLabel") );
   mpTimeDisplay->setAlignment( Qt::AlignRight );
   mpTimeDisplay->setFrameShape( QFrame::Box );
   mpTimeDisplay->setObjectName( QString("TimeLabel") );
   mpPlayPosition->setTickPosition( QSlider::TicksBelow );
   mpPlayPosition->setTickInterval( 60 );
   mpPlayPosition->setMaximum( 1 );

   connect( mpSocket, SIGNAL(connected()),
            this, SLOT(handleConnect()) );
   connect( mpSocket, SIGNAL(disconnected()),
            this, SLOT(handleDisconnect()) );
   connect( mpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(handleError(QAbstractSocket::SocketError)) );
   connect( mpSocket, SIGNAL(readyRead()),
            this, SLOT(handleResponse()) );

   connect( mpPlayPosition, SIGNAL(sliderPressed()),
            this, SLOT(lock()) );
   connect( mpPlayPosition, SIGNAL(sliderReleased()),
            this, SLOT(seek()) );
   connect( mpPlayPosition, SIGNAL(actionTriggered(int)),
            this, SLOT(playPosChange(int)) );
   connect( mpStatusDisplay, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(unload()) );

   mpFSM->changeState( PlayerFSM::disconnected );
}
예제 #13
0
void NetInterface::processPacketReceiveEvent(NetAddress srcAddress, RawData packetData)
{

   U32 dataSize = packetData.size;
   BitStream pStream(packetData.data, dataSize);

   // Determine what to do with this packet:

   if(packetData.data[0] & 0x01) // it's a protocol packet...
   {
      // if the LSB of the first byte is set, it's a game data packet
      // so pass it to the appropriate connection.

      // lookup the connection in the addressTable
      NetConnection *conn = NetConnection::lookup(&srcAddress);
      if(conn)
         conn->processRawPacket(&pStream);
   }
   else
   {
      // Otherwise, it's either a game info packet or a
      // connection handshake packet.

      U8 packetType;
      pStream.read(&packetType);
      NetAddress *addr = &srcAddress;

      if(packetType <= GameHeartbeat)
         handleInfoPacket(addr, packetType, &pStream);
#ifdef GGC_PLUGIN
      else if (packetType == GGCPacket)
      {
         HandleGGCPacket(addr, (U8*)packetData.data, dataSize);
      }
#endif
      else
      {
         // check if there's a connection already:
         switch(packetType)
         {
            case ConnectChallengeRequest:
               handleConnectChallengeRequest(addr, &pStream);
               break;
            case ConnectRequest:
               handleConnectRequest(addr, &pStream);
               break;
            case ConnectChallengeResponse:
               handleConnectChallengeResponse(addr, &pStream);
               break;
            case ConnectAccept:
               handleConnectAccept(addr, &pStream);
               break;
            case Disconnect:
               handleDisconnect(addr, &pStream);
               break;
            case ConnectReject:
               handleConnectReject(addr, &pStream);
               break;
         }
      }
   }
}
예제 #14
0
EthereumMiner::EthereumMiner(QObject *parent) :
    QObject(parent) {
    _ethereumProtocol = new EthereumProtocol(this);

    // When losing connection, handle this.
    connect(_ethereumProtocol->stratumClient(), SIGNAL(disconnectedFromServer()), this, SLOT(handleDisconnect()));
    // Once we login to the server, we want to login in right after that.
    connect(_ethereumProtocol->stratumClient(), SIGNAL(connectedToServer()), this, SLOT(login()));
    // Once we have logged in, query for work.
    connect(_ethereumProtocol, SIGNAL(eth_login(bool)), _ethereumProtocol, SLOT(eth_getWork()));
    // Evertime we receive a work package, work on it.
    connect(_ethereumProtocol, SIGNAL(eth_getWork(QString,QString,QString)), this, SLOT(processWorkPackage(QString,QString,QString)));

    setCurrentStep(Halted);
}