int main () { char **initialEnv = environ; int count = 0; while (FCGI_Accept() >= 0) { char *contentLength = getenv("CONTENT_LENGTH"); int len; printf("Content-type: text/html\r\n" "\r\n" "<title>FastCGI echo</title>" "<h1>FastCGI echo</h1>\n" "Request number %d, Process ID: %d<p>\n", ++count, getpid()); if (contentLength != NULL) { len = strtol(contentLength, NULL, 10); } else { len = 0; } if (len <= 0) { printf("No data from standard input.<p>\n"); } else { int i, ch; printf("Standard input:<br>\n<pre>\n"); for (i = 0; i < len; i++) { if ((ch = getchar()) < 0) { printf("Error: Not enough bytes received on standard input<p>\n"); break; } putchar(ch); } printf("\n</pre><p>\n"); } PrintEnv("Request environment", environ); PrintEnv("Initial environment", initialEnv); } /* while */ return 0; }
int main () { FCGX_Stream *in, *out, *err; FCGX_ParamArray envp; int count = 0; while (FCGX_Accept(&in, &out, &err, &envp) >= 0) { char *contentLength = FCGX_GetParam("CONTENT_LENGTH", envp); int len = 0; FCGX_FPrintF(out, "Content-type: text/html\r\n" "\r\n" "<title>FastCGI echo (fcgiapp version)</title>" "<h1>FastCGI echo (fcgiapp version)</h1>\n" "Request number %d, Process ID: %d<p>\n", ++count, getpid()); if (contentLength != NULL) len = strtol(contentLength, NULL, 10); if (len <= 0) { FCGX_FPrintF(out, "No data from standard input.<p>\n"); } else { int i, ch; FCGX_FPrintF(out, "Standard input:<br>\n<pre>\n"); for (i = 0; i < len; i++) { if ((ch = FCGX_GetChar(in)) < 0) { FCGX_FPrintF(out, "Error: Not enough bytes received on standard input<p>\n"); break; } FCGX_PutChar(ch, out); } FCGX_FPrintF(out, "\n</pre><p>\n"); } PrintEnv(out, "Request environment", envp); PrintEnv(out, "Initial environment", environ); } /* while */ return 0; }
/******************************************************************** * FUNCTION main * * STDIN is input from the HTTP server through FastCGI wrapper * (sent to ncxserver) * STDOUT is output to the HTTP server (rcvd from ncxserver) * * RETURNS: * 0 if NO_ERR * 1 if error connecting or logging into ncxserver *********************************************************************/ int main (int argc, char **argv, char **envp) { int status = 0; yang_api_profile_t yang_api_profile; /* setup global vars used across all requests */ status = yang_api_init(&yang_api_profile); if (status != OK) { printf("Content-type: text/html\r\n\r\n" "<html><head><title>YANG-API echo</title></head>" "<body><h1>YANG-API init failed</h1></body></html>\n"); } /* temp: exit on all errors for now */ while (status == OK && FCGI_Accept() >= 0) { #ifdef DEBUG_TRACE printf("Content-type: text/html\r\n\r\n" "<html><head><title>YANG-API echo</title></head>" "<body><h1>YANG-API echo</h1>\n<pre>\n"); PrintEnv("Request environment", environ); #endif status = save_environment_vars(&yang_api_profile); if (status != OK) { continue; } status = setenv("REMOTE_USER", yang_api_profile.username, 0); if (status != 0) { continue; } #ifdef DEBUG_TRACE printf("start invoke netconf-subsystem-pro\n"); #endif status = run_subsystem_ex(PROTO_ID_YANGAPI, 3, argc, argv, envp, read_yangapi_buff, send_yangapi_buff, yang_api_profile.content_length); if (status != OK) { continue; } #ifdef DEBUG_TRACE printf("\n</pre></body></html>\n"); #endif cleanup_request(&yang_api_profile); } /* while */ yang_api_cleanup(&yang_api_profile); return status; } /* main */
int main() { int n, childPid; char buf[BUF_MAX_SIZE]; char execPath[PATH_MAX_LEN]; char execCmd[CMD_MAX_LEN]; int cmdLen = 0; char* execArgv[BUF_MAX_SIZE]; int argvNum = 0; struct ExecCmd execCmdQueue[CMD_MAX_NUM]; int cmdNum = 0; chdir(WorkDir); if(remoteOption) CreateConnection(); stdoutfd = dup(STDOUT_FILENO); stderrfd = dup(STDERR_FILENO); /*** a connection come ***/ for(;;) { /*** accept ***/ if(remoteOption) { clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen); if(newsockfd < 0) { write(STDERR_FILENO, "accept error!\n", 14); exit(1); } //write(STDERR_FILENO, "accept\n", 7); /*** for remote client, stdout/stderr is client socket ***/ if(remoteOption){ dup2(newsockfd, STDOUT_FILENO); dup2(newsockfd, STDERR_FILENO); } } connectionOption = 1; //int line = 1; /*** shell start ***/ while(connectionOption) { if(welcomeMsgOption) { welcomeMsgOption = WelcomeMsg(); } //printf("%4d", line++);fflush(stdout); write(STDOUT_FILENO, "% ", 2); /*** clean & initialize variables ***/ bzero(buf, BUF_MAX_SIZE); bzero(execPath, PATH_MAX_LEN); bzero(execCmd, CMD_MAX_LEN); bzero(execArgv, sizeof(execArgv)); bzero(execCmdQueue, sizeof(execCmdQueue)); cmdNum = 0; argvNum = 0; cmdLen = 0; if(remoteOption) ReadCmdLineFromRemote(buf, &n); else ReadCmdLine(buf, &n); /*** cut input ***/ char buf2[BUF_MAX_SIZE]; strncpy(buf2, buf, n); strtok(buf2, "\n"); strtok(buf2, "\r"); /*write(STDERR_FILENO, "parse cmd line: ", 16); write(STDERR_FILENO, buf2, strlen(buf2)); write(STDERR_FILENO, "\n", 1);*/ ParsePipe(buf2, execCmdQueue, &cmdNum); int i = 0; for(; i < cmdNum; ++i) { /*** clean & initialize variables ***/ bzero(execPath, PATH_MAX_LEN); bzero(execCmd, CMD_MAX_LEN); bzero(execArgv, sizeof(execArgv)); argvNum = 0; cmdLen = 0; if(ParseCmdAndArgv(execCmdQueue[i].execCmdLine, execCmd, execArgv, &cmdLen, &argvNum) == -1) { break; } /*** select a function ***/ if(!strcmp(execCmd, "setenv")) { SetEnv(argvNum, execArgv); } else if(!strcmp(execCmd, "printenv")) { PrintEnv(); } else if(!strcmp(execCmd, "\n")) { break; } else if(!strcmp(execCmd, "exit")) { CloseAllPipe(); //ListAllPipe(); if(remoteOption) { connectionOption = 0; break; } else { return 0; } } else { /*** prepare to execute cmd ***/ int refreshOption = 0; int stdinOption = 0; int stdoutOption = 0; char* ptrNextCmdLine; if(i+1 < cmdNum) { ptrNextCmdLine = execCmdQueue[i+1].execCmdLine; } /*** | or ! or > pipe ***/ if(execCmdQueue[i].pipeType > 0) { CreatePipe(&stdoutOption, &execCmdQueue[i].pipeType, ptrNextCmdLine); SetPipePriority(ptrNextCmdLine, &cmdNum, &refreshOption, &execCmdQueue[i].pipeType); //ListAllPipe(); } /*** fork a process to execute the cmd (in child process) ***/ if( (childPid = fork()) == -1) { write(STDERR_FILENO, "fork() error.\n", 14); } else if(childPid == 0) { /*** child process ***/ if(remoteOption) close(sockfd); SetStdin(&stdinOption); SetStdoutAndStderr(&stdoutOption, &execCmdQueue[i].pipeType); Execute(execCmd, execPath, execArgv, &cmdLen); exit(0); } else { /*** parent process ***/ wait(); /*** stdout check & close ***/ if(stdoutOption == 1) { if(execCmdQueue[i].pipeType == 1 || execCmdQueue[i].pipeType == 2) { //printf("close fd[1]: %d\n", pipesTail->pipefd[1]);fflush(stdout); close(pipesTail->pipefd[1]); } else if(execCmdQueue[i].pipeType == 3 && filepipe != NULL) { //printf("close file, fd: %d\n", pipesTail->pipefd[0]);fflush(stdout); fclose(filepipe); filepipe = NULL; struct PipeStruct* tmpPtr = pipes; struct PipeStruct* tmpPrePtr; pipesTail->priority = 1; } } /*** when stdin complete, close both the r/w pipe fd (that priority==1) ***/ struct PipeStruct* ptrPipeStruct = pipes; struct PipeStruct* prePtr = NULL; while(ptrPipeStruct != NULL) { if(ptrPipeStruct->priority == 1) { //printf("close fd[0]: %d\n", ptrPipeStruct->pipefd[0]);fflush(stdout); close(ptrPipeStruct->pipefd[0]); if(ptrPipeStruct == pipes) { /*** delete the first node ***/ if(ptrPipeStruct == pipesTail) { /*** the first node is also the last node ***/ free(ptrPipeStruct); pipes = NULL; pipesTail = NULL; break; } else { pipes = ptrPipeStruct->next; free(ptrPipeStruct); ptrPipeStruct = pipes; } } else if(ptrPipeStruct == pipesTail) { /*** delete the last node ***/ prePtr->next = NULL; pipesTail = prePtr; free(ptrPipeStruct); break; } else { prePtr->next = ptrPipeStruct->next; free(ptrPipeStruct); ptrPipeStruct = prePtr->next; } } else { prePtr = ptrPipeStruct; ptrPipeStruct = ptrPipeStruct->next; } } /*** refresh the next pipe priority ***/ if(refreshOption) { pipesTail->priority = pipesTail->priority - 1; } /*** handle > pipe, end this execCmdQueue ***/ if(execCmdQueue[i].pipeType == 3) { break; } } } } RefreshPipe(); } if(remoteOption){ dup2(stdoutfd, STDOUT_FILENO); dup2(stderrfd, STDERR_FILENO); close(newsockfd); } welcomeMsgOption = 1; bzero(PATH, sizeof(PATH)); strcpy(PATH[0], "bin"); strcpy(PATH[1], "."); pathNum = 2; } if(remoteOption) close(sockfd); return 0; }
/*** cmd setenv ***/ void SetEnv(int argc, char** argv) { int regexFlags = REG_EXTENDED | REG_ICASE; regex_t preg; size_t nMatch = 1; regmatch_t pMatch[nMatch]; char* pattern = "^PATH$"; int result; if(argc < 2) { PrintEnv(); } else if(argc > 3) { write(STDERR_FILENO, "setenv: Too many arguments.\n", 28); } else if(regcomp(&preg, pattern, regexFlags) != 0) { /*** initialize Regex ***/ write(STDERR_FILENO, "Regex compile error!\n", 21); } else if( (result = regexec(&preg, argv[1], nMatch, pMatch, 0)) == 0) { /*** setenv command: PATH ***/ regfree(&preg); if(argc == 2) { /*** setenv PATH: PATH="" ***/ bzero(PATH, sizeof(PATH)); pathNum = 0; } else { /*** setenv PATH [path1:path2:...] ***/ pattern = "/"; if(regcomp(&preg, pattern, regexFlags) != 0) { /*** initialize Regex ***/ write(STDERR_FILENO, "Regex compile error!\n", 21); } else if( (result = regexec(&preg, argv[2], nMatch, pMatch, 0)) == 0) { /*** match any character has a '/' ***/ write(STDERR_FILENO, "Parameters have a character '/' !\n", 34); } else{ bzero(PATH, sizeof(PATH)); char* ptr = strtok(argv[2], ":"); strncpy(PATH[0], ptr, PATH_MAX_LEN); int i = 1; for(; (ptr = strtok(NULL, ":")) && (i < PATH_MAX_NUM); ++i) { strncpy(PATH[i], ptr, PATH_MAX_LEN); } pathNum = i; } } } else { regfree(&preg); write(STDERR_FILENO, "usage: setenv PATH [path1:path2:...]\n", 37); } return; }
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, ¤tShow, 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; }
int main(const int argc, const char* argv[]) { const char* prgm_path = FCGX_GetParam("PROGRAM_PATH", environ); if(!prgm_path) { cerr << "Unable to find program, please ensure the 'PROGRAM_PATH' variable has been set correctly." << endl; exit(1); } // load program srand(time(NULL)); rand(); Loader loader(prgm_path); loader.Load(); // ignore web applications if(!loader.IsWeb()) { cerr << "Please recompile the code to be a web application." << endl; exit(1); } #ifdef _TIMING clock_t start = clock(); #endif // locate starting class and method StackMethod* mthd = loader.GetStartMethod(); if(!mthd) { cerr << "Unable to locate the 'Request(args)' function." << endl; exit(1); } #ifdef _DEBUG cerr << "### Loaded method: " << mthd->GetName() << " ###" << endl; #endif Runtime::StackInterpreter intpr(Loader::GetProgram()); // go into accept loop... FCGX_Stream*in; FCGX_Stream* out; FCGX_Stream* err; FCGX_ParamArray envp; while(mthd && (FCGX_Accept(&in, &out, &err, &envp) >= 0)) { // execute method long* op_stack = new long[CALC_STACK_SIZE]; long* stack_pos = new long; // create request long* req_obj = MemoryManager::Instance()->AllocateObject("FastCgi.Request", op_stack, *stack_pos, false); if(req_obj) { req_obj[0] = (long)in; req_obj[1] = (long)envp; // create response long* res_obj = MemoryManager::Instance()->AllocateObject("FastCgi.Response", op_stack, *stack_pos, false); if(res_obj) { res_obj[0] = (long)out; res_obj[1] = (long)err; // set calling parameters op_stack[0] = (long)req_obj; op_stack[1] = (long)res_obj; *stack_pos = 2; // execute method intpr.Execute((long*)op_stack, (long*)stack_pos, 0, mthd, NULL, false); } else { cerr << ">>> DLL call: Unable to allocate object FastCgi.Response <<" << endl; // TODO: error return 1; } } else { cerr << ">>> DLL call: Unable to allocate object FastCgi.Request <<<" << endl; // TODO: error return 1; } #ifdef _DEBUG cout << "# final stack: pos=" << (*stack_pos) << " #" << endl; if((*stack_pos) > 0) { for(int i = 0; i < (*stack_pos); i++) { cout << "dump: value=" << (void*)(*stack_pos) << endl; } } #endif // clean up delete[] op_stack; op_stack = NULL; delete stack_pos; stack_pos = NULL; #ifdef _DEBUG PrintEnv(out, "Request environment", envp); PrintEnv(out, "Initial environment", environ); #endif } return 0; }