bool DrHttpClient::stopConnection(string strUrl){
	/* remove url which is connected*/
	showLog("Jni.DrHttpClient stopConnection", "strUrl=%s", strUrl.c_str());
	bool bFlag = false;
	m_DrMutex.lock();
	HTTPSOCKETMAP::iterator it = m_SocketMap.find(strUrl);
	if(it != m_SocketMap.end()){
		tcpSocket *pSocket = it->second._pSocket;
		if(pSocket){
//#ifdef PRINT_JNI_LOG
//			if(mIDrHttpClientCallback) {
//				char logBuffer[DrHttpClient_BUFFER_2K];
//				memset(logBuffer, '\0', DrHttpClient_BUFFER_2K);
//				sprintf(logBuffer, "%s:\r\nstopConnection close socket:%d _isReceiving:%d\r\n%s", "Jni.DrHttpClient.stopConnection", pSocket->getSocketId(), (it->second)._isReceiving, LOG_SEP);
//				mIDrHttpClientCallback->onWriteLog((unsigned char*)logBuffer, strlen(logBuffer), -1);
//			}
//#endif
			pSocket->Close();
			bFlag = true;
			showLog("Jni.DrHttpClient stopConnection", "_isReceiving:%d", (it->second)._isReceiving);
			if((it->second)._isReceiving == false) {
				delete pSocket;
				pSocket = NULL;
			}
		}
    	m_SocketMap.erase(it);
    	showLog("Jni.DrHttpClient.stopConnection", "stopConnection m_SocketMap.erase:%s", (it->first).c_str());
	}
	m_DrMutex.unlock();
	showLog("Jni.DrHttpClient stopConnection", "bFlag:%d", bFlag);
	return bFlag;
}
int DrHttpClient::getUrlPort(string url, string &newUrl, string &port, string &param){
//	showLog("Jni.DrHttpClient.getUrlPort", "before new tempBuf url:%s", url.c_str());
	char *tempBuf = new char[DrHttpClient_BUFFER_4K];
	int ret = -1;
	const char *portEnd = "/";
	const char *portStart = ":";
	char *end;
	char *host = StringHandle::strIstr(url.c_str(), HTTP_URL_START);
//	showLog("Jni.DrHttpClient.getUrlPort", "host before:%s", host);
	if(host){
		host += sizeof(HTTP_URL_START) - 1;
	}
	else{
		host = (char*)url.c_str();
	}
	//showLog("Jni.DrHttpClient.getUrlPort", "host after:%s", host);
	char *sep = StringHandle::strIstr(host, portStart);
	if (sep) {
		for (end = sep + 1; *end; ++end) {
			if (toupper(*end) > '9' || toupper(*end) < '0') {
//				showLog("Jni.DrHttpClient.getUrlPort", "url(%x):%s", url.c_str(),url.c_str());
//				showLog("Jni.DrHttpClient.getUrlPort", "host(%x):%s", host, host);
//				showLog("Jni.DrHttpClient.getUrlPort", "sep(%x):%s", sep, sep);
				newUrl = StringHandle::findStringBetween((char*)url.c_str(), (char*)host, (char*)sep, tempBuf, DrHttpClient_BUFFER_4K);
//				showLog("Jni.DrHttpClient.getUrlPort", "newUrl:%s", newUrl.c_str());
				port = StringHandle::findStringBetween((char*)url.c_str(), (char*)sep + 1, (char*)end, tempBuf, DrHttpClient_BUFFER_4K);
//				showLog("Jni.DrHttpClient.getUrlPort", "port:%s", port.c_str());
				if(NULL != end){
					param = end;
				}
//				showLog("Jni.DrHttpClient.getUrlPort", "newUrl:%s port:%s", newUrl.c_str(), port.c_str());
				ret = 1;
				break;
			}
		}
	}
	else{
		for (end = host; *end; ++end) {
			if (toupper(*end) == toupper(*portStart)) {
				newUrl = StringHandle::findStringBetween((char*)url.c_str(), (char*)host, (char*)end, NULL, 0);
				if(NULL != end){
					param = end;
				}
				ret = 1;
				break;
			}
		}
		showLog("Jni.DrHttpClient.getUrlPort", "newUrl:%s no port found!",newUrl.c_str());
	}
	showLog("Jni.DrHttpClient.getUrlPort", "ret:%d", ret);
	if(tempBuf)
		delete[] tempBuf;
	return ret;
}
DrHttpClient::~DrHttpClient() {
	showLog("Jni.DrHttpClient.~DrHttpClient", "");
	for(int i=0; i<MAXTHREADCOUNT; i++){
		if(m_ThreadArray[i]){
			if(m_ThreadArray[i]->isRunning()){
				m_ThreadArray[i]->stop();
				showLog("Jni.DrHttpClient.~DrHttpClient", "stop m_ThreadArray[%d]", i);
			}
			delete m_ThreadArray[i];
		}
	}
}
/*
 * Class:     com_drcom_drauth_DrAuthJni
 * Method:    StatusPPOE
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_com_drcom_drauth_DrAuthJni_StatusPPOE
	(JNIEnv *env, jobject) {
	jboolean jbFlag = StatusPPPoE();
	if(jbFlag) {
		// 开始DrPPPoE插件协议
		showLog("jni.StatusPPOE", "检测到PPPoE已经拨号");
		if(!g_DrppoePlugin.IsRunning()) {
			g_DrppoePlugin.StartDrPPPoEPlugin();
		}
	}
	else {
		showLog("jni.StatusPPOE", "没有检测到PPPoE拨号!");
	}
	return jbFlag;
}
int DrHttpClient::httpPost(string strUrl, const char* data, int len, bool isKeepAlive){
	for(int i=0; i<MAXTHREADCOUNT; i++){
		if(m_ThreadArray[i]){
			if(!m_ThreadArray[i]->isRunning()){
				showLog("Jni.DrHttpClient.httpPost", "m_ThreadArray[%d] use", i);
				HTTPCLIENTTHREADDATA thdata;
				thdata._url = strUrl;
				thdata._size = len;
				thdata._data = (char*)data;

				if(!isKeepAlive){
					m_ThreadArray[i]->setParams(this, HTTPPOST, thdata);

				}
				else{
					m_ThreadArray[i]->setParams(this, HTTPPOST_KEEP_ALIVE, thdata);
				}
				m_ThreadArray[i]->start();
				//delete thdata;
				return m_ThreadArray[i]->getThreadId();
			}
		}
	}
	return -1;
}
/*
 * Receive a log message.  We happen to know that "vector" has three parts:
 *
 *  priority (1 byte)
 *  tag (N bytes -- null-terminated ASCII string)
 *  message (N bytes -- null-terminated ASCII string)
 */
static ssize_t logWritev(int fd, const struct iovec* vector, int count)
{
    LogState* state;
    DECLARE_SIGSET(sigflags);

    /* Make sure that no-one frees the LogState while we're using it.
     * Also guarantees that only one thread is in showLog() at a given
     * time (if it matters).
     */
    lock(&sigflags);

    state = fdToLogState(fd);
    if (state == NULL) {
        errno = EBADF;
        goto error;
    }

    if (state->isBinary) {
        TRACE("%s: ignoring binary log\n", state->debugName);
        goto bail;
    }

    if (count != 3) {
        TRACE("%s: writevLog with count=%d not expected\n",
              state->debugName, count);
        goto error;
    }

    /* pull out the three fields */
    int logPrio = *(const char*)vector[0].iov_base;
    const char* tag = (const char*) vector[1].iov_base;
    const char* msg = (const char*) vector[2].iov_base;

    /* see if this log tag is configured */
    int i;
    int minPrio = state->globalMinPriority;
    for (i = 0; i < kTagSetSize; i++) {
        if (state->tagSet[i].minPriority == ANDROID_LOG_UNKNOWN)
            break;      /* reached end of configured values */

        if (strcmp(state->tagSet[i].tag, tag) == 0) {
            //TRACE("MATCH tag '%s'\n", tag);
            minPrio = state->tagSet[i].minPriority;
            break;
        }
    }

    if (logPrio >= minPrio) {
        showLog(state, logPrio, tag, msg);
    } else {
        //TRACE("+++ NOLOG(%d): %s %s", logPrio, tag, msg);
    }

bail:
    unlock(&sigflags);
    return vector[0].iov_len + vector[1].iov_len + vector[2].iov_len;
error:
    unlock(&sigflags);
    return -1;
}
示例#7
0
void PlanExecutor::integrityCheckFinished(KJob *pJob) {
	endSleepInhibit();
	discardIntegrityNotification();
	mIntegrityNotification = new KNotification(QStringLiteral("IntegrityCheckCompleted"), KNotification::Persistent);
	mIntegrityNotification->setTitle(xi18nc("@title:window", "Integrity Check Completed"));
	mIntegrityNotification->setText(pJob->errorText());
	QStringList lAnswers;
	if(pJob->error() == BackupJob::ErrorWithLog) {
		lAnswers << xi18nc("@action:button", "Show log file");
		connect(mIntegrityNotification, SIGNAL(action1Activated()), SLOT(showLog()));
	} else if(pJob->error() == BackupJob::ErrorSuggestRepair) {
		lAnswers << xi18nc("@action:button", "Yes");
		lAnswers << xi18nc("@action:button", "No");
		connect(mIntegrityNotification, SIGNAL(action1Activated()), SLOT(startRepairJob()));
	}
	mIntegrityNotification->setActions(lAnswers);

	connect(mIntegrityNotification, SIGNAL(action2Activated()), SLOT(discardIntegrityNotification()));
	connect(mIntegrityNotification, SIGNAL(closed()), SLOT(discardIntegrityNotification()));
	connect(mIntegrityNotification, SIGNAL(ignored()), SLOT(discardIntegrityNotification()));
	mIntegrityNotification->sendEvent();

	if(mState == INTEGRITY_TESTING) { //only restore if nothing has changed during the run
		mState = mLastState;
	}
	emit stateChanged();
}
示例#8
0
void usermain(int argc, char * argv[])
{
    WApplication app(argc, argv);
    app.setTitle("ShowLog");
    
	CShowLog showLog(app.root());
	showLog.appSelf = &app;
	app.setBodyAttribute("class='workbody' ");
    app.exec();
}
/*
 * Class:     com_drcom_drauth_DrAuthJni
 * Method:    LogoutPPOE
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_drcom_drauth_DrAuthJni_LogoutPPOE
	(JNIEnv *env, jobject thiz) {

	SnifferCommand scmd;
	scmd.scmdt = StopSnifferType;
	g_DrCommandHandler.SendCommand(scmd);

	jint iCode = 0;

	char cmd[1024] = {'\0'};
	sprintf(cmd, "setprop net.pppoe.ppp-exit %s", DrPPPID);
	SystemComandExecuteWithRoot(cmd);
	SystemComandExecuteWithRoot("setprop net.pppoe.reason gone");
	SystemComandExecuteWithRoot("setprop net.pppoe.interface");

	FILE* file = fopen(DrPPPID, "r");
	if(NULL != file) {
		showLog("jni.LogoutPPOE", "file is not NULL");
		int pid = -1;
		fscanf(file, "%d", &pid);
		showLog("jni.LogoutPPOE", "pid:%d", pid);
		if(-1 != pid) {
			char cmd[1024] = {'\0'};
			sprintf(cmd, "kill -s HUP %d", pid);
			SystemComandExecuteWithRoot(cmd);

			sprintf(cmd, "rm %s", DrPPPID);
			SystemComandExecuteWithRoot(cmd);
		}
		fclose(file);
	}

	sleep(2);
//	if(!StatusPPPoE()) {
		// 注销成功, 停止DrPPPoE插件协议
		showLog("jni.LogoutPPOE", "PPPoE注销成功, 停止DrPPPoE插件协议");
		g_DrppoePlugin.StopDrPPPoEPlugin();
//	}

	return iCode;
}
示例#10
0
int DrUdpSocket::SendData(string ip, unsigned int iPort, char* pBuffer, unsigned int uiSendLen) {
	int iRet = -1, iRetS = -1, iSendedLen = 0;
	int iOrgLen = uiSendLen;
	fd_set wset;

	struct sockaddr_in remoteAddr;
	bzero(&remoteAddr, sizeof(remoteAddr));
	socklen_t iremoteAddrLen = sizeof(struct sockaddr_in);
	remoteAddr.sin_family = AF_INET;
	inet_aton(ip.c_str(), &remoteAddr.sin_addr);
	remoteAddr.sin_port = htons(iPort);

	string log = Arithmetic::AsciiToHexWithSep(pBuffer, uiSendLen);
	showLog("jni.DrUdpSocket::SendData", "准备向(%s:%d)发送数据,Hex编码后:\n%s(%d)", ip.c_str(), iPort, log.c_str(), uiSendLen);

	socket_type sendSocket;
	if(m_Socket > 0) {
		sendSocket = m_Socket;
	}
	else {
		if((sendSocket = socket(AF_INET, SOCK_DGRAM, 0/*IPPROTO_UDP*/)) < 0){
			// create socket error;
			showLog("Jni.DrUDPSocket.SendData", "create socket error");
		    return iRet;
		}
	}
	iRet = sendto(sendSocket, pBuffer, uiSendLen, 0, (struct sockaddr *)&remoteAddr, iremoteAddrLen);

	showLog("jni.DrUdpSocket::SendData", "成功发送字节数:(%d)", iRet);

//	int iLeft;
//	iRet = ioctl(m_Socket, SIOCOUTQ, &iLeft);
//	if(iRet >= 0) {
//		showLog("Jni.DrUDPSocket.SendData", "缓冲区剩余包:%d", iLeft);
//	}

	return iRet;
}
int DrHttpClient::singleHttpGet(string strUrl, int iThreadId){
	showLog("Jni.DrHttpClient.singleHttpGet","strUrl:%s", strUrl.c_str());
	tcpSocket tSocket;
	//tcpSocket *ptSocket = new tcpSocket();
	int iRet = -1;
	int iHttpCode = 0, iContentLen = 0, iPort = 80;
	string strNewUrl="", strPort="", strParam="", strUrlWithPort;
	string retContent = "";
	char cHttpBodyBuffer[DrHttpClient_BUFFER_64K];
	bzero(cHttpBodyBuffer, sizeof(cHttpBodyBuffer));
	if(-1 == getUrlPort(strUrl, strNewUrl, strPort, strParam)){
		showLog("Jni.DrHttpClient.httpGet", "getUrlPort:error");
		return iRet;
	}
	strUrlWithPort = strNewUrl;
	if("" != strPort){
		strUrlWithPort += ":" + strPort;
		iPort = atoi(strPort.c_str());
	}
	if("" == strParam){
		strParam = "/";
	}
	showLog("Jni.DrHttpClient.httpGet", "strNewUrl:%s iPort:%i strParam:%s", strNewUrl.c_str(), iPort, strParam.c_str());
	if (tSocket.Connect(strNewUrl,iPort) == 1) {
		sprintf(cHttpBodyBuffer, DrHttpClient_GET, strParam.c_str(), \
				DrHttpClient_HTTP_LANGUALE_CN, \
				strUrlWithPort.c_str());
		showLog("Jni.DrHttpClient.httpGet", "cHttpBodyBuffer:\r\n%s", cHttpBodyBuffer);
#ifdef PRINT_JNI_LOG
		if(mIDrHttpClientCallback) {
			char logBuffer[DrHttpClient_BUFFER_1K + strUrl.length() + 1024];
			memset(logBuffer, '\0', DrHttpClient_BUFFER_1K + strUrl.length() + 1024);
			sprintf(logBuffer, "%s:(socket:%d thread:%d)\r\n%s\r\n%s", "Jni.DrHttpClient.httpGet", tSocket.getSocketId(), iThreadId, strUrl.c_str(), LOG_SEP);
			mIDrHttpClientCallback->onWriteLog((unsigned char*)logBuffer, strlen(logBuffer), iThreadId);
		}
#endif
		if (tSocket.SendData(cHttpBodyBuffer, strlen(cHttpBodyBuffer)) == strlen(cHttpBodyBuffer)) {
			bzero(cHttpBodyBuffer, sizeof(cHttpBodyBuffer));
			//if (httpHandle(&tSocket, iHttpCode, iContentLen, (char*)cHttpBodyBuffer) == 1) {
			if (httpHandle(&tSocket, iHttpCode, iContentLen, iThreadId) != -1) {
			    showLog("Jni.DrHttpClient.httpGet", "iThreadId:%d", iThreadId);
				iRet = 1;
			}
		}
		else{
			if(mIDrHttpClientCallback)
				mIDrHttpClientCallback->onError((unsigned char*)HTTP_SEND_REQUEST_ERROR, strlen(HTTP_SEND_REQUEST_ERROR), iThreadId, true);
		}
	}
	else{
		showLog("Jni.DrHttpClient.httpGet", "httpGet_Connect Fail:%s", strUrl.c_str());
		if(mIDrHttpClientCallback)
			mIDrHttpClientCallback->onError((unsigned char*)HTTP_CONNECTION_ERROR, strlen(HTTP_CONNECTION_ERROR), iThreadId, true);
	}
	tSocket.Close();

	return iRet;
}
示例#12
0
void MQLEdit::parseQuery()
{
  _sql->_log->clear();
  _log->_log->clear();
  _log->_log->append(tr("---- Parsing Query ----\n"));
  MetaSQLQuery mql(_text->toPlainText());
  _log->_log->append(mql.parseLog());
  if(mql.isValid()) {
      _log->_log->append(tr("Query parsed."));
  } else {
      _log->_log->append(tr("ERROR: Invalid query!"));
  }
  showLog();
}
示例#13
0
void Settings::showEvent(QShowEvent *showEvent)
{
    Q_UNUSED(showEvent);

    ui->autoconnectCheckBox->setChecked(autoconnect());
    ui->autoanswerCheckBox->setChecked(autoanswer());
    ui->showLogCheckBox->setChecked(showLog());

    ui->hotAnswer1LineEdit->setText(hotAnswer(1));
    ui->hotAnswer2LineEdit->setText(hotAnswer(2));
    ui->hotAnswer3LineEdit->setText(hotAnswer(3));
    ui->hotAnswer4LineEdit->setText(hotAnswer(4));
    ui->hotAnswer5LineEdit->setText(hotAnswer(5));
}
示例#14
0
void loadShaders(void)
{
	const char *vs_source = readFile("shader_vertex.glsl");
	const char *fs_source = readFile("shader_fragment_final.glsl");
	shader = 0;
	GLuint shader_handle = 0;

	if (vs_source == NULL || fs_source == NULL)
	{
		fprintf(stderr, "Could not load shaders.\n");
		exit(EXIT_FAILURE);
	}

	shader = glCreateProgram();

	shader_handle = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(shader_handle, 1, &vs_source, NULL);
	glCompileShader(shader_handle);
	showLog(shader_handle, "Vertex shader:");
	glAttachShader(shader, shader_handle);

	shader_handle = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(shader_handle, 1, &fs_source, NULL);
	glCompileShader(shader_handle);
	showLog(shader_handle, "Fragment shader:");
	glAttachShader(shader, shader_handle);

	glLinkProgram(shader);

	handle_rot = glGetUniformLocation(shader, "rot");
	handle_pos = glGetUniformLocation(shader, "pos");
	handle_eyedist = glGetUniformLocation(shader, "eyedist");
	handle_stepsize = glGetUniformLocation(shader, "stepsize");
	handle_accuracy = glGetUniformLocation(shader, "accuracy");
	handle_user_params0 = glGetUniformLocation(shader, "user_params0");
	handle_user_params1 = glGetUniformLocation(shader, "user_params1");
}
示例#15
0
void MQLEdit::execQuery()
{
    if(!_loggedIn) {
	QMessageBox::warning(this, tr("Not Connected"),
          tr("You must be connected to a database in order to execute a query."));
	return;
    }

    _results->_table->setRowCount(0);
    _results->_table->setColumnCount(0);
    
    _sql->_log->clear();
    _log->_log->clear();
    _log->_log->append(tr("---- Parsing Query ----\n"));
    MetaSQLQuery mql(_text->toPlainText());
    _log->_log->append(mql.parseLog());
    if(mql.isValid()) {
	_log->_log->append(tr("Query parsed."));
	_log->_log->append(tr("---- Executing Query ----"));
	ParameterList plist = _pEdit->getParameterList();
	XSqlQuery qry = mql.toQuery(plist);
        _sql->_log->append(qry.executedQuery());
	if(qry.isActive()) {
            QSqlRecord rec = qry.record();
	    int ncols = rec.count();
            _results->_table->setColumnCount(ncols);
            int c;
            for(c = 0; c < ncols; c++) {
                _results->_table->setHorizontalHeaderItem(c, new QTableWidgetItem(rec.fieldName(c)));
            }
            int nrows = 0;
            while(qry.next()) {
                _results->_table->setRowCount(nrows + 1);
                for(c = 0; c < ncols; c++) {
                    _results->_table->setItem(nrows, c, new QTableWidgetItem(qry.value(c).toString()));
                }
                nrows++;
            }
            showResults();
	} else {
	    _log->_log->append(tr("Failed to execute query."));
	    QSqlError err = qry.lastError();
	    _log->_log->append(err.text());
	}
    } else {
	_log->_log->append(tr("ERROR: Invalid query!"));
	showLog();
    }   
}
示例#16
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    lastcnf = new config();
    crackingProcess = new QProcess(this);
    initializeHashType(ui->comboBox);
    initializeOutputType(ui->comboBox_2);
    loadWordList();
    ui->txtSalt->setDisabled(true);
	ui->txtLog->installEventFilter(this);
	//connect(ui->txtLog,SIGNAL(keyPressEvent()),this,SLOT(handleKeyPress()));
    connect(ui->btnclipboard,SIGNAL(clicked()),this,SLOT(handleClipboardHash()));
    connect(ui->btnBrowseInput,SIGNAL(clicked()),this,SLOT(handleOpenInput()));
    connect(ui->btnBrowseOutput,SIGNAL(clicked()),this,SLOT(handleOpenOutput()));
    connect(crackingProcess,SIGNAL(started()),this,SLOT(processStarted()));
    connect(crackingProcess,SIGNAL(finished(int, QProcess::ExitStatus)),this,SLOT(processDone(int,QProcess::ExitStatus)));
    connect(crackingProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(showLog()));
    connect(ui->btnAction,SIGNAL(clicked()),this,SLOT(startCracking()));
    connect(ui->btnCreate,SIGNAL(clicked()),this,SLOT(createHashFile()));
    connect(ui->btnAdd,SIGNAL(clicked()),this,SLOT(addWordList()));
    connect(ui->btnRemove,SIGNAL(clicked()),this,SLOT(deleteWordList()));
    connect(ui->btnBrowseSalt,SIGNAL(clicked()),this,SLOT(handleOpenSalt()));
    connect(ui->btnBrowseProg,SIGNAL(clicked()),this,SLOT(handleOpenProg()));
    connect(ui->btnUp,SIGNAL(clicked()),this,SLOT(moveWordUp()));
    connect(ui->btnDown,SIGNAL(clicked()),this,SLOT(moveWordDown()));
    ui->txtInputFile->setText(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation) + "/input.txt");
    ui->txtOutputFile->setText(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation) + "/output.txt");
#ifdef Q_OS_WIN32
    ui->txtProg->setText("hashcat-cli32.exe");
#endif
#ifdef Q_OS_DARWIN
    ui->txtProg->setText("/usr/local/bin/hashcat");
#endif
    if(lastcnf->lasthashpath != "")
        ui->txtInputFile->setText(lastcnf->lasthashpath);
    if(lastcnf->hashcatpath != "")
        ui->txtProg->setText(lastcnf->hashcatpath);
    if(lastcnf->separator != "")
        ui->sep->setText(lastcnf->separator);
    ui->tab_3->setFocus();
    createActionText("idle");
    if(lastcnf->lastdir != "")
        lastdir = lastcnf->lastdir;
    else
        lastdir = QDir::currentPath();
}
void
DlgRuleEditorFilterActionPage::update(Subject *subject)
{
    SfsDefaultFilterPolicy	*sfs;

    if (subject == filterPolicy_) {
        /* This is our policy. */
        showAction();
        showLog();
    }
    if ((subject == defaultPathPicker) &&
            (dynamic_cast<SfsDefaultFilterPolicy*>(filterPolicy_))) {
        sfs = dynamic_cast<SfsDefaultFilterPolicy*>(filterPolicy_);
        sfs->setPath(defaultPathPicker->getFileName());
    }
}
int DrHttpClient::httpGet(string strUrl){
	int iThreadId = -1;
	for(int i=0; i<MAXTHREADCOUNT; i++){
		if(m_ThreadArray[i]){
			if(!m_ThreadArray[i]->isRunning()){
				showLog("Jni.DrHttpClient.httpGet", "m_ThreadArray[%d] use", i);
				HTTPCLIENTTHREADDATA thdata;
				thdata._url = strUrl;
				m_ThreadArray[i]->setParams(this, HTTPGET, thdata);
				return m_ThreadArray[i]->start();
				//return m_ThreadArray[i]->getThreadId();
			}
		}
	}
	return iThreadId;
}
示例#19
0
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    setWindowTitle(tr("Mupen64Plus-Qt"));
    setWindowIcon(QIcon(":/images/mupen64plus.png"));

    autoloadSettings();

    emulation = new EmulatorHandler(this);

    connect(emulation, SIGNAL(started()), this, SLOT(disableButtons()));
    connect(emulation, SIGNAL(finished()), this, SLOT(enableButtons()));
    connect(emulation, SIGNAL(showLog()), this, SLOT(openLog()));


    romCollection = new RomCollection(QStringList() << "*.z64" << "*.v64" << "*.n64" << "*.zip",
                                      QStringList() << SETTINGS.value("Paths/roms","").toString().split("|"),
                                      this);

    connect(romCollection, SIGNAL(updateStarted(bool)), this, SLOT(disableViews(bool)));
    connect(romCollection, SIGNAL(romAdded(Rom*, int)), this, SLOT(addToView(Rom*, int)));
    connect(romCollection, SIGNAL(updateEnded(int, bool)), this, SLOT(enableViews(int, bool)));


    mainWidget = new QWidget(this);
    setCentralWidget(mainWidget);
    setGeometry(QRect(SETTINGS.value("Geometry/windowx", 0).toInt(),
                      SETTINGS.value("Geometry/windowy", 0).toInt(),
                      SETTINGS.value("Geometry/width", 900).toInt(),
                      SETTINGS.value("Geometry/height", 600).toInt()));

    createMenu();
    createRomView();

    mainLayout = new QVBoxLayout(mainWidget);
    mainLayout->setMenuBar(menuBar);

    mainLayout->addWidget(emptyView);
    mainLayout->addWidget(tableView);
    mainLayout->addWidget(gridView);
    mainLayout->addWidget(listView);

    mainLayout->setMargin(0);

    mainWidget->setLayout(mainLayout);
    mainWidget->setMinimumSize(300, 200);
}
示例#20
0
bool DrSocket::IsTimeout(unsigned int uiStart, unsigned int uiTimeout)
{
	showLog("Jni.DrSocket.IsTimeout", "uiStart:%d uiTimeout:%d", uiStart, uiTimeout);
	unsigned int uiCurr = GetTick();
	unsigned int uiDiff;

	if (uiTimeout == 0)
		return false;
	if (uiCurr >= uiStart) {
		uiDiff = uiCurr - uiStart;
	}else{
		uiDiff = (0xFFFFFFFF - uiStart) + uiCurr;
	}
	if(uiDiff >= uiTimeout){
		return true;
	}
	return false;
}
示例#21
0
void regDialog::acceptSP()
{
    QString spInfo1 = client->readAll();
    QByteArray b;
    b = spInfo1.toLatin1();

    //len_cipher2 = (spInfo1.length() / 16 + 1) * 16;
    len_cipher2 = 0;
    memset(cipher2, '\0', 256);
    len_cipher2 = spInfo1.length();
    qDebug()<<"[acceptSP]: "<<len_cipher2;


//    cipher2 = (char *)malloc(len_cipher2 * sizeof(char));
//    memset(cipher2, '\0', len_cipher2);

//    strcpy(cipher2, b.data());
    memcpy(cipher2, b.data(), len_cipher2);
    qDebug()<<"[acceptSP]: "<<cipher2;

    if(!strcmp(cipher2, "existed"))
    {
        QMessageBox::about(this, "Attention!", "Username Existed!");
    }else if(!strcmp(cipher2, "succ"))
    {
        QMessageBox::about(this, "Attention!", "Registed Success!");
        client->close();

        emit(showLog());
        this->hide();
    }else {
        DecryptK0();
        Depack();
        if(Verify())
        {
            caly0();
            Enpack("03");
            Encrypt1K0();
            SendAck();
        }
    }

}
示例#22
0
void PlanExecutor::repairFinished(KJob *pJob) {
	endSleepInhibit();
	discardRepairNotification();
	mRepairNotification = new KNotification(QStringLiteral("RepairCompleted"), KNotification::Persistent);
	mRepairNotification->setTitle(xi18nc("@title:window", "Repair Completed"));
	mRepairNotification->setText(pJob->errorText());
	QStringList lAnswers;
	lAnswers << xi18nc("@action:button", "Show log file");
	mRepairNotification->setActions(lAnswers);
	connect(mRepairNotification, SIGNAL(action1Activated()), SLOT(showLog()));
	connect(mRepairNotification, SIGNAL(closed()), SLOT(discardRepairNotification()));
	connect(mRepairNotification, SIGNAL(ignored()), SLOT(discardRepairNotification()));
	mRepairNotification->sendEvent();

	if(mState == REPAIRING) { //only restore if nothing has changed during the run
		mState = mLastState;
	}
	emit stateChanged();
}
/*
 * Class:     com_drcom_drauth_DrAuthJni
 * Method:    ReleaseDrSniffer
 * Signature: (Ljava/lang/String;)Z
 */
JNIEXPORT jboolean JNICALL Java_com_drcom_drauth_DrAuthJni_ReleaseDrSniffer
	(JNIEnv *env, jobject thiz, jstring sdcardPath)  {
	jboolean jbFlag = false;

	const char *pPath = env->GetStringUTFChars(sdcardPath, 0);
	string filePath = pPath;
	env->ReleaseStringUTFChars(sdcardPath, pPath);

	// 安装DrSniffer
	string releaseFile = ReleaseDrSniffer(filePath);
	if(releaseFile.length() > 0) {
		jbFlag = RootExecutableFile(releaseFile.c_str());
		if(jbFlag) {
			showLog("jni.DrAuthJni.ReleaseDrSniffer", "安装DrSniffer成功!");
		}
	}

	return jbFlag;
}
示例#24
0
MQLEdit::MQLEdit(QWidget* parent, Qt::WindowFlags fl)
    : QMainWindow(parent, fl)
{
    setupUi(this);

    (void)statusBar();

    // signals and slots connections
    connect(fileNewAction, SIGNAL(activated()), this, SLOT(fileNew()));
    connect(fileOpenAction, SIGNAL(activated()), this, SLOT(fileOpen()));
    connect(fileSaveAction, SIGNAL(activated()), this, SLOT(fileSave()));
    connect(fileSaveAsAction, SIGNAL(activated()), this, SLOT(fileSaveAs()));
    connect(filePrintAction, SIGNAL(activated()), this, SLOT(filePrint()));
    connect(fileExitAction, SIGNAL(activated()), this, SLOT(fileExit()));
    connect(editFindAction, SIGNAL(activated()), this, SLOT(editFind()));
    connect(helpIndexAction, SIGNAL(activated()), this, SLOT(helpIndex()));
    connect(helpContentsAction, SIGNAL(activated()), this, SLOT(helpContents()));
    connect(helpAboutAction, SIGNAL(activated()), this, SLOT(helpAbout()));
    connect(fileDatabaseConnectAction, SIGNAL(activated()), this, SLOT(fileDatabaseConnect()));
    connect(fileDatabaseDisconnectAction, SIGNAL(activated()), this, SLOT(fileDatabaseDisconnect()));
    connect(viewParameter_ListAction, SIGNAL(activated()), this, SLOT(showParamList()));
    connect(toolsParse_QueryAction, SIGNAL(activated()), this, SLOT(parseQuery()));
    connect(toolsExecute_QueryAction, SIGNAL(activated()), this, SLOT(execQuery()));
    connect(viewLog_OutputAction, SIGNAL(activated()), this, SLOT(showLog()));
    connect(viewResultsAction, SIGNAL(activated()), this, SLOT(showResults()));
    connect(viewExecuted_SQLAction, SIGNAL(activated()), this, SLOT(showExecutedSQL()));

    QSqlDatabase db = QSqlDatabase();
    if(_loggedIn && db.isValid() && db.isOpen()) {
	_loggedIn = true;
    } else {
	_loggedIn = false;
    }
    
    fileDatabaseConnectAction->setEnabled(!_loggedIn);
    fileDatabaseDisconnectAction->setEnabled(_loggedIn);
    
    _pEdit = new ParameterEdit(this);
    _log = new LogOutput(this);
    _sql = new LogOutput(this);
    _results = new ResultsOutput(this);
}
示例#25
0
void Runner::onRunFinished(bool success, const QString& errorMsg) {

    if (!success) {

        showErrorMsg(errorMsg);
    }

    showLog();

    bool pointerToFolderOK = false;

    finalProjectFolder = dirToShow(pointerToFolderOK); // Side effect: always deletes the pointer

    if (pointerToFolderOK && opts().getConvertToPdf()) {

        converter->run(finalProjectFolder);  // calls onConversionFinished in the end
    }
    else {

        onConcatFinished(success && pointerToFolderOK);
    }
}
示例#26
0
void PlanExecutor::notifyBackupFailed(KJob *pFailedJob) {
	discardFailNotification();
	mFailNotification = new KNotification(QStringLiteral("BackupFailed"), KNotification::Persistent);
	mFailNotification->setTitle(xi18nc("@title:window", "Saving of Backup Failed"));
	mFailNotification->setText(pFailedJob->errorText());

	QStringList lAnswers;
	if(pFailedJob->error() == BackupJob::ErrorWithLog) {
		lAnswers << xi18nc("@action:button", "Show log file");
		connect(mFailNotification, SIGNAL(action1Activated()), SLOT(showLog()));
	} else if(pFailedJob->error() == BackupJob::ErrorSuggestRepair) {
		lAnswers << xi18nc("@action:button", "Yes");
		lAnswers << xi18nc("@action:button", "No");
		connect(mFailNotification, SIGNAL(action1Activated()), SLOT(startRepairJob()));
	}
	mFailNotification->setActions(lAnswers);

	connect(mFailNotification, SIGNAL(action2Activated()), SLOT(discardFailNotification()));
	connect(mFailNotification, SIGNAL(closed()), SLOT(discardFailNotification()));
	connect(mFailNotification, SIGNAL(ignored()), SLOT(discardFailNotification()));
	mFailNotification->sendEvent();
}
示例#27
0
BitSplit::BitSplit()
{
    fontDb.addApplicationFont(":/fonts/OpenSans-Light.ttf");
    fontDb.addApplicationFont(":/fonts/OpenSans-Regular.ttf");
    exit = true;
    blockToggle = false;
    searchExisting = false;

    /* Timer setup*/
    guiUpdater  = new QTimer( this );
    guiUpdater->setInterval(25);

    syncAnimator  = new QTimer( this );
    syncAnimator->setInterval(75);

    /* Interface setup */
    fileInterface.debug = false;
    fileInterface.copyDirection = BothDirections;
    actionCreator.fileInterface = &fileInterface;
    smartMatch.fileInterface = &fileInterface;
    actionHandler.fileInterface = &fileInterface;
    updater.fileInterface = &fileInterface;

    /* Set up icons */
    remove  = new QIcon(":images/general/remove.png");

    done    = new QIcon(":images/table/tick.png");
    errorIcon   = new QIcon(":images/table/error.png");
    skip    = new QIcon(":images/table/skip.png");

    sync1   = new QIcon(":images/table/sync1.png");
    syncAnimation.append(sync1);
    sync2   = new QIcon(":images/table/sync2.png");
    syncAnimation.append(sync2);
    sync3   = new QIcon(":images/table/sync3.png");
    syncAnimation.append(sync3);
    sync4   = new QIcon(":images/table/sync4.png");
    syncAnimation.append(sync4);
    sync5   = new QIcon(":images/table/sync5.png");
    syncAnimation.append(sync5);
    sync6   = new QIcon(":images/table/sync6.png");
    syncAnimation.append(sync6);
    sync7   = new QIcon(":images/table/sync7.png");
    syncAnimation.append(sync7);
    sync8   = new QIcon(":images/table/sync8.png");
    syncAnimation.append(sync8);


    ui.setupUi( this );
    ui.runButton->setDisabled(true);

    /* Connect buttons to their dialogs */
    connect(ui.editSettingsButton,  SIGNAL(clicked()),  this,   SLOT(editSettings()));
    connect(ui.newProfileButton,    SIGNAL(clicked()),  this,   SLOT(newProfile()));


    /* Log Connections*/
    connect(ui.actionView_Log,  SIGNAL(triggered()),        this,       SLOT(showLog()));
    connect(ui.exitLog,         SIGNAL(clicked()),          this,       SLOT(showMain()));
    connect(&fileInterface,     SIGNAL(updateLog(QString)), ui.log,     SLOT(append(QString)));
    connect(ui.errorViewLog,    SIGNAL(clicked()),          this,       SLOT(showLog()));

    /* Top Bar connections*/
    connect(&fileInterface, SIGNAL(matchComplete()),            this,               SLOT(matchComplete()));
    connect(&fileInterface, SIGNAL(updateSingle(QString)),      ui.topBarSingle,    SLOT(setText(QString)));
    connect(&fileInterface, SIGNAL(updateTopMP(QString)),       ui.mp_top,          SLOT(setText(QString)));
    connect(&fileInterface, SIGNAL(updateBottomMP(QString)),    ui.mp_bottom,       SLOT(setText(QString)));
    connect(&fileInterface, SIGNAL(updateOperationMP(QString)), ui.mp_operation,    SLOT(setText(QString)));
    connect(guiUpdater,     SIGNAL(timeout()),                  &smartMatch,        SLOT(updateGuiLabels()));
    connect(&smartMatch,    SIGNAL(startTime()),                guiUpdater,         SLOT(start()));
    connect(&smartMatch,    SIGNAL(stopTime()),                 guiUpdater,         SLOT(stop()));
    connect(&smartMatch,    SIGNAL(setTopBarLineStack(int)),    this,               SLOT(setTopBarLineStack(int)));

    /* Unmatched files tree Connections */
    connect(ui.unmatchedTree,   SIGNAL(itemChanged(QTreeWidgetItem*,int)),  this,   SLOT(toggleTree(QTreeWidgetItem*,int)));
    connect(&fileInterface,     SIGNAL(updateFileTree(bool, QTreeWidgetItem *)), this, SLOT(insertTreeItem(bool, QTreeWidgetItem *)));
    connect(&fileInterface,     SIGNAL(pop()),                              this,   SLOT(popParent()));
    connect(&fileInterface,     SIGNAL(expandTree()), this, SLOT(expandTree()));

    /* Matched Table Connections */
    connect(&fileInterface, SIGNAL(insertMatchTableRow(QList<QTableWidgetItem*>*)), this, SLOT(insertMatchTableRow(QList<QTableWidgetItem*>*)));

    /* Action Table Connections*/
    connect(&fileInterface, SIGNAL(insertActionTableRow(QList<QTableWidgetItem*>*)), this, SLOT(insertActionTableRow(QList<QTableWidgetItem*>*)));

    /* Error connections */
    connect(&smartMatch,    SIGNAL(operationFailed()),  this, SLOT(error()));
    connect(&actionCreator,    SIGNAL(operationFailed()),  this, SLOT(error()));
    connect(&actionHandler,     SIGNAL(exception()), this, SLOT(error()));

    /* Developer Test Connections */
    connect(ui.actionDeveloper_Test, SIGNAL(triggered()), this, SLOT(runDeveloperTest()));
    connect(&smartMatch, SIGNAL(stopTestTime()), this, SLOT(endTimer()));

    /* Action Handler Connections */
    connect(&actionHandler, SIGNAL(updateProgress(int)),            ui.progressBar,         SLOT(setValue(int)));
    connect(&actionHandler, SIGNAL(updateActionLabel(QString)),     ui.actionLabel,         SLOT(setText(QString)));
    connect(&actionHandler, SIGNAL(updateSpeedLabel(QString)),      ui.speedLabel,          SLOT(setText(QString)));
    connect(&actionHandler, SIGNAL(updatePercentageLabel(QString)), ui.mp_busyIndicator,    SLOT(setText(QString)));
    connect(&actionHandler, SIGNAL(setComplete(int)),               this,                   SLOT(setDone(int)));
    connect(&actionHandler, SIGNAL(setSkipped(int)),                this,                   SLOT(setSkip(int)));
    connect(&actionHandler, SIGNAL(setError(int)),                  this,                   SLOT(setError(int)));
    connect(&actionHandler, SIGNAL(setInProgress(int)),             this,                   SLOT(setSync(int)));

    /* Updater Connections */
    connect(&updater,       SIGNAL(complete()),     this,   SLOT(updaterComplete()));

    /* General Connections & Button Stack Connections */
    connect(syncAnimator,           SIGNAL(timeout()),  this,   SLOT(showSync()));
    connect(ui.finishEditButton,    SIGNAL(clicked()),  this,   SLOT(createActions()));
    connect(&actionCreator,         SIGNAL(complete()), this,   SLOT(actionsComplete()));
    connect(ui.runButton,           SIGNAL(clicked()),  this,   SLOT(runActionHandler()));
    connect(ui.searchButton,        SIGNAL(clicked()),  this,   SLOT(searchForSync()));
    connect(&actionHandler,         SIGNAL(complete()), this,   SLOT(actionHandlerComplete()));

    /* General Setup*/
    frame = 0;
    currentAction = -1;
    actionHandler.table = ui.actionsTable;
    ui.mp_ProfileLabel->fontMetrics().width(ui.mp_ProfileLabel->text());
    createTrayIcon();
    setupTable();
    fileInterface.loadDatabase();
    recentProfiles = fileInterface.loadRecentProfiles();
    if(recentProfiles.size() > 0)
        showRecentProfiles();

}
示例#28
0
MQLEdit::MQLEdit(QWidget* parent, Qt::WindowFlags fl)
    : QWidget(parent, fl)
{
  setupUi(this);

  if (OpenRPT::name.isEmpty())
    OpenRPT::name = tr("MetaSQL Editor");

  _mqlSelector = 0;
  _document = _text->document();
  _document->setDefaultFont(QFont("Courier"));

  connect(_document,     SIGNAL(modificationChanged(bool)), this, SLOT(setWindowModified(bool)));
  connect(editFindAction,              SIGNAL(triggered()), this, SLOT(editFind()));
  connect(fileDatabaseConnectAction,   SIGNAL(triggered()), this, SLOT(fileDatabaseConnect()));
  connect(fileDatabaseDisconnectAction,SIGNAL(triggered()), this, SLOT(fileDatabaseDisconnect()));
  connect(fileDatabaseOpenAction,      SIGNAL(triggered()), this, SLOT(fileDatabaseOpen()));
  connect(fileDatabaseSaveAsAction,    SIGNAL(triggered()), this, SLOT(fileDatabaseSaveAs()));
  connect(fileExitAction,              SIGNAL(triggered()), this, SLOT(fileExit()));
  connect(fileNewAction,               SIGNAL(triggered()), this, SLOT(fileNew()));
  connect(fileOpenAction,              SIGNAL(triggered()), this, SLOT(fileOpen()));
  connect(filePrintAction,             SIGNAL(triggered()), this, SLOT(filePrint()));
  connect(fileSaveAction,              SIGNAL(triggered()), this, SLOT(fileSave()));
  connect(fileSaveAsAction,            SIGNAL(triggered()), this, SLOT(fileSaveAs()));
  connect(helpAboutAction,             SIGNAL(triggered()), this, SLOT(helpAbout()));
  connect(helpContentsAction,          SIGNAL(triggered()), this, SLOT(helpContents()));
  connect(helpIndexAction,             SIGNAL(triggered()), this, SLOT(helpIndex()));
  connect(searchForParametersAction,   SIGNAL(triggered()), this, SLOT(populateParameterEdit()));
  connect(toolsExecute_QueryAction,    SIGNAL(triggered()), this, SLOT(execQuery()));
  connect(toolsParse_QueryAction,      SIGNAL(triggered()), this, SLOT(parseQuery()));
  connect(viewExecuted_SQLAction,      SIGNAL(triggered()), this, SLOT(showExecutedSQL()));
  connect(viewLog_OutputAction,        SIGNAL(triggered()), this, SLOT(showLog()));
  connect(viewParameter_ListAction,    SIGNAL(triggered()), this, SLOT(showParamList()));
  connect(viewResultsAction,           SIGNAL(triggered()), this, SLOT(showResults()));

  QSqlDatabase db = QSqlDatabase().database();
  if(db.isValid() && db.isOpen())
    OpenRPT::loggedIn = true;
  else
  {
    OpenRPT::loggedIn = false;
    db = QSqlDatabase();
  }

  if (parent) // then must be embedded
  {
    if (DEBUG)
      qDebug("MQLEdit::MQLEdit(%p) OpenRPT::loggedIn = %d",
             parent, OpenRPT::loggedIn);
    fileDatabaseConnectAction->setVisible(! OpenRPT::loggedIn);
    fileDatabaseDisconnectAction->setVisible(! OpenRPT::loggedIn);

    fileExitAction->setText(tr("Close"));

    QToolBar *menuproxy = new QToolBar(this);
    menuproxy->setObjectName("menuproxy");
    menuproxy->setOrientation(Qt::Horizontal);
    verticalLayout->insertWidget(0, menuproxy);

    menuproxy->addAction(fileMenu->menuAction());
    menuproxy->addAction(editMenu->menuAction());
    menuproxy->addAction(ViewMenu->menuAction());
    menuproxy->addAction(ToolsMenu->menuAction());
    menuproxy->addAction(helpMenu->menuAction());
  }
  
  fileDatabaseConnectAction->setEnabled(!OpenRPT::loggedIn);
  fileDatabaseDisconnectAction->setEnabled(OpenRPT::loggedIn);
  fileDatabaseOpenAction->setEnabled(OpenRPT::loggedIn);
  fileDatabaseSaveAsAction->setEnabled(OpenRPT::loggedIn);
  
  _pEdit   = new ParameterEdit(this, Qt::Window);
  _log     = new LogOutput(this);
  _sql     = new LogOutput(this);
  _results = new ResultsOutput(this);

  _highlighter = new MetaSQLHighlighter(_document);

  clear();

  setDestType(MQLUnknown);
}
示例#29
0
int DrUdpSocket::Bind(unsigned int iPort, string ip, bool bBlocking) {
	int iRet = -1;
	if((m_Socket = socket(AF_INET, SOCK_DGRAM, 0/*IPPROTO_UDP*/)) < 0){
		// create socket error;
		showLog("Jni.DrUDPSocket.Bind", "create socket error");
	    return false;
	}

	int iBuffer;
	iRet = getsockopt(m_Socket, SOL_SOCKET, SO_RCVBUF, &iBuffer, NULL);
	if(iRet >= 0) {
		showLog("Jni.DrUDPSocket.Bind", "当前接收缓冲区大小:%d", iBuffer);
	}

	iRet = getsockopt(m_Socket, SOL_SOCKET, SO_SNDBUF, &iBuffer, NULL);
	if(iRet >= 0) {
		showLog("Jni.DrUDPSocket.Bind", "当前发送缓冲区大小:%d", iBuffer);
	}
//
//	iRet = getsockopt(m_Socket, SOL_SOCKET, SO_RCVBUF, &i, &iLen);
//	if(iRet >= 0) {
//		showLog("Jni.DrUDPSocket.Bind", "getsockopt SOL_SOCKET SO_RCVBUF:%d iLen:%d", i, iLen);
//	}
//
//	int size = 8;
//	iRet = setsockopt(m_Socket, SOL_SOCKET, SO_SNDBUF,  &size, sizeof(int));
//	if(iRet < 0) {
//		showLog("Jni.DrUDPSocket.Bind", "setsockopt SOL_SOCKET SO_SNDBUF error");
//		return false;
//	}
//
//	iRet = setsockopt(m_Socket, SOL_SOCKET, SO_RCVBUF,  &size, sizeof(int));
//	if(iRet < 0) {
//		showLog("Jni.DrUDPSocket.Bind", "setsockopt SOL_SOCKET SO_RCVBUF error");
//		return false;
//	}

	m_bBlocking = bBlocking;
	if(m_bBlocking) {
		// set to blocking
		int iFlag = 1;
		if ((iFlag = fcntl(m_Socket, F_GETFL, 0)) == -1) {
			showLog("Jni.DrUDPSocket.Bind", "fcntl F_GETFL O_NONBLOCK socket error");
			return iRet;
		}
		if (fcntl(m_Socket, F_SETFL, iFlag & ~O_NONBLOCK) == -1) {
			showLog("Jni.DrUDPSocket.Bind", "fcntl F_SETFL iFlag & ~O_NONBLOCK socket error");
			return iRet;
		}
		showLog("Jni.DrUDPSocket.Bind", "set socket to blocking");
	}
	else {
		// set to nonblocking
		int iFlag = 1;
		if ((iFlag = fcntl(m_Socket, F_GETFL, 0)) == -1) {
			showLog("Jni.DrUDPSocket.RecvData", "fcntl F_GETFL O_NONBLOCK socket error");
			return iRet;
		}
		if (fcntl(m_Socket, F_SETFL, iFlag | O_NONBLOCK) == -1) {
			showLog("Jni.DrUDPSocket.RecvData", "fcntl F_SETFL iFlag | O_NONBLOCK socket error");
			return iRet;
		}
		showLog("Jni.DrUDPSocket.Bind", "set socket to nonblocking");
	}

	struct sockaddr_in localAddr;
	bzero(&localAddr, sizeof(localAddr));
	localAddr.sin_family = AF_INET;
	if(ip.length() > 0) {
		inet_aton(ip.c_str(), &localAddr.sin_addr);
	}
	else {
		localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	}

	localAddr.sin_port = htons(iPort);
	if(bind(m_Socket, (struct sockaddr *)&localAddr, sizeof(localAddr)) < 0) {
		// bind socket error
		showLog("Jni.DrUDPSocket.Bind", "bind socket error");
		return false;
	}

	m_iPort = iPort;

	return true;
}
示例#30
0
int DrUdpSocket::RecvData(char* pBuffer, unsigned int uiRecvLen, unsigned int uiTimeout, struct sockaddr_in* remoteAddr) {
	int iRet = -1, iRetS = -1;
	int iOrgLen = uiRecvLen;
	fd_set rset;

	if(-1 == m_Socket) {
		return iRet;
	}

	struct sockaddr_in sendAddr;
	bzero(&sendAddr, sizeof(sendAddr));
	int iSendAddrLen = sizeof(struct sockaddr_in);

	if(NULL != remoteAddr) {
		if(sizeof(*remoteAddr) != iSendAddrLen) {
			return iRet;
		}
	}

	if(m_bBlocking) {
		// blocking recv
		bzero(pBuffer, sizeof(pBuffer));
		iRet = recvfrom(m_Socket, pBuffer, uiRecvLen, 0, (struct sockaddr *)&sendAddr , &iSendAddrLen);
		memcpy((void *)remoteAddr, &sendAddr, iSendAddrLen);

		string ip = DrSocket::IpToString(sendAddr.sin_addr.s_addr);
		int iPort = ntohs(sendAddr.sin_port);
		string log = Arithmetic::AsciiToHexWithSep(pBuffer, iRet);
		showLog("jni.DrUdpSocket::RecvData", "收到来自(%s:%d)访问,成功接收字节数:(%d) Hex编码后:\n%s", ip.c_str(), iPort, iRet, log.c_str());
	}
	else {
		// nonblocking recv
		timeval tout;
		tout.tv_sec = uiTimeout / 1000;
		tout.tv_usec = (uiTimeout % 1000) * 1000;

		FD_ZERO(&rset);
		FD_SET(m_Socket, &rset);
		iRetS = select(m_Socket + 1, &rset, NULL, NULL, &tout);

		if(iRetS > 0) {
			bzero(pBuffer, sizeof(pBuffer));
			iRet = recvfrom(m_Socket, pBuffer, uiRecvLen, 0, (struct sockaddr *)&sendAddr , &iSendAddrLen);
			memcpy((void *)remoteAddr, &sendAddr, iSendAddrLen);

			string ip = DrSocket::IpToString(sendAddr.sin_addr.s_addr);
			int iPort = ntohs(sendAddr.sin_port);
			string log = Arithmetic::AsciiToHexWithSep(pBuffer, iRet);
			showLog("jni.DrUdpSocket::RecvData", "收到来自(%s:%d)访问,成功接收字节数:(%d) Hex编码后:\n%s", ip.c_str(), iPort, iRet, log.c_str());
		}
		else if(iRetS == 0){
			showLog("jni.DrUdpSocket::RecvData", "%d秒超时返回!", uiTimeout / 1000);
		}
		else {
			showLog("jni.DrUdpSocket::RecvData", "socket错误返回!");
		}
	}



	return iRet;
}