Ejemplo n.º 1
0
void
_handle_req_hello(conn_t *conn)
{
  ipc_resp_t *resp = NULL;
  char *buf = NULL;
  size_t buf_len = 1024;
  size_t len = 0;

  conn->flags |= CONN_F_HUMAN;

  CALLOC(resp, 1, sizeof(ipc_resp_t));

  do {
    FREE(buf);
    if (len > buf_len) buf_len = len + 1;
    CALLOC(buf, buf_len, sizeof(char));
    len = snprintf(buf, buf_len, "%s v%u.%u %s\n",
                   PROGNAME, VERSION_MAJOR, VERSION_MINOR, MSG_I_HELLO);
  } while (len > buf_len);

  resp->status = STATUS_OK;
  resp->data.type = DATA_T_MSG;
  data_item_add(&resp->data, buf, len);

  ipc_responce_write(conn, resp);

  data_clear(&resp->data);
  FREE(resp);
}
Ejemplo n.º 2
0
void
_handle_req_file_search(conn_t *conn, const ipc_req_t *req)
{
  ipc_resp_t resp;
  uint16_t i = 0;
  char *item = NULL;

  ASSERT(conn != NULL && req != NULL, MSG_M_NULLPTR);

  memset(&resp, 0x0, sizeof(ipc_resp_t));
  resp.status = STATUS_OK;
  resp.data.type = DATA_M_UUID_FILE;

  while (data_items_walk(&req->data, &item) > 0)
    if (db_file_search_path(item, &resp.data) == 0)
      i++;

  if (i != req->data.items && i != 0)
    data_item_add(&conn->errors, MSG_I_PARTREQ, 0);

  if (resp.data.items == 0)
    {
      resp.status = STATUS_ERR;
      resp.data.type = DATA_EMPTY;
    }

  ipc_responce_write(conn, &resp);

  data_clear(&resp.data);
}
Ejemplo n.º 3
0
Archivo: rfxd.c Proyecto: hyper/librisp
// initialise a data structure that is invalid.
void data_init(data_t *data) {
	assert(data != NULL);
	
	expbuf_init(&data->file, 0);
	expbuf_init(&data->data, 0);

	data_clear(data);
}
Ejemplo n.º 4
0
/**
 * Load recorded data from a file.
 */
void data_load(FILE *file) {
    char buf[64];
    int line = 1, origin_az = 0;

    while (fgets(buf, sizeof(buf), file) != NULL) {
        if (buf[0] == '#') {
            if (sscanf(buf, "# @%s %d,%*d\n", buf, &origin_az) >= 1) {
                if (strcmp(buf, "origin") == 0) {
                    printf("# Origin: %d\n", origin_az);
                } else if (strcmp(buf, "azimuth") == 0) {
                    printf("#### Azimuth ####\n");
                    data_clear(&set);
                    set.elevation = false;
                } else if (strcmp(buf, "elevation") == 0) {
                    data_pattern_dump(origin_az);
                    printf("#### Elevation ####\n");
                    data_clear(&set);
                    set.elevation = true;
                } else {
                    fprintf(stderr, "%d: warning: unknown command\n", line);
                }
            }
        } else {
            float azimuth, elevation;
            int strength;

            if (sscanf(buf, format, &azimuth, &elevation, &strength) != 3) {
                fprintf(stderr, "%d: error: invalid data format\n", line);
                exit(EXIT_FAILURE);
            }

            if (!set.elevation) {
                data_add(azimuth, strength);
            } else {
                data_add(elevation, strength);
            }
        }

        line++;
    }

    // Dump the data from the elevation pattern.
    data_pattern_dump(origin_az);
}
Ejemplo n.º 5
0
Archivo: rfxd.c Proyecto: hyper/librisp
// This callback function is to be fired when the CMD_CLEAR command is 
// received.  It should clear off any data received and stored in variables 
// and flags.  In otherwords, after this is executed, the node structure 
// should be in a predictable state.
void cmdClear(void *base) 
{
 	node_t *ptr = (node_t *) base;
 	assert(ptr != NULL);
	data_clear(&ptr->data);
 	assert(ptr->stats != NULL);
	ptr->stats->commands ++;

	printf("node:%d CLEAR\n", ptr->handle);
}
Ejemplo n.º 6
0
void transaction3(unsigned char dev_addr)
{
	int temp, index, length;
	u32 SMBusBase;

	SMBusBase = sch_SMbase_read();
	printk(BIOS_DEBUG, "smb_read_multiple_bytes");
	smb_clear();
	data_clear();
	outb(dev_addr, SMBusBase + SMBHSTADD);
	outb(0x03, SMBusBase + SMBHSTCMD);
	outb(0x11, SMBusBase + SMBHSTCNT);

	//data_clear();
	outb(dev_addr + 1, SMBusBase + SMBHSTADD);

	outb(0x15, SMBusBase + SMBHSTCNT);

	// sch_SMbus_regs ();
	//check the status register for busy state
	//temp = inb(SMBusBase+SMBHSTSTS);
	//printk(BIOS_DEBUG, "SMBus Busy.. status =%x\r\n",temp);
	//sch_SMbus_regs ();
	//printk(BIOS_DEBUG, "SMBHSTSTS. =%x\r\n",inb(SMBusBase+SMBHSTSTS));
	do {
		temp = inb(SMBusBase + SMBHSTSTS);
		printk(BIOS_DEBUG, "SMBHSTSTS. =%x\r\n",
		       inb(SMBusBase + SMBHSTSTS));
		//sch_SMbus_regs ();
		if (temp > 0)
			break;
	} while (1);

	switch (temp) {
	case 1:
		printk(BIOS_DEBUG, "SMBus Success\n");
		break;
	default:
		printk(BIOS_DEBUG, "SMBus error %d", temp);
		break;

	}

	sch_SMbus_regs();
	printk(BIOS_DEBUG, "ADDRESS is.. %x\r\n", inb(SMBusBase + SMBHSTADD));
	length = inb(SMBusBase + SMBHSTDAT0);

	printk(BIOS_DEBUG, "Length is.. %x\r\n", inb(SMBusBase + SMBHSTDAT0));

	printk(BIOS_DEBUG, "Command is... %x\r\n", inb(SMBusBase + SMBHSTDATB));
	printk(BIOS_DEBUG, "Status .. %x\r\n", inb(SMBusBase + SMBHSTDATB + 1));
	for (index = 0; index < length; index++)
		printk(BIOS_DEBUG, "Serial Byte[%x]..%x\r\n", index,
		       inb(SMBusBase + SMBHSTDATB + index));
}
Ejemplo n.º 7
0
void transaction1(unsigned char dev_addr)
{
	int temp, a;
	u32 SMBusBase;

	SMBusBase = sch_SMbase_read();
	printk(BIOS_DEBUG, "Transaction 1");
	//clear the control and status registers
	smb_clear();
	//clear the data register
	data_clear();
	//program TSA register
	outb(dev_addr, SMBusBase + SMBHSTADD);
	//program command register
	outb(0x04, SMBusBase + SMBHSTCMD);
	//write data register
	outb(0x04, SMBusBase + SMBHSTDAT0);
	outb(0x04, SMBusBase + SMBHSTDATB);

	outb(0x09, SMBusBase + (SMBHSTDATB + 0x1));
	outb(0x11, SMBusBase + (SMBHSTDATB + 0x2));
	outb(0x22, SMBusBase + (SMBHSTDATB + 0x3));

	//set the control register
	outb(0x15, SMBusBase + SMBHSTCNT);
	//check the status register for busy state
	//sch_SMbus_regs ();
	temp = inb(SMBusBase + SMBHSTSTS);
	//printk(BIOS_DEBUG, "SMBus Busy.. status =%x\r\n",temp);
	//printk(BIOS_DEBUG, "SMBHSTSTS. =%x\r\n",inb(SMBusBase+SMBHSTSTS));
	do {
		temp = inb(SMBusBase + SMBHSTSTS);
		printk(BIOS_DEBUG, "SMBus Busy.. status =%x\r\n", temp);
		//sch_SMbus_regs ();
		printk(BIOS_DEBUG, "SMBHSTSTS. =%x\r\n",
		       inb(SMBusBase + SMBHSTSTS));
		if (temp > 0)
			break;
	} while (1);

	switch (temp) {
	case 1:
		printk(BIOS_DEBUG, "SMBus Success");
		break;
	default:
		printk(BIOS_DEBUG, "SMBus error %d", temp);
		break;

	}
	sch_SMbus_regs();
	printk(BIOS_DEBUG, "Command in TRansaction 1=%x\r\n\n",
	       inb(SMBusBase + SMBHSTCMD));
}
Ejemplo n.º 8
0
Archivo: commands.c Proyecto: hyper/rqd
// This callback function is to be fired when the CMD_CLEAR command is 
// received.  It should clear off any data received and stored in variables 
// and flags.  In otherwords, after this is executed, the node structure 
// should be in a predictable state.
static void cmdClear(void *base) 
{
 	node_t *node = (node_t *) base;

 	assert(node != NULL);
 	assert(node->handle >= 0);
 	
	data_clear(&node->data);
 	
 	assert(node->sysdata != NULL);
	logger(node->sysdata->logging, 3, "node:%d CLEAR", node->handle);
}
Ejemplo n.º 9
0
void
_handle_req_file_del(conn_t *conn, const ipc_req_t *req)
{
  ipc_resp_t resp;
  uuid_t uuid;
  uint16_t i = 0;
  char buf[MAXLINE] = { 0 };
  size_t buf_len = 0;
  char *item = NULL;

  ASSERT(conn != NULL && req != NULL, MSG_M_NULLPTR);

  memset(&resp, 0x0, sizeof(ipc_resp_t));
  resp.status = STATUS_ERR;
  resp.data.type = DATA_T_MSG;

  while (data_items_walk(&req->data, &item) > 0)
    {
      memset(&uuid, 0x0, sizeof(uuid_t));
      if (uuid_parse(&uuid, item) != 0)
        {
          buf_len = snprintf(buf, MAXLINE, COMMON_ERR_FMTN, MSG_I_BADUUID, item);
          data_item_add(&resp.data, buf, buf_len);
          continue;
        }
      if (db_file_del(&uuid) == 0)
        i++;
    }

  if (i != req->data.items && i != 0)
    data_item_add(&conn->errors, MSG_I_PARTREQ, 0);

  if (resp.data.items == 0)
    {
      resp.status = STATUS_OK;
      resp.data.type = DATA_EMPTY;
    }

  ipc_responce_write(conn, &resp);

  data_clear(&resp.data);
}
Ejemplo n.º 10
0
void
_handle_req_file_add(conn_t *conn, const ipc_req_t *req)
{
  ipc_resp_t resp;
  uuid_t new_uuid;
  char buf[MAXLINE];
  size_t buf_len = 0;
  uint16_t i = 0;
  char *item = NULL;

  ASSERT(conn != NULL && req != NULL, MSG_M_NULLPTR);

  memset(&resp, 0x0, sizeof(ipc_resp_t));
  resp.status = STATUS_ERR;

  while (data_items_walk(&req->data, &item) > 0)
    {
      memset(&new_uuid, 0x0, sizeof(uuid_t));
      if (db_file_add(item, &new_uuid) == 0)
        {
          buf_len = snprintf_m_uuid_file(buf, MAXLINE, &new_uuid, item);
          data_item_add(&resp.data, buf, buf_len);
          i++;
        }
    }

  if (resp.data.items > 0)
    {
      resp.status = STATUS_OK;
      resp.data.type = DATA_M_UUID_FILE;
    }

  if (i != req->data.items && i != 0)
    data_item_add(&conn->errors, MSG_I_PARTREQ, 0);

  ipc_responce_write(conn, &resp);

  data_clear(&resp.data);
}
Ejemplo n.º 11
0
Archivo: rfxd.c Proyecto: hyper/librisp
// used to clear a previously valid node.
void node_clear(node_t *node)
{
	assert(node != NULL);
	
	if (node->active == true) {
		assert(node->event.ev_base != NULL);
		event_del(&node->event);
	}
	
	assert(node->handle == INVALID_HANDLE);
	memset(&node->event, 0, sizeof(node->event));
	node->active = false;
	node->sending = false;
	assert(node->filehandle == INVALID_HANDLE);
	node->offset = 0;
	node->size = 0;
	
	expbuf_clear(&node->in);
	expbuf_clear(&node->out);
	
	data_clear(&node->data);
}
Ejemplo n.º 12
0
Archivo: show.cpp Proyecto: s12v/mtop
int main()
{
  // Инициализация глобальных переменных
  query = new char[65536];
	areaCodeNumber = 0;
	globalError = 0;

	// Инициализация генератора случайных чисел с помощью номера процесса
	init_genrand(getpid());

  // Подключение к MySQL
  connection = mysql_init(NULL);
  if(connection == NULL)
  {
    loading_error_exit(1);
  }
  if(mysql_real_connect(connection, NULL, MTOP_MYSQL_RO_USER, MTOP_MYSQL_RO_PASSWD, MTOP_MYSQL_DB, 0, NULL, 0) == NULL)
  {
    loading_error_exit(1);
  }

	// Загрузка регионов/городов
	// Загрузка данных геотаргетинга
	gi = GeoIP_open(MTOP_GEOIP_FILE, GEOIP_MEMORY_CACHE);
	if(gi == NULL)
	{
    loading_error_exit(3);
	}

	// Составляем массив соответствий areaCodeArr[AreaId] = AreaCode
	mysql_query_check(globalError, connection, "SELECT AreaId, AreaCode FROM Area;");
	result = mysql_store_result(connection);
	areaCodeNumber = mysql_num_rows(result);
	if(areaCodeNumber > 0) areaCodeArr = new int[areaCodeNumber];
	while((row = mysql_fetch_row(result)) != NULL)
	{
	  i = atoi(row[0]);
	  if(i > 0 && i < areaCodeNumber)	areaCodeArr[i] = atoi(row[1]);
	}
	mysql_free_result(result);

	// Открытие канала FIFO
	int fd = open(MTOP_FIFO_FILE, O_WRONLY | O_NONBLOCK);
	if(fd < 0)
	{
    loading_error_exit(133);
	}

  // Загрузка данных
	data_load();

	//// ПЕРЕМЕННЫЕ, необходимые для работы основного цикла

  #ifdef DEBUG
		struct timeval start_time, end_time;  // необходимо для определения времени работы основного цикла
	#endif
	struct timeval load_timeout, tmp_time;	// таймаут с предыдущей загрузки данных
	gettimeofday(&load_timeout, NULL);
	
  char *query_string = new char[1024];
  char *remote_addr = new char[50];
  char *p;
  int siteId;
  int accountId;
  int areaCodeId;
	time_t time_of_day;
	struct tm *tmbuf;

	PROFILE **profileCheckedArr;
	if(profileNum > 0) profileCheckedArr = new PROFILE*[profileNum];
	int	profileCheckedNum;

	BANNERCHECKED	*bannerCheckedArr;
	if(bannerNum) bannerCheckedArr = new BANNERCHECKED[bannerNum];
	int	bannerCheckedNum;
	int newPriority;
	int prioritySumm;

	unsigned long	rnd;
	unsigned long trafficKey;

	SITE *currentSite;
	BANNER *currentBanner;
	unsigned int bannerShowNum;

	TRAFFIC currentShow;

	int found;
	int error;

	int outputCodeType;

/////// ОСНОВНОЙ ЦИКЛ

	while(FCGI_Accept() >= 0)
	{
		#ifdef DEBUG
			printf("Content-type: text/plain\r\n\r\n");
			PrintEnv("Request environment", environ);
		#endif

    // Определение необходимости перезагрузки данных
		gettimeofday(&tmp_time, NULL);
		if(tmp_time.tv_sec - load_timeout.tv_sec > MTOP_DATA_TIMEOUT)
		{
			data_clear();										// Очистка памяти
			data_load();										// Перезагрузка данных
			gettimeofday(&load_timeout, NULL);
		}
		
		#ifdef DEBUG
			gettimeofday(&start_time, NULL);
		#endif

		// Инициализация переменных
		memset(query_string, 0, 1024);		// строка запроса
		memset(remote_addr, 0, 50);       // адрес

		p = NULL;                         // временная переменная

		siteId = 0;                       // ID сайта и аккаунта, полученные
		accountId = 0;                    // из строки запроса. Не доверять!
		areaCodeId = 0;                   // ID области (именно ID)

	  tmp_ui = 0;

		time_of_day = time(NULL);
		tmbuf = localtime(&time_of_day);  // структура с днём недели и т.п.

		for(i = 0; i < profileNum; i++)
		{ // обнуляем массив
			profileCheckedArr[i] = NULL;
		}
		profileCheckedNum = 0;

		for(i = 0; i < bannerNum; i++)
		{ // обнуляем массив
			bannerCheckedArr[i].banner = NULL;
			bannerCheckedArr[i].Priority = 0;
		}
		bannerCheckedNum = 0;

		newPriority = 0;									// временная переменная
		prioritySumm = 0;                 // сумма приоритетов подходящих баннеров

		currentSite = NULL;								// сайт, на котором происходит показ
		currentBanner = NULL;							// баннер, который показывается
		bannerShowNum = 1;								// количество баннеров, которые необходимо показать

		error = 0;                        // во время выполнения возникла какая-от ошибка
		found = 0;												// временная переменная
		outputCodeType = 0;               // тип выводимого кода (TEXT, WAP, картинка)

	  // Переносим переменную окружения QUERY_STRING в локальную переменную
	  p = getenv("QUERY_STRING");
		if(p != NULL)
		{
		  strncpy(query_string, p, 1024);
		}

		#ifdef DEBUG
		  printf("query_string = %s\n", query_string);
		#endif

	  // Выделяем тип вывода
	  // !!!!!! доработать
	  p = strtok(query_string, ";");
	  if(p != NULL) outputCodeType = atoi(p);
	  p = strtok(NULL, ";"); 									// ID аккаунта
	  if(p != NULL) siteId = atoi(p);
	  p = strtok(NULL, ";");									// ID сайта
	  if(p != NULL) accountId = atoi(p);

	  if(outputCodeType == CODE_TEXT_PHP)
	  {
		  p = strtok(NULL, ";");								// Количество баннеров для показа
		  if(p != NULL) bannerShowNum = atoi(p);
		  p = strtok(NULL, ";");								// IP-адрес, тип - int
		  if(p != NULL) tmp_ui= atoi(p);
	  }

	  // Проверка bannerShowNum in [1,MTOP_MAX_BANNER_NUM]
	  if( (bannerShowNum <= 0) || (bannerShowNum > MTOP_MAX_BANNER_NUM) )
	  {
			bannerShowNum = 1;
	  }

		#ifdef DEBUG
		  printf("outputCodeType = %d\n", outputCodeType);
		  printf("siteId         = %d\n", siteId);
		  printf("accountId      = %d\n", accountId);
		#endif

		// Определяем IP-адрес
		if(tmp_ui > 0)
		{
			ipntoa(tmp_ui, remote_addr);
		}
		else
		{
		  // Переносим переменную окружения REMOTE_ADDR в локальную переменную
		  p = getenv("REMOTE_ADDR");
			if(p != NULL)
			{
				strncpy(remote_addr, p, 49);
			}
			else
			{
				strncpy(remote_addr, MTOP_SERVER_IP, 49);
			}
		}

	  // Проверяем ID аккаунта и сайта на корректность (частично)
	  if(siteId <= 0 || accountId <= 0)
	  {
			error = 2;
	  }

		// Находим сайт, на котором происходит показ
		// Таким образом проверяем корректность siteId и accountID
		if(!error)
		{
		  // перебираем все сайты (обход списка)
			for(site = siteList; site != NULL; site = site->next)
			{
				if( (site->Id == siteId) && (site->AccountId == accountId) )
				{ // нашли сайт, устанавливаем указатель на него
					currentSite = site;
					#ifdef DEBUG
					  printf("Site found:\n");
					  currentSite->show();
					#endif
					break;
				}
			}
			if(currentSite == NULL)
			{ // не нашли сайт, ошибка
				error = 4;
			}
		}
		//

	  printf("IP (%s)\n", remote_addr);

		// Находим область (город или регион) по адресу
		if(!error)
		{
			#ifdef DEBUG
			  printf("IP (%s) ", remote_addr);
			#endif
			gir = GeoIP_record_by_addr(gi, remote_addr);
			if(gir != NULL)
			{ // нашли регион для IP
			  if(gir->region != NULL)
			  {
				  areaCodeId = atoi(gir->region);
					#ifdef DEBUG
					  printf(" FOUND. ", remote_addr);
					  printf("Country_code=%s, ", gir->country_code);
					  printf("region=%s, ", gir->region);
						printf("city=%s\n", gir->city);
					#endif
					GeoIPRecord_delete(gir);
				}
			}
		}

		// Перебираем профили (нерекурсивный обход списка)
		if(!error)
		{
			for(profile = profileList; profile != NULL; profile = profile->next)
			{ // отбор подходящего профиля
				#ifdef DEBUG
					printf("Profile:\n");
					profile->show();
				#endif

				// проверяем совпадение сайта
				if(profile->UserId == currentSite->UserId)
				{
					if(profile->OwnSites == MTOP_NET_OWNSITES_NO)
					{
						#ifdef DEBUG
							printf("MTOP_NET_OWNSITES_NO, rejecting profile:\n");
						#endif
						continue;
					}
				}

				// проверяем день недели
				if(!(dayOfWeekBitArr[tmbuf->tm_wday] & profile->DayOfWeek))
				{
					#ifdef DEBUG
						printf("DayOfWeek, rejecting profile:\n");
					#endif
					continue;
				}
	
				// проверяем время суток
				if(!(timeBitArr[tmbuf->tm_wday] & profile->Time))
				{
					#ifdef DEBUG
						printf("Time, rejecting profile:\n");
					#endif
					continue;
				}

				// Проверяем директ-таргетинг (белый список)
				if(profile->TargetingWhiteNumber > 0)
				{
				  found = 0;
				  for(i = 0; i < profile->TargetingWhiteNumber; i++)
				  {
				  	if(profile->TargetingWhite[i] == currentSite->Id)
				  	{
				  	  found = 1;
				  		break;
				  	}
				  }
				  // не найдено в белом списке - пропускаем профиль
				  if(!found) continue;
				}

				// Проверяем директ-таргетинг (черный список)
				if(profile->TargetingBlackNumber > 0)
				{
				  found = 0;
				  for(i = 0; i < profile->TargetingBlackNumber; i++)
				  {
				  	if(profile->TargetingBlack[i] == currentSite->Id)
				  	{
				  	  found = 1;
				  		break;
				  	}
				  }
				  // найдено в черном списке - пропускаем профиль
				  if(found) continue;
				}

				// Проверяем таргетинг по рубрикам
				if(profile->TargetingRubricNumber > 0)
				{
				  found = 0;
				  for(i = 0; i < profile->TargetingRubricNumber; i++)
				  {
				  	if(profile->TargetingRubric[i] == currentSite->RubricId)
				  	{
				  	  found = 1;
				  		break;
				  	}
				  }
				  // не найдено в рубриках - пропускаем профиль
				  if(!found) continue;
				}

				// Проверяем геотаргетинг
				if(profile->TargetingAreaNumber > 0)
				{
				  found = 0;
				  for(i = 0; i < profile->TargetingAreaNumber; i++)
				  {
				  	if(profile->TargetingArea[i] == areaCodeId)
				  	{
				  	  found = 1;
				  		break;
				  	}
				  }
				  // не найдено в рубриках - пропускаем профиль
				  if(!found) continue;
				}

				// добавляем в массив проверенных профилей
				profileCheckedArr[profileCheckedNum++] = profile;
			}
		}

		#ifdef DEBUG
	  printf("Selected profiles:\n");
		for(i = 0; i < profileCheckedNum; i++)
		{
		  profileCheckedArr[i]->show();
		}
		#endif

		// Перебираем баннеры и составляем массив сумм
		#ifdef DEBUG
		  printf("Total banners. bannerNum=%d\n", bannerNum);
		#endif
		if(!error)
		{
			for(banner = bannerList; banner != NULL; banner = banner->next)
			{
			  if( (banner->NetworkId == currentSite->NetworkId) && (banner->Priority > 0) )
			  {
					#ifdef DEBUG
					  printf("Banner:\n");
					  banner->show();
					#endif
			    found = 1;
			    // поиск в массиве подходящих профилей
					for(i = 0; i < profileCheckedNum; i++)
					{
					  profile = profileCheckedArr[i];
						if(banner->ProfileId == profile->Id)
						{
						  if(profile->OwnSites == MTOP_NET_OWNSITES_CHECK)
						  { // Требуется проверка URL сайта и баннера
							  if(strcmp(banner->HrefHash, currentSite->UrlHash) == 0)
							  { // URL совпадают, баннер не подходит
									found = 0;
									#ifdef DEBUG
									  printf("OwnSites == MTOP_NET_OWNSITES_CHECK, HrefHash = UrlHash, found = 0\n\n");
									#endif
							  	break;
							  }
							}
						  if( (profile->OwnSites == MTOP_NET_OWNSITES_NO) && (currentSite->UserId == profile->UserId))
						  { // Показ на своих сайтах запрещен
								#ifdef DEBUG
								  printf("MTOP_NET_OWNSITES_NO, Site->UserId = profile->UserId\n\n");
								#endif
						  	found = 0;
								break;
							}
						}
					}

					// баннер в профиле и подходит для показа
					if(found)
					{
					  // Добавляем баннер к массиву проверенных
					  newPriority = (int)(banner->Priority*200);
						bannerCheckedArr[bannerCheckedNum].banner = banner;
						bannerCheckedArr[bannerCheckedNum].Priority = prioritySumm + newPriority;
						prioritySumm += newPriority;

						#ifdef DEBUG
							printf("added banner to bannerCheckedArr[%d], ", bannerCheckedNum);
						  printf("Id: %d, ", banner->Id);
							printf("PrioritySumm: %d\n\n", prioritySumm);
						#endif

						bannerCheckedNum++;
						//
					}
				}
			}
		}

		// Цикл показов баннера
		for(j = 0; (j < bannerShowNum) && (j < MTOP_MAX_BANNER_NUM); j++)
		{
			// Если хотя бы один баннер можно показать
			if((bannerCheckedNum > 0) && (prioritySumm > 0))
			{
				rnd = genrand_int32();			// генерация случайного числа (скорость - ~10 млн. раз в сек)
				trafficKey = rnd;						// ключ для записи в базу трафика

				// Выбираем случайное целое число из интервала [0, prioritySumm-1]
				// можно попробовать заменить на (int)genrand_real2()*prioritySumm
				// т.е. rnd [0,1) * prioritySumm
				if(!error)
				{
					rnd = rnd % prioritySumm;
				}

				// определяем выпавший баннер
				if(!error)
				{
					for(i = 0; i < bannerCheckedNum; i++)
					{
						if(rnd < bannerCheckedArr[i].Priority)
						{
						  currentBanner = bannerCheckedArr[i].banner;
							break;
						}
					}
				}

				// Передача данных обработчику статистики
				if(!error)
				{
					currentShow.Type = mtop_signature_show;
					currentShow.SiteId = siteId;
					currentShow.AccountId = accountId;
					currentShow.NetworkId = currentSite->NetworkId;
					currentShow.BannerId = currentBanner->Id;
					currentShow.BannerAccountId = currentBanner->AccountId;
					currentShow.IP = ipaton(remote_addr);
					currentShow.Key = trafficKey;

				  p = getenv("HTTP_REFERER");
					if(p != NULL)
					{
					  strncpy(currentShow.Referer, p, 128);
					}

					// Находим и записываем AreaId
					for(i = 0; i < areaCodeNumber; i++)
					{
						if(areaCodeArr[i] == areaCodeId)
						{
							currentShow.AreaId = i;
							break;
						}
					}
				
					// Запись в канал
					if(write(fd, &currentShow, sizeof(TRAFFIC)) == -1)
					{
						#ifdef DEBUG
							printf("ERROR writing\n");
						#endif
					}
				}
			}
			//

			// Вывод отклика
			if((currentBanner != NULL) && !error)
			{ // баннер найден
				#ifdef DEBUG
					printf("\n-----------------\nSHOW BANNER:\n");
				  currentBanner->show();
				#endif

				switch(outputCodeType)
				{
					case CODE_IFRAME:
					{
					  if(j == 0)
					  {
							printf("Content-type: text/html\r\n\r\n");
						}
						printf("<html><head><title></title></head><body leftmargin=0 topmargin=0 marginwidth=0 marginheight=0><a href=\"http://nw.mtop.ru/go.cgi?%u;%u;%u\" target=\"_blank\"><img src=\"http://mtop.ru/i/%s\" width=%d height=%d border=0 alt=\"%s\"></a><br></body></html>\n", currentBanner->Id, siteId, trafficKey, currentBanner->File, currentSite->XSize, currentSite->YSize, currentBanner->String);
					 	break;
					}
					case CODE_TEXT:
					{
					  if(j == 0)
					  {
							printf("Content-type: application/x-javascript\r\n\r\n");
						}
						printf("document.write('<a href=\"http://nw.mtop.ru/go.cgi?%u;%u;%u\" target=\"_blank\">%s</a><br>');\r\n", currentBanner->Id, siteId, trafficKey, currentBanner->String);
					 	break;
					}
					case CODE_WAP:
					{
					  printf("Location: http://mtop.ru/i/%s\r\n\r\n", currentBanner->File);
					 	break;
					}
					case CODE_TEXT_PHP:
					{
					  if(j == 0)
					  {
							printf("Content-type: text/plain\r\n\r\n");
						}
						printf("<a href=\"http://nw.mtop.ru/go.cgi?%u;%u;%u\" target=\"_blank\">%s</a>\n", currentBanner->Id, siteId, trafficKey, currentBanner->String);
					 	break;
					}
				}
			}
			else
			{ // нет ни одного подходящего баннера или возникла ошибка
				// показываем загрушку для данной сети
			  if(j == 0)
			  {
					printf("Content-type: text/html\r\n\r\n");
				}
				if(currentSite != NULL)
				{
					#ifdef DEBUG
						printf("No banner found\n");
					#endif
					show_default_banner(currentSite->NetworkId, outputCodeType);
				}
				else
				{ // не найден даже сайт
					#ifdef DEBUG
						printf("No banner found, no site found\n");
					#endif
					show_default_banner();
				}
			}
		}
		//

		#ifdef DEBUG
			printf("Process ID: %d\n", getpid());
			gettimeofday(&end_time, NULL);
			double timediff = (end_time.tv_sec - start_time.tv_sec) + ((double)end_time.tv_usec - (double)start_time.tv_usec)/1000000;
			printf("main while{} time: %f seconds\n", timediff);
		#endif
	}

/////// ДЕИНИЦИАЛИЗАЦИЯ: закрываем соединение с MySQL, освобождаем память

  // Закываем соединение с MySQL
  mysql_close(connection);

  // Освобождаем память
	delete query;
	delete query_string;
	delete remote_addr;
	delete areaCodeArr;

	// Закрываем базу GeoIP
	GeoIP_delete(gi);

	return 0;
}