void closeConnection(int inputChannel , int outputChannel){ char msg[2048]; fprintf(stderr,"Sending closing connection message : %s\n" , ClientCloseConnection); if(writeInPipe(outputChannel, (byte *) ClientCloseConnection , strlen(ClientCloseConnection)) < 0) { perror("Closing client error"); return; } fprintf(stderr , "message written , waiting for response\n"); readFromPipe(inputChannel ,(byte *) msg); if(strncmp(msg , ServerCloseConnection , strlen(ServerCloseConnection)) != 0) { perror("Closing client error"); return; } fprintf(stderr , "Connection closed\n\n"); closeChannel(inputChannel); closeChannel(outputChannel); }
std::string SSH::execute(const std::string& command) { _logger->trace("Executing SSH command: %s", command); int rc; char buffer[1024]; int nbytes; memset(buffer, 0, 1024); if (_ssh == NULL) { _logger->debug("Initializing SSH"); _ssh = ssh_new(); } if (_ssh == NULL) { throw SubutaiException("Failed to start SSH session"); } if (!_bChanOpen) { rc = openChannel(); if (rc != E_NOERR) { _logger->error("Couldn't open SSH channel: %d", rc); return ""; } } _logger->trace("Starting SSH command execution"); rc = ssh_channel_request_exec(_channel, command.c_str()); if (rc != SSH_OK) { closeChannel(); throw SSHException("Failed to execute SSH command", SSHErrorCode::E_CMD_EXEC_FAILED); } _logger->trace("Reading from channel"); nbytes = ssh_channel_read(_channel, buffer, sizeof(buffer), 0); std::string pBuffer(""); while (nbytes > 0) { pBuffer.append(buffer); nbytes = ssh_channel_read(_channel, buffer, sizeof(buffer), 0); } if (nbytes < 0) { closeChannel(); throw SSHException("Output channel is empty", SSHErrorCode::E_EMPTY_OUTPUT_CHAN); } closeChannel(); _logger->debug("SSH Execution output: %s", pBuffer); return Poco::trim(pBuffer); }
void AbstractSshChannel::handleOpenSuccess(quint32 remoteChannelId, quint32 remoteWindowSize, quint32 remoteMaxPacketSize) { const ChannelState oldState = m_state; switch (oldState) { case CloseRequested: // closeChannel() was called while we were in SessionRequested state case SessionRequested: break; // Ok, continue. default: throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR, "Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION packet."); } m_timeoutTimer.stop(); if (remoteMaxPacketSize < MinMaxPacketSize) { throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR, "Maximum packet size too low."); } #ifdef CREATOR_SSH_DEBUG qDebug("Channel opened. remote channel id: %u, remote window size: %u, " "remote max packet size: %u", remoteChannelId, remoteWindowSize, remoteMaxPacketSize); #endif m_remoteChannel = remoteChannelId; m_remoteWindowSize = remoteWindowSize; m_remoteMaxPacketSize = remoteMaxPacketSize; setChannelState(SessionEstablished); if (oldState == CloseRequested) closeChannel(); else handleOpenSuccessInternal(); }
// Maps over to the other closeChannel call void Session::closeChannel(Channel *ch, char *data, unsigned int length) throw (CloseChannelException) { if(status == STATUS_CLOSED && ch->getChannelNumber() != 0) return; closeChannel(ch->getChannelNumber()); }
void SshDirectTcpIpTunnelPrivate::handleEof() { /* * For some reason, the OpenSSH server only sends EOF when the remote port goes away, * but does not close the channel, even though it becomes useless in that case. * So we close it ourselves. */ closeChannel(); }
status_t OverlayUI::setSource(const overlay_buffer_info& info, int orientation, bool useVGPipe, bool ignoreFB, int fbnum, int zorder) { status_t ret = NO_INIT; int format3D = FORMAT_3D(info.format); int colorFormat = COLOR_FORMAT(info.format); int format = get_mdp_format(colorFormat); if (format3D || !isRGBType(format)) return ret; if (mChannelState == PENDING_CLOSE) closeChannel(); if (mChannelState == UP) { mdp_overlay ov; if (mobjOVHelper.getOVInfo(ov) == NO_ERROR) { if (mOrientation == orientation && mFBNum == fbnum && checkOVState(info.width, info.height, format, orientation, zorder, ignoreFB, ov)) return NO_ERROR; else mChannelState = PENDING_CLOSE; } else mChannelState = PENDING_CLOSE; return ret; } mOrientation = orientation; mdp_overlay ovInfo; msm_rotator_img_info rotInfo; setupOvRotInfo(info.width, info.height, format, orientation, ovInfo, rotInfo); int flags = 0; if (ignoreFB) ovInfo.is_fg = 1; else flags |= MDP_OV_PLAY_NOWAIT; if (turnOFFVSync()) flags |= MDP_OV_PLAY_NOWAIT; if (useVGPipe || (fbnum == FB0 && getRGBBpp(format) != mobjOVHelper.getFBBpp())) flags |= MDP_OV_PIPE_SHARE; ovInfo.flags = flags; if (zorder != NO_INIT) ovInfo.z_order = zorder; ret = startChannel(fbnum, ovInfo, rotInfo, info.size); return ret; }
void SocketIO::createChannel(const char *remoteCommand, int *protocol) { closeChannel(); std::stringstream error; d_socket = rsync::SocketUtil::create(d_serverList.c_str(), d_port, &error); if (d_socket == -1) { LOG_FATAL(SOCKET_CONNECT) << error.str() << LOG_END return; }
virtual void go() { LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__); for (int i = 0; i < max_count; ++i) { UInt32 chid = rand() % UINT_MAX + 1; closeChannel(chid); } }
void AbstractSshChannel::sendData(const QByteArray &data) { try { m_sendBuffer += data; flushSendBuffer(); } catch (Botan::Exception &e) { qDebug("Botan error: %s", e.what()); closeChannel(); } }
void AbstractSshChannel::sendData(const QByteArray &data) { try { m_sendBuffer += data; flushSendBuffer(); } catch (const std::exception &e) { qCWarning(sshLog, "Botan error: %s", e.what()); closeChannel(); } }
void AbstractSshChannel::handleChannelClose() { qCDebug(sshLog, "Receiving CLOSE for channel %u", m_localChannel); if (channelState() == Inactive || channelState() == Closed) { throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR, "Unexpected SSH_MSG_CHANNEL_CLOSE message."); } closeChannel(); setChannelState(Closed); }
virtual void go() { LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__); for (int i = 0; i < max_count; ++i) { UInt32 chid = allocChannel(ePlainData, this); closeChannel(chid); } }
void SSH2Channel::channelClosed() { m_in->getUInt8(); uint localID = m_in->getUInt32(); Channel * target = m_channelList.at(localID); m_out->startPacket(SSH2_MSG_CHANNEL_CLOSE); m_out->putUInt32(target->remoteID); m_out->sendPacket(); emit closeChannel(localID); m_channelList.removeAt(localID); }
bool BassPlayer::stopProcessing() { if (openChannelWatcher) { while(openChannelWatcher && !openChannelWatcher -> isFinished()) QApplication::processEvents(); // openChannelWatcher -> waitForFinished(); } closeChannel(); return true; }
void SftpChannelPrivate::handleChannelFailure() { if (channelState() == CloseRequested) return; if (m_sftpState != SubsystemRequested) { throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR, "Unexpected SSH_MSG_CHANNEL_FAILURE packet."); } emit initializationFailed(tr("Server could not start SFTP subsystem.")); closeChannel(); }
void SshForwardedTcpIpTunnelPrivate::handleOpenSuccessInternal() { QSSH_ASSERT_AND_RETURN(channelState() == AbstractSshChannel::SessionEstablished); try { m_sendFacility.sendChannelOpenConfirmationPacket(remoteChannel(), localChannelId(), initialWindowSize(), maxPacketSize()); } catch (const std::exception &e) { // Won't happen, but let's play it safe. qCWarning(sshLog, "Botan error: %s", e.what()); closeChannel(); } }
virtual void go() { LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__); for (int i = 0; i < max_count; ++i) { UInt32 chid = allocChannel(ePlainData, this); sync_test("MultipleOpenCloseTest alloc sync"); closeChannel(chid); sync_test("MultipleOpenCloseTest close sync"); } }
static void job(IThreadPoolJobData const* pData) { struct Observer : public IChannelObserver { virtual void dataReceivedCallback(const UInt32 channel_id, const UInt32 read_size)//, const UInt32 free_size) { LOG4CPLUS_TRACE(msLogger, std::string("Observer::bufferOverflowCallback ") + "channel_id = " + convertIntegerToString(channel_id) + "read_size = " + convertIntegerToString(read_size));// + // "free_size = " + convertIntegerToString(free_size)); } virtual void bufferOverflowCallback(const UInt32 channel_id) { LOG4CPLUS_TRACE(msLogger, "Observer::bufferOverflowCallback channel_id = " + convertIntegerToString(channel_id)); } virtual void channelDeletedCallback(const UInt32 channel_id) { LOG4CPLUS_TRACE(msLogger, "Observer::channelDeletedCallback channel_id = " + convertIntegerToString(channel_id)); } virtual void connectionLostCallback() { LOG4CPLUS_TRACE(msLogger, "Observer::connectionLostCallback"); } }; Observer obs; LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__); JobBarrierData const* jdb = static_cast<JobBarrierData const*>(pData); LOG4CPLUS_INFO(msLogger, "job begin, waiting"); int res = pthread_barrier_wait(jdb->pBar); LOG4CPLUS_INFO(msLogger, "job wait done, allocating"); UInt32 chid = allocChannel(ePlainData, &obs); closeChannel(chid); LOG4CPLUS_INFO(msLogger, "job close done, waiting"); res = pthread_barrier_wait(jdb->pBar); if (res == PTHREAD_BARRIER_SERIAL_THREAD) { jdb->pSem->signal(); LOG4CPLUS_INFO(msLogger, "signaling to main thread"); } LOG4CPLUS_INFO(msLogger, "job done, waiting"); }
void AbstractSshChannel::requestSessionStart() { // Note: We are just being paranoid here about the Botan exceptions, // which are extremely unlikely to happen, because if there was a problem // with our cryptography stuff, it would have hit us before, on // establishing the connection. try { m_sendFacility.sendSessionPacket(m_localChannel, initialWindowSize(), maxPacketSize()); setChannelState(SessionRequested); m_timeoutTimer.start(ReplyTimeout); } catch (const Botan::Exception &e) { qDebug("Botan error: %s", e.what()); closeChannel(); } }
bool ClientSidePlayerChannel::receiveMessage(const QByteArray& msg) { QJsonParseError errors; QJsonDocument doc(QJsonDocument::fromJson(msg, &errors)); if (errors.error != QJsonParseError::NoError) { WARN("Failed to parse json message: error =" << errors.errorString() << ", offset =" << errors.offset << ", message =" << msg); return false; } QJsonObject json(doc.object()); if (json.contains("command") && json["command"] == "CloseChannel") { DEBUG("CloseChannel received"); closeChannel(); // no responses return true; } else if (json.contains("command") && json["command"] == "PlayerMessage") { DEBUG("PlayerMessage received"); // TODO: more complex if (json.contains("data")) { QString msgStr; // TODO: encode data if (json["data"].isObject()) { msgStr.append(QJsonDocument(json["data"].toObject()).toJson()); } else msgStr.append(json["data"].toString()); if (_playerPartner) _playerPartner->playerMessage(msgStr.toLatin1()); return true; } } else { DEBUG("UNKNOWN MESSAGE"); } return false; }
SSH::~SSH() { if (_bShellOpen) { closeShell(); } if (_bChanOpen) { closeChannel(); } _logger->debug("Destructing SSH instance"); if (_connected) ssh_disconnect(_ssh); if (_ssh != NULL) { _logger->trace("Freeing SSH object"); ssh_free(_ssh); } _logger->debug("SSH instance destructed"); }
virtual void go() { LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__); for (int i = 0; i < max_count; ++i) { UInt32 chid = allocChannel(ePlainData, this); //sync_test("DataLostAfterChannelAlloc alloc sync"); int sem_res = data_sem.waitTimeout(timeout); assert(0 == sem_res && "data lost, sem exited by timeout"); sync_test("DataLostAfterChannelAlloc data sync"); closeChannel(chid); sync_test("DataLostAfterChannelAlloc close sync"); } }
BOOL SendTestFrames( FT_HANDLE ftHandle ) { CANMsg msg; if ( !openChannel( ftHandle, 6 ) ) { printf("Failed to open channel\n"); return FALSE; } // Send extended frame msg.flags = CANMSG_EXTENDED; msg.id = 0x123456; msg.len = 2; msg.data[0] = 1; msg.data[1] = 2; if ( !sendFrame( ftHandle, &msg ) ) { printf("Failed to send frame\n"); return FALSE; } // Send standard frame msg.flags = 0; msg.id = 0x123; msg.len = 2; msg.data[0] = 1; msg.data[1] = 2; if ( !sendFrame( ftHandle, &msg ) ) { printf("Failed to send frame\n"); return FALSE; } FT_Purge( ftHandle, FT_PURGE_TX ); if ( !closeChannel( ftHandle ) ) { printf("Failed to close channel\n"); return FALSE; } return TRUE; }
BOOL GetTestFrames( FT_HANDLE ftHandle ) { gnReceivedFrames = 0; if ( !openChannel( ftHandle, 6 ) ) { printf("Failed to open channel\n"); return FALSE; } printf("Waiting to receive five frames (ctrl-c to abort)...\n"); while ( gnReceivedFrames < 5 ) { readFrame( ftHandle ); } if ( !closeChannel( ftHandle ) ) { printf("Failed to close channel\n"); return FALSE; } return TRUE; }
void SftpChannelPrivate::handleServerVersion() { checkChannelActive(); if (m_sftpState != InitSent) { throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR, "Unexpected SSH_FXP_VERSION packet."); } #ifdef CREATOR_SSH_DEBUG qDebug("sftp init received"); #endif const quint32 serverVersion = m_incomingPacket.extractServerVersion(); if (serverVersion != ProtocolVersion) { emit initializationFailed(tr("Protocol version mismatch: Expected %1, got %2") .arg(serverVersion).arg(ProtocolVersion)); closeChannel(); } else { m_sftpState = Initialized; emit initialized(); } }
void BassPlayer::afterSourceOpening() { QFutureWatcher<OpenCallbackData> * watcher = (QFutureWatcher<OpenCallbackData> *)sender(); OpenCallbackData result = watcher -> result(); if (proc_channel.uid != result.uid) BASS_StreamFree(result.channel_handle); else { closeChannel(); //INFO: close prev channel chan = result.channel_handle; if (!chan) proceedErrorState(result.error); else { emit statusChanged(media_title, LoadedMedia); if (chan) playPreproccessing(); } } watcher -> deleteLater(); if (watcher == openChannelWatcher) openChannelWatcher = 0; }
virtual void go() { LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__); UInt8 data[1] = { 42 }; for (int i = 0; i < max_count; ++i) { UInt32 chid = allocChannel(ePlainData, this); //sync_test("DataLostAfterChannelAlloc alloc sync"); ERROR_CODE err = sendData(chid, data, 1); assert(ERR_OK == err && "sendData error"); // if (ERR_OK != err) // { // LOG4CPLUS_WARN(msLogger, "sendData err = " + covertIntegerToString((int)err)); // } sync_test("DataLostAfterChannelAlloc data sync"); closeChannel(chid); sync_test("DataLostAfterChannelAlloc close sync"); } }
int Parser::runCommand(QString command) { // command channel //------------setup channel ---------------------- LIBSSH2_CHANNEL *channel = NULL; channel = libssh2_channel_open_session(session_); if ( channel == NULL ) { qDebug()<<"Failed to open a new channel\n"; socket_->disconnectFromHost(); return -1; } /* Force Data to on STDOUT and STDERR to be on seperate channels * read individually with *_read and *_read_stderr functions */ libssh2_channel_handle_extended_data(channel,LIBSSH2_CHANNEL_EXTENDED_DATA_NORMAL); libssh2_channel_set_blocking(channel, 1); { int rc; while ((rc=libssh2_channel_exec(channel, command.toLocal8Bit().constData()))==LIBSSH2_ERROR_EAGAIN ); if (rc) { return -1; } //-------read channel----------- int read; QString stdout_str; QString stderr_str; while(true) { //qDebug("libssh2_channel_read() >>>"); { QByteArray byte_array; byte_array.resize(4096); char* buffer=byte_array.data(); int buffer_size=byte_array.size(); read = libssh2_channel_read(channel, buffer, buffer_size-10); if(read>0) { QByteArray debug = QByteArray(buffer, read); stdout_str.append(debug); } if(LIBSSH2_ERROR_EAGAIN == read) { qDebug("LIBSSH2_ERROR_EAGAIN"); break; } else if(read < 0) { qDebug(" error reading from std channel"); closeChannel(channel); goto next_channel; } } { QByteArray byte_array; byte_array.resize(4096); char* buffer=byte_array.data(); int buffer_size=byte_array.size(); read = libssh2_channel_read_stderr(channel, buffer, buffer_size-10); if(read>0) { QByteArray debug = QByteArray(buffer, read); stderr_str.append(debug); } if(LIBSSH2_ERROR_EAGAIN == read) { qDebug("LIBSSH2_ERROR_EAGAIN"); break; } else if(read < 0) { qDebug(" error reading from stderr channel"); closeChannel(channel); goto next_channel; } } int i = libssh2_channel_eof(channel); if(i) { //qDebug("libssh2_channel_eof %i", i); closeChannel(channel); goto next_channel; } } next_channel: if(!stdout_str.isEmpty()) { qDebug()<<"STDOUT:\n"<<stdout_str; } if(!stderr_str.isEmpty()) { qDebug()<<"STDERR:\n"<<stderr_str; } } return 1; }
OverlayUI::~OverlayUI() { closeChannel(); }
QString Parser::sshRequest(QString commandline) { QString host_ip(this->sharedHost); QString user_name=this->sharedUser; QString pass_word=this->sharedPass; //---------- connection -------------- int libssh2_error = libssh2_init(0); if(libssh2_error) { qDebug("libssh2_init() error: %d", libssh2_error); //return -2; } QTcpSocket socket; socket.connectToHost(host_ip, 22); if(!socket.waitForConnected()) { qDebug("Error connecting to host %s", host_ip.toLocal8Bit().constData()); //return -1; } LIBSSH2_SESSION *session = libssh2_session_init(); if(!session) { qDebug("libssh2_session_init() failed"); //return -2; } libssh2_error = libssh2_session_startup(session, socket.socketDescriptor()); if(libssh2_error) { qDebug("libssh2_session_startup() error: %d", libssh2_error); //return -3; } { /* At this point we havn't yet authenticated. The first thing to do * is check the hostkey's fingerprint against our known hosts Your app * may have it hard coded, may go to a file, may present it to the * user, that's your call */ const char *fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); } libssh2_userauth_list(session, user_name.toLocal8Bit().constData(), user_name.toLocal8Bit().length()); if(libssh2_userauth_password( session, user_name.toLocal8Bit().constData(), pass_word.toLocal8Bit().constData() )) { qDebug("Password authentication failed"); socket.disconnectFromHost(); libssh2_session_disconnect(session, "Client disconnecting for error"); libssh2_session_free(session); libssh2_exit(); //return -4; } // command channel //------------setup channel ---------------------- LIBSSH2_CHANNEL *channel = NULL; channel = libssh2_channel_open_session(session); int rc; if ( channel == NULL ) { qDebug()<<"Failed to open a new channel\n"; socket.disconnectFromHost(); //return -1; } libssh2_channel_set_blocking(channel, 1); while ((rc=libssh2_channel_exec(channel, commandline.toLocal8Bit().constData()))==LIBSSH2_ERROR_EAGAIN ); if (rc) { //return -1; } //-------read channel----------- int read; QByteArray byte_array; byte_array.resize(4096); char* buffer=byte_array.data(); int buffer_size=byte_array.size(); QString myOutPut; while(true) { { read = libssh2_channel_read(channel, buffer, buffer_size); QByteArray debug = QByteArray(buffer, read); //qDebug()<<"STDOUT: "<<debug.constData(); myOutPut = debug.constData(); qDebug() << myOutPut; if(LIBSSH2_ERROR_EAGAIN == read) { qDebug("LIBSSH2_ERROR_EAGAIN"); break; } else if(read < 0) { qDebug(" error reading from channel"); closeChannel(channel); goto next_channel; } } { read = libssh2_channel_read_stderr(channel, buffer, buffer_size); QByteArray debug = QByteArray(buffer, read); qDebug()<<"STDERR: "<<debug.constData(); if(LIBSSH2_ERROR_EAGAIN == read) { qDebug("LIBSSH2_ERROR_EAGAIN"); break; } else if(read < 0) { qDebug(" error reading from channel"); closeChannel(channel); goto next_channel; } } int i=0; i = libssh2_channel_eof(channel); if(i) { qDebug("libssh2_channel_eof %i", i); closeChannel(channel); goto next_channel; } } next_channel: //------------ clean session socket.disconnectFromHost(); libssh2_session_disconnect(session, "Client disconnecting normally"); libssh2_session_free(session); libssh2_exit(); return myOutPut; }