Пример #1
0
void MpcImportWindow::createDialogContent()
{
	ui->setupUi(dialog);

	//Signals
	connect(&StelApp::getInstance(), SIGNAL(languageChanged()), this, SLOT(retranslate()));
	connect(ui->closeStelWindow, SIGNAL(clicked()), this, SLOT(close()));
	connect(ui->TitleBar, SIGNAL(movedTo(QPoint)), this, SLOT(handleMovedTo(QPoint)));

	connect(ui->pushButtonAcquire, SIGNAL(clicked()),
	        this, SLOT(acquireObjectData()));
	connect(ui->pushButtonAbortDownload, SIGNAL(clicked()),
	        this, SLOT(abortDownload()));
	connect(ui->pushButtonAdd, SIGNAL(clicked()), this, SLOT(addObjects()));
	connect(ui->pushButtonDiscard, SIGNAL(clicked()),
	        this, SLOT(discardObjects()));

	connect(ui->pushButtonBrowse, SIGNAL(clicked()), this, SLOT(selectFile()));
	connect(ui->comboBoxBookmarks, SIGNAL(currentIndexChanged(QString)),
	        this, SLOT(bookmarkSelected(QString)));

	connect(ui->radioButtonFile, SIGNAL(toggled(bool)),
	        ui->frameFile, SLOT(setVisible(bool)));
	connect(ui->radioButtonURL, SIGNAL(toggled(bool)),
	        ui->frameURL, SLOT(setVisible(bool)));

	connect(ui->radioButtonAsteroids, SIGNAL(toggled(bool)),
	        this, SLOT(switchImportType(bool)));
	connect(ui->radioButtonComets, SIGNAL(toggled(bool)),
	        this, SLOT(switchImportType(bool)));

	connect(ui->pushButtonMarkAll, SIGNAL(clicked()),
	        this, SLOT(markAll()));
	connect(ui->pushButtonMarkNone, SIGNAL(clicked()),
	        this, SLOT(unmarkAll()));

	connect(ui->pushButtonSendQuery, SIGNAL(clicked()),
	        this, SLOT(sendQuery()));
	connect(ui->lineEditQuery, SIGNAL(returnPressed()),
		this, SLOT(sendQuery()));
	connect(ui->pushButtonAbortQuery, SIGNAL(clicked()),
	        this, SLOT(abortQuery()));
	connect(ui->lineEditQuery, SIGNAL(textEdited(QString)),
	        this, SLOT(resetNotFound()));
	//connect(ui->lineEditQuery, SIGNAL(editingFinished()), this, SLOT(sendQuery()));
	connect(countdownTimer, SIGNAL(timeout()), this, SLOT(updateCountdown()));

	QSortFilterProxyModel * filterProxyModel = new QSortFilterProxyModel(this);
	filterProxyModel->setSourceModel(candidateObjectsModel);
	filterProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
	ui->listViewObjects->setModel(filterProxyModel);
	connect(ui->lineEditSearch, SIGNAL(textChanged(const QString&)),
	        filterProxyModel, SLOT(setFilterFixedString(const QString&)));

	loadBookmarks();
	updateTexts();

	resetCountdown();
	resetDialog();
}
Пример #2
0
/*!
    \reimp
*/
void QModemPhoneBook::requestLimits( const QString& store )
{
    QModemPhoneBookCache *cache;

    // Find the cache entry associated with this store.
    cache = findCache( store );

    // If the cache is fully loaded, then emit the result now.
    // If there is a password, then force a re-get of the phone book
    // because the new password may not be the same as the original.
    if ( cache->fullyLoaded && cache->passwd.isEmpty() ) {
        emit limits( store, cache->limits );
        return;
    }

    // We need to requery the extents if the phone book was previously loaded.
    if ( cache->fullyLoaded ) {
        cache->fullyLoaded = false;
        cache->entries.clear();
        cache->limits = QPhoneBookLimits();
        sendQuery( cache );
    }

    // We'll need a signal to be emitted once it is fully loaded.
    cache->needLimitEmit = true;
}
Пример #3
0
void
AsyncCDDBPLookup::doQuery()
{
    sendQuery();

    state_ = WaitingForQueryResponse;
}
Пример #4
0
int db_readDominoTilemap(char* usr, int index, unsigned char* tilemap)
{
	MYSQL_RES* res;
	MYSQL_ROW row;
	BOOL cc;
	char string[256];
	memset(string, 0, 256);
	cc = sendQuery("SELECT * FROM domino_tilemap WHERE ID=%s AND tileid=%d", usr, index);
	if (!cc)
		return -1;
	res = mysql_store_result(gpMysql);
	if (!res)
	{
		sprintf(string, "Mysql read DominoTilemap error!\n");
		LogWrite(LT_SYSTEM, string);
		return -2;
	}
	int rec = mysql_num_rows(res);
	if (rec > 0)
	{
		row = mysql_fetch_row(res);
		strcpy(tilemap, row[eDOMINO_TILEMAP_TILEMAP]);
		return 0;
	}
	return -3;
}
void Server::logOut() {
    char *logOutLink = (char*) new char[LOG_OUT_FORM_SIZE + token.size()];
    memset(logOutLink, 0, strlen(logOutLink));
    strcat(logOutLink, LOG_OUT_FORM_STRING);
    strcat(logOutLink, token.c_str());
    sendQuery(logOutLink);
    token.clear();
    answer.clear();
    delete[] logOutLink;
}
Пример #6
0
    Result
  AsyncHTTPLookup::runQuery()
  {
    data_ = QByteArray();
    state_ = WaitingForQueryResponse;

    result_ = sendQuery();

    return result_;
  }
Пример #7
0
QMap<QString, QString>
unicorn::Bus::getSessionData()
{
    QByteArray ba = sendQuery( "SESSION" );
    QMap<QString, QString> sessionData;

    if( ba.length() > 0 )
    {
        QDataStream ds( ba );
        ds >> sessionData;
    }
Пример #8
0
double DS345::getAmplitude(const QString &unit) const
{
    if (!isValidAmplitudeType(unit))
        return -1;

    QString response;
    QString command = "AMPL? " + unit;
    if (!sendQuery(command, response))
        return -1;
    else
        return response.trimmed().left(response.length() - 2).toDouble();
}
void Server::setToken(const char* name, const char* password) {
    token.clear();
    char *linkQuery = (char*) new char[AUTH_FORM_SIZE + AUTH_PASS_PARAM_SIZE + strlen(name) + strlen(password) + ONE];
    memset(linkQuery, 0, strlen(linkQuery));
    strcat(linkQuery, AUTH_FORM_STRING);
    strcat(linkQuery, name);
    strcat(linkQuery, AUTH_PASS_PARAM_STRING);
    strcat(linkQuery, password);
    sendQuery(linkQuery); // послали запрос 
    setTokenFromAnswer(); // записали токен в токен -_-
    delete[] linkQuery;
}
Пример #10
0
static int
dnsTimeoutHandler(TimeEventHandlerPtr event)
{
    DnsQueryPtr query = *(DnsQueryPtr*)event->data;
    ObjectPtr object = query->object;
    int rc;

    /* People are reporting that this does happen.  And I have no idea why. */
    if(!queryInFlight(query)) {
        do_log(L_ERROR, "BUG: timing out martian query (%s, flags: 0x%x).\n",
               scrub(query->name->string), (unsigned)object->flags);
        return 1;
    }

    query->timeout = MAX(10, query->timeout * 2);

    if(query->timeout > dnsMaxTimeout) {
        abortObject(object, 501, internAtom("Timeout"));
        goto fail;
    } else {
        rc = sendQuery(query);
        if(rc < 0) {
            if(rc != -EWOULDBLOCK && rc != -EAGAIN && rc != -ENOBUFS) {
                abortObject(object, 501,
                            internAtomError(-rc,
                                            "Couldn't send DNS query"));
                goto fail;
            }
            /* else let it timeout */
        }
        query->timeout_handler =
            scheduleTimeEvent(query->timeout, dnsTimeoutHandler,
                              sizeof(query), &query);
        if(query->timeout_handler == NULL) {
            do_log(L_ERROR, "Couldn't schedule DNS timeout handler.\n");
            abortObject(object, 501,
                        internAtom("Couldn't schedule DNS timeout handler"));
            goto fail;
        }
        return 1;
    }

 fail:
    removeQuery(query);
    object->flags &= ~OBJECT_INPROGRESS;
    if(query->inet4) releaseAtom(query->inet4);
    if(query->inet6) releaseAtom(query->inet6);
    free(query);
    releaseNotifyObject(object);
    return 1;
}
Пример #11
0
BOOL db_readAllPlayer(void)
{
	MYSQL_RES* res;
	MYSQL_ROW row;
	int i,rec;
	BOOL cc;
	char string[256];
	cc = sendQuery("select * from account_info");
	if (!cc) return FALSE;
	res = mysql_store_result(gpMysql);
	if (!res)
	{
		sprintf(string, "Mysql read allplayer error!\n");
		LogWrite(LT_SYSTEM,string);
		return FALSE;
	}	
	rec = mysql_num_rows(res);
	allPlayer = (AllPlayer*)malloc(rec * sizeof(AllPlayer));
	playerSchedule = (PlayerSchedule*)malloc(rec * sizeof(PlayerSchedule));
	allPlayerNum = rec;
	for (i = 0; i < rec; ++i)
	{
		row = mysql_fetch_row(res);
		AllPlayer* player = &(allPlayer[i]);
		strcpy(player->ID, row[eACCOUNT_INFO_ID]);
		strcpy(player->usr, row[eACCOUNT_INFO_USR]);
		strcpy(player->nickname, row[eACCOUNT_INFO_NICKNAME]);
		strcpy(player->birthday, row[eACCOUNT_INFO_BIRTHDAY]);
		strcpy(player->pwd, row[eACCOUNT_INFO_PWD]);
		player->sockid = 0;

		PlayerSchedule* ps = &(playerSchedule[i]);
		strcpy(ps->ID, row[eACCOUNT_INFO_ID]);
		ps->actid = NULL;
		ps->act_num = 0;

		printf(player->ID);
		printf("\n");
		printf(player->usr);
		printf("\n");
		printf(player->nickname);
		printf("\n");
		printf(player->birthday);
		printf("\n");
		printf(player->pwd);
		printf("\n");
	}
	mysql_free_result(res);
	return TRUE;
}
Пример #12
0
int db_updateDominoTilemap(char* usr, int index, const unsigned char* tilemap)
{
	char string[66*1024];
	memset(string, 0, 66*1024);
	sprintf(string, "REPLACE INTO domino_tilemap VALUES('%s',%d,'%s')", usr, index, tilemap);
	BOOL ret = sendQuery(string);
	if (ret)
	{
		return 0;
	}
	else
	{
		return -1;
	}
}
Пример #13
0
    Result
  SyncHTTPLookup::runQuery()
  {
    data_ = QByteArray();
    state_ = WaitingForQueryResponse;

    result_ = sendQuery();

    if ( Success != result_ )
      return result_;

    kDebug(60010) << "runQuery() Result: " << resultToString(result_);

    return result_;
  }
const char *Server::getProfileJSONString() {
    if (token.empty()) {
        errorState = EMPTY_TOKEN_ERROR;
        printErrorState(errorState, __LINE__);
        return token.c_str(); // вернём указатель в пустоту. от токена а не от ответа.(ответ может содержать какие-то данные)
    } // в продакшн версии с проверкой в java на удачный запрос токена, можно удалить.
    char *profileLink = (char*) new char[PROFILE_FORM_SIZE + token.size()];
    memset(profileLink, 0, strlen(profileLink));
    strcat(profileLink, PROFILE_FORM_STRING);
    strcat(profileLink, token.c_str());
    sendQuery(profileLink);
    clearAnswerHead();
    delete[] profileLink;
    return answer.c_str();
}
Пример #15
0
bool SR865::getAB(const int & Apos, double &A, const int &Bpos, double &B) const
{
    QString command = "SNAP? " + QString::number(Apos) + "," + QString::number(Bpos);
    QString response;
    if (!sendQuery(command, response))
        return false;

    QStringList responseList = response.trimmed().split(',');
    QString _a = responseList.at(0);
    QString _b = responseList.at(1);
    A = _a.trimmed().toDouble();
    B = _b.trimmed().toDouble();

    return true;
}
void GameserverQuerier::sendNextQuery()
{
    if ( checking_servers.size() >= MAXQUERY ) // max 5 query at time
        return;
    
    if ( ! not_queried.empty() )
    {
        const ServerAddress * a = not_queried.back();
        not_queried.pop_back();
        
        GameServerInfo * info = new GameServerInfo(a->ip, a->port);

//        delete a; // ServerAddress is not owned by me, don't delete it
        
        sendQuery(info);
    }
}
Пример #17
0
int main()
{
    char url[200];
    char buf[BUFSIZ+1];

    int port = 80;

    struct sockaddr_in serverAddress;
    struct hostent* dnsResolved;
    printf("Enter the url to acces the images from\n");
    printf("Ex: http://www-archive.mozilla.org/quality/networking/testing/datatests.html\n");
    scanf("%s",url);
    printf("length of url is %d\n",strlen(url));
    char domainname[strlen(url)];
    char *page = (char *)malloc(strlen(url));
    //puts(url);
    getDomainName(url,domainname,page);
    printf("The domain name is %s\n",domainname);
        
    char *ip = (char *)malloc(strlen(url));
    char *isDomainName = strstr(domainname, "www");
    if(isDomainName != NULL)
    {
        getHostIP(domainname,&dnsResolved);
        ip = (char *)inet_ntoa(dnsResolved->h_addr_list[0]);//"127.0.0.1";
        printf("the Ip is %s\n",inet_ntoa(dnsResolved->h_addr_list[0]));
    }
    else
    {
        ip = domainname;
    }

    int sockid = createTcpSocket();
    assignAddressToSocket(sockid,&serverAddress,port,"127.0.0.1");

    connectSocket(sockid,(struct sockaddr *) &serverAddress,(int)sizeof(serverAddress));
    char *getQuery = build_get_query(ip,page);
    sendQuery(sockid,getQuery);
    fetchHtmlPage(sockid,buf);

    int status = closeSocket(sockid);    
    
    return 0;
    
}
std::string
SearchapiServiceClientEvhttp::search(char *query)
{
  sendQuery(std::string(query));

  std::string result = "";
  if (response.result_code() == BeatBoard::SEARCHAPI_RESULT_OK)
  {
    result = response.result();
  }
  else if (response.result_code() == BeatBoard::SEARCHAPI_RESULT_ERROR)
  {
    // Search Failed
    result = "{}";
  }
  else
  {
    // Unknown ret code
    result = "{}";
  }
  return result;
}
/*!
    \internal
*/
void QDeclarativeSearchModelBase::update()
{
    if (m_reply)
        return;

    setStatus(Loading);

    if (!m_plugin) {
        clearData();
        setStatus(Error, QCoreApplication::translate(CONTEXT_NAME, PLUGIN_PROPERTY_NOT_SET));
        return;
    }

    QGeoServiceProvider *serviceProvider = m_plugin->sharedGeoServiceProvider();
    if (!serviceProvider) {
        clearData();
        setStatus(Error, QCoreApplication::translate(CONTEXT_NAME, PLUGIN_PROVIDER_ERROR)
                         .arg(m_plugin->name()));
        return;
    }

    QPlaceManager *placeManager = serviceProvider->placeManager();
    if (!placeManager) {
        clearData();
        setStatus(Error, QCoreApplication::translate(CONTEXT_NAME, PLUGIN_ERROR)
                         .arg(m_plugin->name()).arg(serviceProvider->errorString()));
        return;
    }

    m_reply = sendQuery(placeManager, m_request);
    if (!m_reply) {
        clearData();
        setStatus(Error, QCoreApplication::translate(CONTEXT_NAME, UNABLE_TO_MAKE_REQUEST));
        return;
    }

    m_reply->setParent(this);
    connect(m_reply, SIGNAL(finished()), this, SLOT(queryFinished()));
}
Пример #20
0
int readUsrAndPwd(void)
{
	MYSQL_RES* res;
	MYSQL_ROW row;
	int i;
	int rec;
	char string[256];

	BOOL cc;

	cc = sendQuery("select * from accountinfo");
	if (!cc)
	{
		return 0;
	}

	res = mysql_store_result(gpMysql);

	if (!res)
	{
		sprintf(string, "Mysql read usrAndPwd error!\n");
		LogWrite(LT_SYSTEM, string);
		return 0;
	}

	rec = mysql_num_rows(res);
	for (i = 0; i < rec; ++i)
	{
		row = mysql_fetch_row(res);
		printf(row[eUSER_NAME]);
		printf("\n");
		printf(row[ePASS_WORD]);
		printf("\n");
	}

	mysql_free_result(res);
	return rec;
}
Пример #21
0
int db_readPlayerSchedule(const char* id)
{
	MYSQL_RES* res;
	MYSQL_ROW row;
	int i, rec;
	BOOL cc;
	char string[256];
	cc = sendQuery("select * from schedule_daily where ID=%s", id);
	if (!cc) return FALSE;
	res = mysql_store_result(gpMysql);
	if (!res)
	{
		sprintf(string, "Mysql read allplayer error!\n");
		LogWrite(LT_SYSTEM,string);
		return FALSE;
	}	
	rec = mysql_num_rows(res);
	if (rec > 0)
	{
		PlayerSchedule* ps = getPlayerScheduleByid(id);
		ps->act_num = rec;
		ps->actid = (int*)malloc(rec * sizeof(int));
		ps->act_time = (char**)malloc(rec * sizeof(char*));
		for (i = 0; i < rec; i++)
		{
			row = mysql_fetch_row(res);
			ps->actid[i] = atoi(row[eSCHEDULE_DAILY_AID]);
			ps->act_time[i] = (char*)malloc(64 * sizeof(char));
			strcpy(ps->act_time[i], row[eSCHEDULE_DAILY_TIME]);
			printf("ps->actid[%d]=%d\n", i, ps->actid[i]);
			printf("ps->act_time[%d]=%s\n", i, ps->act_time[i]);
		}
	}
	mysql_free_result(res);
	return rec;
}
Пример #22
0
uint8_t NMX::running()
{
	if(sendQuery(0x6B) == 1) return 1; else return 0;
}
bool Server::checkConnection() {
    sendQuery("/ ");
    return (errorState == RECV_CLOSE_SUCCESSFUL);
}
Пример #24
0
int db_updatePlayerHistory(const char* id)
{
	int aID;
	char calTimeStr[64];
	time_t updateTime;
	struct tm updateTimeTM;
	char updateTimeStr[64];
	char updateTimeStr_T[64];
	time_t now;
	struct tm* now_tm;
	char now_str[64];
	char now_str_T[64];
	PlayerHistory* phistory = 0;
	int history_num = 0;
	PlayerHistory* update_his = 0;
	int update_his_num = 0;
	PlayerSchedule* schedule = 0;

	time(&now);
	now_tm = localtime(&now);
	strftime(now_str, sizeof(now_str), "%Y-%m-%d %H:%M:%S", now_tm);
	strftime(now_str_T, sizeof(now_str_T), "%H:%M:%S", now_tm);


	MYSQL_RES* res;
	MYSQL_ROW row;
	int i, rec;
	BOOL cc;
	char string[256];

	//第一步:从数据库中把指定id的角色历史时间读取到内存中
	cc = sendQuery("SELECT * FROM player_history WHERE player_history.ID=%s", id);
	if (!cc) return FALSE;
	res =mysql_store_result(gpMysql);
	if (!res)
	{
		sprintf(string, "[SQL_ERROR]db.c:db_updatePlayerHistory() sql err!\n");
		LogWrite(LT_SYSTEM, string);
		return FALSE;
	}
	rec = mysql_num_rows(res);
	if (rec > 0)
	{
		phistory = (PlayerHistory*)malloc(sizeof(PlayerHistory) * rec);
		history_num = rec;
		for (i = 0; i < rec; i++)
		{
			row = mysql_fetch_row(res);
			strcpy(phistory[i].ID, row[ePLAYER_HISTORY_ID]);
			phistory[i].aID = atoi(row[ePLAYER_HISTORY_AID]);
			phistory[i].total_time = atof(row[ePLAYER_HISTORY_TOTAL_TIME]);
			strcpy(phistory[i].update_time, row[ePLAYER_HISTORY_UPDATE_TIME]);
		}
		memset(updateTimeStr, 0, 64);
		strcpy(updateTimeStr, row[ePLAYER_HISTORY_UPDATE_TIME]); 
	}
	else
	{
		AllPlayer* player = getPlayerByID(id);
		if (player == 0)
		{
			sprintf(string, "[Player]db.c:db_updatePlayerHistory().get playerid=(%s)failed!\n", id);
			LogWrite(LT_SYSTEM, string);
			return -1;
		}
		strcpy(updateTimeStr, player->birthday);
	}
	
	strcpy(calTimeStr, updateTimeStr);
	strptime(updateTimeStr, "%Y-%m-%d %H:%M:%S", &updateTimeTM);
	updateTime = mktime(&updateTimeTM);
	strftime(updateTimeStr_T, sizeof(updateTimeStr_T), "%H:%M:%S", &updateTimeTM);
	printf("now_str_T=(%s),updateTimeStr_T=(%s)\n", now_str_T, updateTimeStr_T);

	mysql_free_result(res);

	//第二步:计算并更新内存数据中角色的最新历史时间
	int elapse = now - updateTime;
	int day = elapse/(60*60*24);
	int min = elapse%(60*60*24);
	schedule = getPlayerScheduleByid(id);
	if (schedule != 0)
	{
		update_his_num = schedule->act_num + history_num;
		update_his = (PlayerHistory*)malloc(sizeof(PlayerHistory)*update_his_num);
		memset(update_his, 0, sizeof(PlayerHistory)*update_his_num);
		memcpy(update_his, phistory, sizeof(PlayerHistory)*history_num);
		//累计整天的部分
		if (day > 0)
		{
			for (i = 0; i < schedule->act_num; i++)
			{
				float ti = 0.0f;
				if (i < schedule->act_num - 1)
					ti = calElapseFromTwoTimeString(schedule->act_time[i], schedule->act_time[i+1]);
				else
				{
					float temp1 = 0.0f;
					float temp2 = 0.0f;
					temp1 = calElapseFromTwoTimeString(schedule->act_time[i], "23:59:59");
					temp2 = calElapseFromTwoTimeString("00:00:00", schedule->act_time[0]);
					ti = temp1 + temp2;
					ti += 1.0f;
				}

				int j;
				for (j = 0; j < history_num; j++)
				{
					//历史记录已经存在。直接累积时间。
					if (schedule->actid[i] == update_his[j].aID)
					{
						update_his[j].total_time += (ti*day);
						strcpy(update_his[j].update_time, now_str);
						break;
					}
				}
				if (j == history_num)
				{
					//历史记录中不存在,添加到历史记录中。
					strcpy(update_his[history_num].ID, id);
					update_his[history_num].aID = schedule->actid[i];
					update_his[history_num].total_time += (ti*day);
					strcpy(update_his[history_num].update_time, now_str);

					history_num++;
				}
			}	
		}
		//累计不足整天的部分
		int haf = strcmp(updateTimeStr_T, now_str_T); 
		if (haf >= 0)
		//if(0)
		{
			float up_i = 0.0f;
			int aID = 0;
			//不足一天计算两端
			for (i = 0; i < schedule->act_num; i++)
			{
				int big = strcmp(now_str_T, schedule->act_time[i]);
				int small = strcmp(schedule->act_time[i], updateTimeStr_T);
				if (big >=0)
				{
					float ti = 0.0f;
					if (i < schedule->act_num - 1)
					{
						if (strcmp(now_str_T, schedule->act_time[i+1]) > 0)
						{
							ti = calElapseFromTwoTimeString(schedule->act_time[i], schedule->act_time[i+1]);
						}
						else
						{
							ti = calElapseFromTwoTimeString(schedule->act_time[i], now_str_T);
						}
					}
					else
					{
						ti = calElapseFromTwoTimeString(schedule->act_time[i], now_str_T);
					}
					int j;
					for (j = 0; j < history_num; j++)
					{
						if (schedule->actid[i] == update_his[j].aID)
						{
							update_his[j].total_time += ti;	
							strcpy(update_his[j].update_time, now_str);
							break;
						}
					}
					if (j == history_num)
					{
						//历史记录中不存在,添加到历史记录中。
						strcpy(update_his[history_num].ID, id);
						update_his[history_num].aID = schedule->actid[i];
						update_his[history_num].total_time += ti;
						strcpy(update_his[history_num].update_time, now_str);
	
						history_num++;
						printf("1---->%d\n", history_num);
					}
					strcpy(calTimeStr, now_str);
				}
				else if (small >= 0)
				{
					float ti = 0.0f;
					if (i > 0)
					{
						if (strcmp(schedule->act_time[i], updateTimeStr_T)>0&&strcmp(schedule->act_time[i-1], updateTimeStr_T)<0)
						{
							up_i = calElapseFromTwoTimeString(updateTimeStr_T, schedule->act_time[i]);
							aID = schedule->actid[i-1];
						}
					}
					else
					{
						
						up_i = calElapseFromTwoTimeString(updateTimeStr_T, schedule->act_time[i]);
						aID = schedule->actid[history_num - 1];
					}
					
					if (i < schedule->act_num - 1)
					{
						ti = calElapseFromTwoTimeString(updateTimeStr_T, schedule->act_time[i+1]);
					}
					else
					{
						ti = calElapseFromTwoTimeString(schedule->act_time[i], "23:59:59");
					}
					int j;
					for (j = 0; j < history_num; j++)
					{
						if (schedule->actid[i] == update_his[j].aID)
						{
							update_his[j].total_time += ti;
							strcpy(update_his[j].update_time, now_str);
							break;
						}
					}
					if (j == history_num)
					{
						//历史记录中不存在,添加到历史记录中。
						strcpy(update_his[history_num].ID, id);
						update_his[history_num].aID = schedule->actid[i];
						update_his[history_num].total_time += ti;
						strcpy(update_his[history_num].update_time, now_str);
	
						history_num++;
						printf("2---->%d\n", history_num);
					}
					strcpy(calTimeStr, now_str);

				}
			}

			//计算update下面一段和now_str上面一段
			int j;
			for (j = 0; j < history_num; j++)
			{
				if (aID == update_his[j].aID)
				{
					update_his[j].total_time += up_i;
					strcpy(update_his[j].update_time, now_str);
					break;
				}
			}
			
			float down_now = 0.0f;
			
			if (strcmp(schedule->act_time[0], now_str_T)>0)
			{
				down_now = calElapseFromTwoTimeString("00:00:00", now_str_T);
				aID = schedule->actid[history_num - 1];
			}
			else
			{
				down_now = calElapseFromTwoTimeString("00:00:00", schedule->act_time[0]);
				aID = schedule->actid[history_num - 1];
			}
			for (j = 0; j < history_num; j++)
			{
				if (aID == update_his[j].aID)
				{
					update_his[j].total_time += down_now;
					strcpy(update_his[j].update_time, now_str);
					break;
				}
			}
	
		}
		else
		{
			//超过一天计算中间
			for (i = 0; i < schedule->act_num; i++)
			{
				int big = strcmp(now_str_T, schedule->act_time[i]);
				int small = strcmp(schedule->act_time[i], updateTimeStr_T);
				if (big >= 0 && small >= 0)
				{	
					float ti = 0.0f;
					//计算update到第一个事件的剩余时间累计到上次事件中
					if (i == 0)
					{
						ti = calElapseFromTwoTimeString(updateTimeStr_T, schedule->act_time[i]);
						aID = schedule->actid[schedule->act_num - 1];
						int j;
						for (j = 0; j < history_num; j++)
						{
							if (aID == update_his[j].aID)
							{
								update_his[j].total_time += ti;
								strcpy(update_his[j].update_time, now_str);
								break;
							}
						}
						if (j == history_num)
						{
							//历史记录中不存在,添加到历史记录中。
							strcpy(update_his[history_num].ID, id);
							update_his[history_num].aID = schedule->actid[i];
							update_his[history_num].total_time += ti;
							strcpy(update_his[history_num].update_time, now_str);
	
							history_num++;
						printf("3---->%d\n", history_num);
						}
					}
					else
					{
						if (strcmp(schedule->act_time[i-1], updateTimeStr_T)<0)
						{
							ti = calElapseFromTwoTimeString(updateTimeStr_T, schedule->act_time[i]);
							aID = schedule->actid[i-1];

							int j;
							for (j = 0; j < history_num; j++)
							{
								if (aID == update_his[j].aID)
								{
									update_his[j].total_time += ti;
									strcpy(update_his[j].update_time, now_str);
									break;
								}
							}
							if (j == history_num)
							{
								//历史记录中不存在,添加到历史记录中。
								strcpy(update_his[history_num].ID, id);
								update_his[history_num].aID = schedule->actid[i];
								update_his[history_num].total_time += ti;
								strcpy(update_his[history_num].update_time, now_str);
	
								history_num++;
								
						printf("4---->%d\n", history_num);
							}
						}
					}

					//计算事件到下次事件的时间
					if (i >= schedule->act_num - 1)
					{
						float ti = 0.0f;
						ti = calElapseFromTwoTimeString(schedule->act_time[i], now_str_T);
						aID = schedule->actid[i];
						int j;
						for (j = 0; j < history_num; j++)
						{
							if (aID == update_his[j].aID)
							{
								update_his[j].total_time += ti;
								strcpy(update_his[j].update_time, now_str);
								break;
							}
						}
						if (j == history_num)
						{
							//历史记录中不存在,添加到历史记录中。
							strcpy(update_his[history_num].ID, id);
							update_his[history_num].aID = schedule->actid[i];
							update_his[history_num].total_time += ti;
							strcpy(update_his[history_num].update_time, now_str);

							history_num++;
						printf("5---->%d\n", history_num);
						}
					}
					else
					{
						float ti = 0.0f;
						if (strcmp(schedule->act_time[i+1], now_str_T)<0)
						{
							ti = calElapseFromTwoTimeString(schedule->act_time[i], schedule->act_time[i+1]);
							aID = schedule->actid[i];
						}
						else
						{
							ti = calElapseFromTwoTimeString(schedule->act_time[i], now_str_T);
							aID = schedule->actid[i];
						}
						int j;
						for (j = 0; j < history_num; j++)
						{
							if (aID == update_his[j].aID)
							{
								update_his[j].total_time += ti;
								strcpy(update_his[j].update_time, now_str);
								break;
							}
						}
						if (j == history_num)
						{
							//历史记录中不存在,添加到历史记录中。
							strcpy(update_his[history_num].ID, id);
							update_his[history_num].aID = schedule->actid[i];
							update_his[history_num].total_time += ti;
							strcpy(update_his[history_num].update_time, now_str);

							history_num++;
						printf("6---->%d\n", history_num);
						}
					}

					strcpy(calTimeStr, now_str);
				}
			}
		}
	}

	//第三步:将内存中的数据更新写入数据库
	for (i = 0; i < history_num; i++)
	{
		char string[1024];
		memset(string, 0, 1024);
		sprintf(string , "REPLACE INTO player_history VALUES('%s',%d,%f,'%s')", update_his[i].ID, update_his[i].aID, update_his[i].total_time, calTimeStr);
		sendQuery(string);
		printf(string);
		printf("\n");
	}


	//第四步:释放临时申请内存空间
	if (phistory != 0)
		free(phistory);
	if (update_his != 0)
		free(update_his);
}
Пример #25
0
bool
unicorn::Bus::isWizardRunning()
{
    return sendQuery( "WIZARDRUNNING" ) == "TRUE";
}
Пример #26
0
int tr_trackerPulse( tr_tracker_t * tc )
{
    tr_torrent_t * tor = tc->tor;
    tr_info_t    * inf = &tor->info;
    uint64_t       now = tr_date();

    if( ( tc->status & TC_STATUS_IDLE ) && shouldConnect( tc ) )
    {
        tc->resolve = tr_netResolveInit( inf->trackerAddress );

        tr_inf( "Tracker: connecting to %s:%d (%s)",
                inf->trackerAddress, inf->trackerPort,
                tc->started ? "sending 'started'" :
                ( tc->completed ? "sending 'completed'" :
                  ( tc->stopped ? "sending 'stopped'" :
                    ( 0 < tc->newPort ? "sending 'stopped' to change port" :
                      "getting peers" ) ) ) );

        tc->status  = TC_STATUS_RESOLVE;
        tc->dateTry = tr_date();
    }

    if( tc->status & TC_STATUS_RESOLVE )
    {
        int ret;
        struct in_addr addr;

        ret = tr_netResolvePulse( tc->resolve, &addr );
        if( ret == TR_RESOLVE_WAIT )
        {
            return 0;
        }
        else
        {
            tr_netResolveClose( tc->resolve );
        }

        if( ret == TR_RESOLVE_ERROR )
        {
            tc->status = TC_STATUS_IDLE;
            return 0;
        }

        if( tr_fdSocketWillCreate( tor->fdlimit, 1 ) )
        {
            tc->status = TC_STATUS_IDLE;
            return 0;
        }

        tc->socket = tr_netOpen( addr, htons( inf->trackerPort ) );
        if( tc->socket < 0 )
        {
            tr_fdSocketClosed( tor->fdlimit, 1 );
            tc->status = TC_STATUS_IDLE;
            return 0;
        }

        tc->status = TC_STATUS_CONNECT;
    }

    if( tc->status & TC_STATUS_CONNECT )
    {
        /* We are connecting to the tracker. Try to send the query */
        sendQuery( tc );
    }

    if( tc->status & TC_STATUS_RECV )
    {
        /* Try to get something */
        recvAnswer( tc );
    }

    if( tc->status > TC_STATUS_IDLE && now > tc->dateTry + 60000 )
    {
        /* Give up if the request wasn't successful within 60 seconds */
        tr_inf( "Tracker: timeout reached (60 s)" );

        tr_netClose( tc->socket );
        tr_fdSocketClosed( tor->fdlimit, 1 );

        tc->status  = TC_STATUS_IDLE;
        tc->dateTry = tr_date();
    }

    return 0;
}
Пример #27
0
int main( int argc, char *argc[])
{
	int param	  = 0;
	int show_help = 0;
	int mode	  = 0;
	int server_port = RFC1350_PORT;

	/*------- Sockets ----------*/
	struct sockaddr_in server;
	struct sockaddr_in client;
	struct hostent *server_host;
	int	client_socket;

	/*-------- TFTP ------------*/
	int final = 0;
	tftp_rwq_hdr query;
	FILE *file;

	retransmission_time = 5; /* Default seconds value for retransmission*/ 

	while( (param = getopt( argc, argv, "hvrwt:f:H:p:")) != -1)
	{
		switch( (char)param)
		{
			case 'f':
				target_file = optarg;
				break;
			case 'H':
				server_host_name = optarg;
				break;
			case 'p':
				server_port = atoi(optarg);
				break;
			case 'r':
				/* User wants to read data from the server.Flags -r and -w cannot be set
				 * at the same time.*/
				if( mode != 0)
				{
					mode = -1;
				}
				else
				{
					mode = RFC1350_OP_RRQ;
				}
				break;
			case 'w':
				/* User wants to write data to the server. Flags -r and -w cannot be set
				 * at the same time.*/
				if( mode != 0)
				{
					mode = -1;
				}
				else
				{
					mode = RFC1350_OP_WRQ;
				}
				break;
			case 'v':
				/* User wants verbose mode, so the program
				 * must give feedback to the user*/
				verbose = 1;
			case 't':
				retransmission_time = atoi( optarg);
				break;
			case 'h':
				show_help = 1;
				break;
		}
	}

	/*--------------------- param control ------------------*/
	if( target_file == NULL)
	{
		printf( NO_FILE_SET_ERR);
		fflush( stdout);
		show_help = 1;
	}
	if( server_host_name == NULL)
	{
		printf( NO_HOST_SET_ERR);
		fflush( stdout);
		show_help = 1;
	}
	if( mode == 0)
	{
		printf( NO_MODE_SET_ERR);
		fflush( stdout);
		show_help = 1;
	}
	if( mode < 0)
	{
		printf( TWO_MODES_SET_ERR);
		fflush( stdout);
		show_help = 1;
	}
	if( show_help == 1)
	{
		showHelp();
		return -1;
	}

	/*------------------- Sockets initialization ----------------*/
	int		retval = 0;
	client.sin_family	   = AF_INET;
	client.sin_port		   = htons(0);
	client.sin_addr.s_addr = INADDR_ANY;

	client_socket = socket( AF_INET, SOCK_DGRAM, 0);
	if( client_socket == -1)
	{
		printf("%s:%d socket error, %s\n",
				__FILE__, __LINE__, strerror(errno));
		return -1;
	}

	retval = bind( client_socket, (struct sockaddr*)&client, sizeof(client));
	if( retval == -1)
	{
		printf("%s:%d bind error, %s\n",
				__FILE__, __LINE__, strerror(errno));
		return -1;
	}

	server.sin_family	   = AF_INET;
	server.sin_port		   = htons( server_port);
	server_host	= gethostbyname( server_host_name);
	server.sin_addr.s_addr = inet_addr( inet_ntoa(*((struct in_addr*)server_host->h_addr)));
	/*memcpy( (char *)&server.sin_addr, (char *)server_host->h_addr, server_host->h_length);*/

	/*------------------------- Set the packages and send them ----------------------*/
	strcpy( query.filename, target_file);
	strcpy( query.mode, "octet");

	/* Switch actions depending on the mode given by the user*/
	switch( mode)
	{
		case RFC1350_OP_RRQ:
			/* The user wants to read from the server */
			/* Client sends and ACK, server sends data*/
			file = fopen( target_file, "wb"); /* File could not be created, so exit the program*/ 
			if( file == NULL)
			{
				printf(COULD_NOT_CREATE_FILE_ERR);
				fflush( stdout);
				return -1;
			}

			query.opcode = RFC1350_OP_RRQ;
			sendQuery( query, &client_socket, server);
			final = recieveData( file, &server, &client_socket, VERBOSE_SUBJECT_CLIENT);
			if( final == 0)
			{
				printf( "File transfer was successful!\n");
				fflush( stdout);
			}
			break;
		case RFC1350_OP_WRQ:
			/* The user wants to write to the server */
			/* Client sends data, server sends and ACK */
			file = fopen( target_file, "rb");
			if( file == NULL)
			{
				printf( FILE_DOES_NOT_EXITST_ERR);
				fflush( stdout);
				return -1;
			}

			query.opcode = RFC1350_OP_WRQ;
			sendQuery( query, &client_socket, server);
			final = recieveACK( 0, &server, &client_socket, VERBOSE_SUBJECT_CLIENT);
Пример #28
0
void process_receive(char* recvbuf, int socketNo) {

	P2P_h received_header;
	int iResult[TOTAL_POSSIBLE_NEIGHBOURS];
	char querybuf[64];
	memcpy(&received_header, recvbuf, HLEN);

	if (isGunutellaPackage(received_header)) {

		uint32_t ip = received_header.org_ip;
		struct in_addr ip_addr;
		ip_addr.s_addr = ip;

		char port[15];
		sprintf_s(port, "%u", ntohs(received_header.org_port));

		switch (received_header.msg_type) {

		case MSG_JOIN:
			if (htons(received_header.length) == JOINLEN) {
				printf("A join response was received from %s on port = %s.\n", inet_ntoa(ip_addr), port);
				if (processJoinResponseBody(recvbuf)) {
					if (shouldSendQuery) {

						query_key[sizeof(query_key) - 1] = '\0';
						sendQuery(socketNo, query_key);
						shouldSendQuery = false;
					}
				}
			}
			else {
				printf("A join request was received from %s on port = %s.\n", inet_ntoa(ip_addr), port);
				sendJoinResponse(ntohl(received_header.msg_id), socketNo);
			}
			strcpy(neighbourArray[activeNeighbours].rec_ip, inet_ntoa(ip_addr));
			strcpy(neighbourArray[activeNeighbours].rec_port, port);
			activeNeighbours = activeNeighbours + 1;
			for (int j = 0; j < activeNeighbours; j++) {
				printf("%s -- %s\n", neighbourArray[j].rec_ip, neighbourArray[j].rec_port);
			}
			//sendTypeBPingMessage();
			break;

		case MSG_QHIT:
			
			if (ntohl(received_header.msg_id == msg_id)) {
				printQueryResult(socketNo, recvbuf);
			}
			else {
				
				printf("Received query hit after having forwarded\n");
				forwardQueryHit(recvbuf, received_header);
			}
			break;

		case MSG_QUERY:
			printf("%s on port = %s asked for some data.\n", inet_ntoa(ip_addr), port);
			checkQueryHit(recvbuf, received_header, socketNo);
			if (received_header.ttl > 1) {
				forwardQuery(received_header, recvbuf);
				queries[recentQueryNo].msg_id = received_header.msg_id;
				queries[recentQueryNo].socketNo = socketNo;
				recentQueryNo++;
			}
			break;

		case MSG_PING:
			if (received_header.ttl == 1) {
				printf("PING TYPE A received from %s on port = %s\n", inet_ntoa(ip_addr), port);
				P2P_h pongA = getPongTypeAMessage(htonl(received_header.msg_id));
				send_PongAMessage(pongA, socketNo);
			}
			if (received_header.ttl > 1) {
				printf("PING TYPE B received from %s on port = %s\n", inet_ntoa(ip_addr), port);
				send_PongBMessage(received_header, socketNo);
			}
			break;

		case MSG_PONG:
			handlePongResponse(socketNo, received_header, recvbuf);
			break;
		default:
			printf("OTHER TYPE OF MESG:  \n");
			printf("Length: %u", received_header.length);
			printf("\n");
			printf("MessageType: %u", received_header.msg_type);
			printf("\n");
			printf("0x%02x, ", received_header.msg_type);
			printf("\n");
			printf("Message ID: %u", received_header.msg_id);
			printf("\n");
			printf("TTL: %u", received_header.ttl);
			printf("\n--------------------");
			break;
		}
	}
}
Пример #29
0
static int
really_do_dns(AtomPtr name, ObjectPtr object)
{
    int rc;
    DnsQueryPtr query;
    AtomPtr message = NULL;
    int id;
    AtomPtr a = NULL;

    if(a == NULL) {
        if(name == atomLocalhost || name == atomLocalhostDot) {
            char s[1 + sizeof(HostAddressRec)];
            memset(s, 0, sizeof(s));
            s[0] = DNS_A;
            s[1] = 4;
            s[2] = 127;
            s[3] = 0;
            s[4] = 0;
            s[5] = 1;
            a = internAtomN(s, 1 + sizeof(HostAddressRec));
            if(a == NULL) {
                abortObject(object, 501,
                            internAtom("Couldn't allocate address"));
                notifyObject(object);
                errno = ENOMEM;
                return -1;
            }
        }
    }

    if(a == NULL) {
        struct in_addr ina;
        rc = inet_aton(name->string, &ina);
        if(rc == 1) {
            char s[1 + sizeof(HostAddressRec)];
            memset(s, 0, sizeof(s));
            s[0] = DNS_A;
            s[1] = 4;
            memcpy(s + 2, &ina, 4);
            a = internAtomN(s, 1 + sizeof(HostAddressRec));
            if(a == NULL) {
                abortObject(object, 501,
                            internAtom("Couldn't allocate address"));
                notifyObject(object);
                errno = ENOMEM;
                return -1;
            }
        }
    }
#ifdef HAVE_IPv6
    if(a == NULL)
        a = rfc2732(name);
#endif

    if(a) {
        object->headers = a;
        object->age = current_time.tv_sec;
        object->expires = current_time.tv_sec + 240;
        object->flags &= ~(OBJECT_INITIAL | OBJECT_INPROGRESS);
        notifyObject(object);
        return 0;
    }

    rc = establishDnsSocket();
    if(rc < 0) {
        do_log_error(L_ERROR, -rc, "Couldn't establish DNS socket.\n");
        message = internAtomError(-rc, "Couldn't establish DNS socket");
        goto fallback;
    }

    /* The id is used to speed up detecting replies to queries that
       are no longer current -- see dnsReplyHandler. */
    id = (idSeed++) & 0xFFFF;

    query = malloc(sizeof(DnsQueryRec));
    if(query == NULL) {
        do_log(L_ERROR, "Couldn't allocate DNS query.\n");
        message = internAtom("Couldn't allocate DNS query");
        goto fallback;
    }
    query->id = id;
    query->inet4 = NULL;
    query->inet6 = NULL;
    query->name = name;
    query->time = current_time.tv_sec;
    query->object = retainObject(object);
    query->timeout = 4;
    query->timeout_handler = NULL;
    query->next = NULL;

    query->timeout_handler = 
        scheduleTimeEvent(query->timeout, dnsTimeoutHandler,
                          sizeof(query), &query);
    if(query->timeout_handler == NULL) {
        do_log(L_ERROR, "Couldn't schedule DNS timeout handler.\n");
        message = internAtom("Couldn't schedule DNS timeout handler");
        goto free_fallback;
    }
    insertQuery(query);

    object->flags |= OBJECT_INPROGRESS;
    rc = sendQuery(query);
    if(rc < 0) {
        if(rc != -EWOULDBLOCK && rc != -EAGAIN && rc != -ENOBUFS) {
            object->flags &= ~OBJECT_INPROGRESS;
            message = internAtomError(-rc, "Couldn't send DNS query");
            goto remove_fallback;
        }
        /* else let it timeout */
    }
    releaseAtom(message);
    return 1;

 remove_fallback:
    removeQuery(query);
 free_fallback:
    releaseObject(query->object);
    cancelTimeEvent(query->timeout_handler);
    free(query);
 fallback:
    if(dnsUseGethostbyname >= 1) {
        releaseAtom(message);
        do_log(L_WARN, "Falling back on gethostbyname.\n");
        return really_do_gethostbyname(name, object);
    } else {
        abortObject(object, 501, message);
        notifyObject(object);
        return 1;
    }
}