Exemple #1
0
/*******************************************************************
 *	從 .DIR 中讀取 POST 相關資訊
 *
 *	佈告區 & 精華區 & 信件 通用
 *******************************************************************/
int GetPostInfo(BOARDHEADER *board, POST_FILE *pf)
{
	int fd;
	time_t date;
#ifdef USE_MMAP
	FILEHEADER *fileinfo;
	int i;
#else
	FILEHEADER fileinfo;	
#endif
	char *p, board_dir[PATHLEN];
	
	/* ====== get post info from DIR_REC ====== */
	
	setdotfile(board_dir, pf->POST_NAME, DIR_REC);
	pf->total_rec = get_num_records(board_dir, FH_SIZE);

	if((pf->total_rec == 0)
	|| (p = strrchr(pf->POST_NAME, '/')) == NULL)
		return WEB_FILE_NOT_FOUND;
	xstrncpy(pf->fh.filename, p+1, STRLEN-8-12-4-4);

#if 0
	fprintf(fp_out, "[board_dir=%s, total_post=%d, pf->POST_NAME=%s, pf->fh.filename=%s]\n", board_dir, pf->total_rec, pf->POST_NAME, pf->fh.filename);
	fflush(fp_out);
#endif
	
	if ((fd = open(board_dir, O_RDWR)) < 0)
		return WEB_FILE_NOT_FOUND;

	/* seek from .DIR back is better */
	pf->num = pf->total_rec;
	
#ifdef USE_MMAP
	fileinfo = (FILEHEADER *) mmap((caddr_t) 0, 
		(size_t)(pf->total_rec*FH_SIZE), 
		(PROT_READ | PROT_WRITE), 
		MAP_SHARED, fd, (off_t) 0);

	if(fileinfo == MAP_FAILED)
	{
		sprintf(WEBBBS_ERROR_MESSAGE, "mmap failed: %s %d", 
			strerror(errno), (int)(pf->total_rec*FH_SIZE));
		close(fd);
		return WEB_ERROR;
	}
	close(fd);
	
	while(pf->num > 0)
	{
		if(!strcmp((fileinfo+pf->num-1)->filename, pf->fh.filename))
		{
			if((fileinfo+pf->num-1)->accessed & FILE_DELE)
			{
				munmap((void *)fileinfo, pf->total_rec*FH_SIZE);
				return WEB_FILE_NOT_FOUND;
			}
			break;
		}
		pf->num--;
	}
	
	if(pf->num < 1)
	{
		munmap((void *)fileinfo, pf->total_rec*FH_SIZE);
		return WEB_FILE_NOT_FOUND;
	}
	memcpy(&(pf->fh), fileinfo+pf->num-1, FH_SIZE);
	
#else
	
	if(lseek(fd, (FH_SIZE*(pf->total_rec-1)), SEEK_SET) == -1)
		return WEB_FILE_NOT_FOUND;

	while(pf->num >= 0)
	{
		if(read(fd, &fileinfo, FH_SIZE)==FH_SIZE)
		{
			if(!strcmp(fileinfo.filename, pf->fh.filename))
			{
				if(fileinfo.accessed & FILE_DELE)
				{
					close(fd);
					return WEB_FILE_NOT_FOUND;
				}
				break;
			}
			
			pf->num--;
			lseek(fd, -(FH_SIZE*2), SEEK_CUR);
		}
		else
		{
			close(fd);
			return WEB_FILE_NOT_FOUND;
		}
	}
	
#if 0
	/* search from head */
	pf->num = 0;
	while (read(fd, &fileinfo, FH_SIZE) == FH_SIZE)		
	{
		pf->num++;
		if (!strcmp(fileinfo.filename, pf->fh.filename))
		{
			if(fileinfo.accessed & FILE_DELE)
			{
				close(fd);
				return WEB_FILE_NOT_FOUND;
			}
			break;
		}
	}
#endif

	memcpy(&(pf->fh), &(fileinfo), FH_SIZE);
	
#endif	/* USE_MMAP */
	
	date = atol((pf->fh.filename) + 2);	/* get date from filename */
	xstrncpy(pf->date, ctime(&date), STRLEN);
	
	if(request_rec->HttpRequestType != GET)
	{
		/* skip find last & next post info if not HTTP_GET */
#ifdef USE_MMAP
		munmap((void *)fileinfo, pf->total_rec*FH_SIZE);
#else
		close(fd);
#endif
		return WEB_OK;
	}
	
	if(request_rec->URLParaType == MailRead 
	&& (pf->fh.accessed & FILE_READ) == FALSE)
	{
		int maxkeepmail;
		
		if (curuser.userlevel == PERM_BM) 
			maxkeepmail = SPEC_MAX_KEEP_MAIL;
		else
			maxkeepmail = MAX_KEEP_MAIL;
		
		if(curuser.userlevel != PERM_SYSOP
		&& pf->num > maxkeepmail )	/* lthuang */
		{
#ifdef USE_MMAP
			munmap((void *)fileinfo, pf->total_rec*FH_SIZE);
#else
			close(fd);
#endif
			sprintf(WEBBBS_ERROR_MESSAGE, "%s 信箱已滿 ( %d 封), 請刪除舊信後再看新信...", 
				curuser.userid, pf->total_rec);
			return WEB_ERROR;
		}

		/* set fileinfo as readed */
#ifdef USE_MMAP
		(fileinfo+pf->num-1)->accessed |= FILE_READ;
		
#else
		if (lseek(fd, -FH_SIZE, SEEK_CUR) == -1)
		{
			close(fd);
			return WEB_FILE_NOT_FOUND;
		}
		
		fileinfo.accessed |= FILE_READ;
		write(fd, &fileinfo, FH_SIZE);
#endif

	}
	
#ifdef TORNADO_OPTIMIZE
#if defined(NSYSUBBS1) || defined(NSYSUBBS3)
	if(isTORNADO && request_rec->URLParaType == PostRead)
	{
		if(pf->total_rec - pf->num > TORNADO_GET_MAXPOST)
		{
			strcpy(pf->lfname, "-1");
			strcpy(pf->nfname, "-1");
#ifdef USE_MMAP
			munmap((void *)fileinfo, pf->total_rec*FH_SIZE);
#else
			close(fd);
#endif
			return WEB_OK;
		}
	}
#endif
#endif

	/* get previous post filename */
#ifdef USE_MMAP
	for(i=pf->num-1; i>0; i--)
	{
		if(*((fileinfo+i-1)->filename) != 0x00
		&& !((fileinfo+i-1)->accessed & FILE_DELE) 
		&& !((fileinfo+i-1)->accessed & FILE_TREA))
		{
			xstrncpy(pf->lfname, (fileinfo+i-1)->filename, STRLEN-8);
			break;
		}
	}
	if(i <= 0)
		strcpy(pf->lfname, "-1");

#else
	while(1)
	{
		if(lseek(fd, -(FH_SIZE*2), SEEK_CUR) == -1)
		{
			strcpy(pf->lfname, "-1");
			break;
		}
		if(read(fd, &fileinfo, FH_SIZE)==FH_SIZE)
		{
			if( *fileinfo.filename != 0x00
			&& !(fileinfo.accessed & FILE_DELE) 
			&& !(fileinfo.accessed & FILE_TREA))
			{
            	xstrncpy(pf->lfname, fileinfo.filename, STRLEN-8);
				break;
			}
		}
	}
#endif	/* USE_MMAP */
	

	if(strcmp(pf->lfname, "-1"))
#ifdef USE_MMAP
		if((fileinfo+i-1)->accessed & FILE_HTML)
#else
		if(fileinfo.accessed & FILE_HTML)
#endif
			pf->type |= LAST_POST_IS_HTML;
		
#if 0
	fprintf(fp_out, "[file_num=%d, last_filename=%s]", pf->num, pf->lfname);
	fflush(fp_out);
#endif

	/* get next post filename */
#ifdef USE_MMAP
	for(i=pf->num+1; i<=pf->total_rec; i++)
	{
		if(*((fileinfo+i-1)->filename) != 0x00
		&& !((fileinfo+i-1)->accessed & FILE_DELE) 
		&& !((fileinfo+i-1)->accessed & FILE_TREA))
		{
			xstrncpy(pf->nfname, (fileinfo+i-1)->filename, STRLEN-8);
			break;
		}
	}
	
	if(i >= pf->total_rec+1)
		strcpy(pf->nfname, "-1");

#else
	
	if (lseek(fd, (long) (FH_SIZE * (pf->num)), SEEK_SET) == -1)
    {
		close(fd);
		return WEB_FILE_NOT_FOUND;
	}

	while(1)
    {
		if(read(fd, &fileinfo, FH_SIZE)==FH_SIZE)
       	{
			if( *fileinfo.filename != 0x00
			&& !(fileinfo.accessed & FILE_DELE) 
			&& !(fileinfo.accessed & FILE_TREA))
			{
				xstrncpy(pf->nfname, fileinfo.filename, STRLEN-8);
				break;
			}
		}
       	else
       	{
       		strcpy(pf->nfname, "-1");
       		break;
       	}
	}
#endif	/* USE_MMAP */


	if(strcmp(pf->nfname, "-1"))
#ifdef USE_MMAP
		if((fileinfo+i-1)->accessed & FILE_HTML)
#else
		if(fileinfo.accessed & FILE_HTML)
#endif
			pf->type |= NEXT_POST_IS_HTML;
	
#if 0
	fprintf(fp_out, "[next_filename=%s]", pf->nfname);
	fflush(fp_out);
#endif

#ifdef USE_MMAP
	munmap((void *)fileinfo, pf->total_rec*FH_SIZE);
#else
	close(fd);
#endif
	return WEB_OK;
}
Exemple #2
0
int main(int argc, char *argv[]) {
	char *bslash;
	VerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	GetVersionEx(&VerInfo);
	if (argc < 2) {
		show_usage();
		return -1;
	}
	hAdvapi = LoadLibrary("advapi32.dll");
	uChangeServiceConfig2 = (UCHANGESERVICECONFIG2)GetProcAddress(hAdvapi, "ChangeServiceConfig2A");
	if (!stricmp(argv[1], "install")) {
		SC_HANDLE hService, hSCManager;
		char path[MAX_PATH+1];
		char binpath[MAX_PATH+1];
		hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);

		if (!hSCManager) {
			exit(0);
		}
		GetModuleFileName(NULL,path,MAX_PATH);
		if ((bslash = strrchr(path, '\\')))
			*bslash = 0;
		
		strcpy(binpath,path);
		strcat(binpath, "\\UnrealIRCd.exe");
		hService = CreateService(hSCManager, "UnrealIRCd", "UnrealIRCd",
				 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
				 SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, binpath,
				 NULL, NULL, NULL, NULL, NULL); 
		if (hService) 
		{
			printf("UnrealIRCd NT Service successfully installed");
			if (VerInfo.dwMajorVersion >= 5) {
				SERVICE_DESCRIPTION info;
				info.lpDescription = "Internet Relay Chat Server. Allows users to chat with eachother via an IRC client.";
				uChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &info);
			}
			CloseServiceHandle(hService);
		} else
			printf("Failed to install UnrealIRCd NT Service - %s", show_error(GetLastError()));
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "uninstall")) {
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", DELETE); 
		if (DeleteService(hService)) 
			printf("UnrealIRCd NT Service successfully uninstalled");
		else
			printf("Failed to uninstall UnrealIRCd NT Service - %s", show_error(GetLastError()));
		CloseServiceHandle(hService);
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "start")) {
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_START); 
		if (StartService(hService, 0, NULL)) 
			printf("UnrealIRCd NT Service successfully started");
		else
			printf("Failed to start UnrealIRCd NT Service - %s", show_error(GetLastError()));
		CloseServiceHandle(hService);
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "stop")) {
		SERVICE_STATUS status;
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_STOP); 
		ControlService(hService, SERVICE_CONTROL_STOP, &status);
		printf("UnrealIRCd NT Service successfully stopped");
		CloseServiceHandle(hService);
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "restart")) {
		SERVICE_STATUS status;
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_STOP|SERVICE_START); 
		ControlService(hService, SERVICE_CONTROL_STOP, &status);
		if (StartService(hService, 0, NULL)) 
			printf("UnrealIRCd NT Service successfully restarted");
		CloseServiceHandle(hService);
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "rehash")) {
		SERVICE_STATUS status;
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_USER_DEFINED_CONTROL); 
		ControlService(hService, IRCD_SERVICE_CONTROL_REHASH, &status);
		printf("UnrealIRCd NT Service successfully rehashed");
	}
	else if (!stricmp(argv[1], "config")) {
		SERVICE_STATUS status;
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd",
						 SERVICE_CHANGE_CONFIG|SERVICE_START); 
		if (argc < 3) {
			show_usage();
			return -1;
		}
		if (!stricmp(argv[2], "startup")) {
			if (ChangeServiceConfig(hService, SERVICE_NO_CHANGE,
					    !stricmp(argv[3], "auto") ? SERVICE_AUTO_START
						: SERVICE_DEMAND_START, SERVICE_NO_CHANGE,
					    NULL, NULL, NULL, NULL, NULL, NULL, NULL)) 
				printf("UnrealIRCd NT Service configuration changed");
			else
				printf("UnrealIRCd NT Service configuration change failed - %s", show_error(GetLastError()));	
		}
		else if (!stricmp(argv[2], "crashrestart") && VerInfo.dwMajorVersion == 5) {
			SERVICE_FAILURE_ACTIONS hFailActions;
			SC_ACTION hAction;
			memset(&hFailActions, 0, sizeof(hFailActions));
			if (argc >= 4) {
				hFailActions.dwResetPeriod = 30;
				hFailActions.cActions = 1;
				hAction.Type = SC_ACTION_RESTART;
				hAction.Delay = atoi(argv[3])*60000;
				hFailActions.lpsaActions = &hAction;
				if (uChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, 	
						     &hFailActions))
					printf("UnrealIRCd NT Service configuration changed");
				else
					printf("UnrealIRCd NT Service configuration change failed - %s", show_error(GetLastError()));	
			}
			else {
				hFailActions.dwResetPeriod = 0;
				hFailActions.cActions = 0;
				hAction.Type = SC_ACTION_NONE;
				hFailActions.lpsaActions = &hAction;
				if (uChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS,
						     &hFailActions)) 
					printf("UnrealIRCd NT Service configuration changed");
				else
					printf("UnrealIRCd NT Service configuration change failed - %s", show_error(GetLastError()));	

				
			}
		}
		else {
			show_usage();
			return -1;
		}	
	}
	else {
		show_usage();
		return -1;
	}

		
			
}
Exemple #3
0
void 
CodeInjectionPlayer::InjectCode()
{
	if (!opts.enable_code_injection)
		return;
	else if (m_next_request_time > GetTickCount())
		return;

	// Window is opened?
	m_hwnd = FindWindow();
	if (m_hwnd == NULL) {
		m_state = PL_OFFLINE;
		return;
	}

	// Msg Window is registered? (aka plugin is running?)
	HWND msgHwnd = ::FindWindow(m_message_window_class, NULL);
	if (msgHwnd != NULL)
		return;

	m_next_request_time = GetTickCount() + 30000;

	// Get the dll path
	char dll_path[1024] = {0};
	if (!GetModuleFileNameA(hInst, dll_path, MAX_REGS(dll_path)))
		return;

	char *p = strrchr(dll_path, '\\');
	if (p == NULL)
		return;

	p++;
	*p = '\0';

	size_t len = p - dll_path;

	mir_snprintf(p, 1024 - len, "listeningto\\%s.dll", m_dll_name);

	len = strlen(dll_path);

	// File exists?
	DWORD attribs = GetFileAttributesA(dll_path);
	if (attribs == 0xFFFFFFFF || !(attribs & FILE_ATTRIBUTE_ARCHIVE))
		return;

	// Do the code injection
	unsigned long pid;
	GetWindowThreadProcessId(m_hwnd, &pid);
	HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION 
									| PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, pid);
	if (hProcess == NULL)
		return;

	char *_dll = (char *) VirtualAllocEx(hProcess, NULL, len+1, MEM_COMMIT, PAGE_READWRITE );
	if (_dll == NULL)
	{
		CloseHandle(hProcess);
		return;
	}
	WriteProcessMemory(hProcess, _dll, dll_path, len+1, NULL);

	HMODULE hKernel32 = GetModuleHandleA("kernel32");
	HANDLE hLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA");
	DWORD threadId;
	HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) hLoadLibraryA, 
										_dll, 0, &threadId);
	if (hThread == NULL)
	{
		VirtualFreeEx(hProcess, _dll, len+1, MEM_RELEASE);
		CloseHandle(hProcess);
		return;
	}
	WaitForSingleObject(hThread, INFINITE);
	CloseHandle(hThread);
	VirtualFreeEx(hProcess, _dll, len+1, MEM_RELEASE);
	CloseHandle(hProcess);
}
Exemple #4
0
int
main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  int		i;			/* Looping var */
  http_t	*http;			/* Connection to server */
  const char	*job;			/* Job name */
  int		jobid;			/* Job ID */
  int		num_dests;		/* Number of destinations */
  cups_dest_t	*dests;			/* Destinations */
  const char	*src,			/* Original queue */
		*dest;			/* New destination */


  _cupsSetLocale(argv);

  dest      = NULL;
  dests     = NULL;
  job       = NULL;
  jobid     = 0;
  num_dests = 0;
  src       = NULL;

  for (i = 1; i < argc; i ++)
    if (argv[i][0] == '-')
      switch (argv[i][1])
      {
        case 'E' : /* Encrypt */
#ifdef HAVE_SSL
	    cupsSetEncryption(HTTP_ENCRYPT_REQUIRED);

#else
            _cupsLangPrintf(stderr,
	                    _("%s: Sorry, no encryption support."),
	                    argv[0]);
#endif /* HAVE_SSL */
	    break;

        case 'h' : /* Connect to host */
	    if (argv[i][2] != '\0')
	      cupsSetServer(argv[i] + 2);
	    else
	    {
	      i ++;

	      if (i >= argc)
	      {
	        _cupsLangPuts(stderr,
		              _("Error: need hostname after \"-h\" option."));
		return (1);
              }

	      cupsSetServer(argv[i]);
	    }
	    break;

	default :
	    _cupsLangPrintf(stderr, _("lpmove: Unknown option \"%c\"."),
	                    argv[i][1]);
	    return (1);
      }
    else if (!jobid && !src)
    {
      if (num_dests == 0)
        num_dests = cupsGetDests(&dests);

      if ((job = strrchr(argv[i], '-')) != NULL &&
          cupsGetDest(argv[i], NULL, num_dests, dests) == NULL)
        jobid = atoi(job + 1);
      else if (isdigit(argv[i][0] & 255) &&
               !cupsGetDest(argv[i], NULL, num_dests, dests))
        jobid = atoi(argv[i]);
      else
        src = argv[i];
    }
    else if (dest == NULL)
      dest = argv[i];
    else
    {
      _cupsLangPrintf(stderr, _("lpmove: Unknown argument \"%s\"."), argv[i]);
      return (1);
    }

  if ((!jobid && !src) || !dest)
  {
    _cupsLangPuts(stdout, _("Usage: lpmove job/src dest"));
    return (1);
  }

  http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption());

  if (http == NULL)
  {
    _cupsLangPrintf(stderr, _("lpmove: Unable to connect to server: %s"),
		    strerror(errno));
    return (1);
  }

  return (move_job(http, src, jobid, dest));
}
Exemple #5
0
/**
 * Detect subtitle files.
 *
 * When called this function will split up the psz_name string into a
 * directory, filename and extension. It then opens the directory
 * in which the file resides and tries to find possible matches of
 * subtitles files.
 *
 * \ingroup Demux
 * \param p_this the calling \ref input_thread_t
 * \param psz_path a list of subdirectories (separated by a ',') to look in.
 * \param psz_name_org the complete filename to base the search on.
 * \param pp_slaves an initialized input item slave list to append detected subtitles to
 * \param p_slaves pointer to the size of the slave list
 * \return VLC_SUCCESS if ok
 */
int subtitles_Detect( input_thread_t *p_this, char *psz_path, const char *psz_name_org,
                      input_item_slave_t ***ppp_slaves, int *p_slaves )
{
    int i_fuzzy = var_GetInteger( p_this, "sub-autodetect-fuzzy" );
    if ( i_fuzzy == 0 )
        return VLC_EGENERIC;
    int j, i_fname_len;
    input_item_slave_t **pp_slaves = *ppp_slaves;
    int i_slaves = *p_slaves;
    char *f_fname_noext = NULL, *f_fname_trim = NULL;
    char **subdirs; /* list of subdirectories to look in */

    if( !psz_name_org )
        return VLC_EGENERIC;

    char *psz_fname = vlc_uri2path( psz_name_org );
    if( !psz_fname )
        return VLC_EGENERIC;

    /* extract filename & dirname from psz_fname */
    char *f_dir = strdup( psz_fname );
    if( f_dir == 0 )
    {
        free( psz_fname );
        return VLC_ENOMEM;
    }

    const char *f_fname = strrchr( psz_fname, DIR_SEP_CHAR );
    if( !f_fname )
    {
        free( f_dir );
        free( psz_fname );
        return VLC_EGENERIC;
    }
    f_fname++; /* Skip the '/' */
    f_dir[f_fname - psz_fname] = 0; /* keep dir separator in f_dir */

    i_fname_len = strlen( f_fname );

    f_fname_noext = malloc(i_fname_len + 1);
    f_fname_trim = malloc(i_fname_len + 1 );
    if( !f_fname_noext || !f_fname_trim )
    {
        free( f_dir );
        free( f_fname_noext );
        free( f_fname_trim );
        free( psz_fname );
        return VLC_ENOMEM;
    }

    strcpy_strip_ext( f_fname_noext, f_fname );
    strcpy_trim( f_fname_trim, f_fname_noext );

    subdirs = paths_to_list( f_dir, psz_path );
    for( j = -1; (j == -1) || ( j >= 0 && subdirs != NULL && subdirs[j] != NULL ); j++ )
    {
        const char *psz_dir = (j < 0) ? f_dir : subdirs[j];
        if( psz_dir == NULL || ( j >= 0 && !strcmp( psz_dir, f_dir ) ) )
            continue;

        /* parse psz_src dir */
        DIR *dir = vlc_opendir( psz_dir );
        if( dir == NULL )
            continue;

        msg_Dbg( p_this, "looking for a subtitle file in %s", psz_dir );

        const char *psz_name;
        while( (psz_name = vlc_readdir( dir )) )
        {
            if( psz_name[0] == '.' || !subtitles_Filter( psz_name ) )
                continue;

            char tmp_fname_noext[strlen( psz_name ) + 1];
            char tmp_fname_trim[strlen( psz_name ) + 1];
            char tmp_fname_ext[strlen( psz_name ) + 1];
            const char *tmp;
            int i_prio = 0;

            /* retrieve various parts of the filename */
            strcpy_strip_ext( tmp_fname_noext, psz_name );
            strcpy_get_ext( tmp_fname_ext, psz_name );
            strcpy_trim( tmp_fname_trim, tmp_fname_noext );

            if( !strcmp( tmp_fname_trim, f_fname_trim ) )
            {
                /* matches the movie name exactly */
                i_prio = SLAVE_PRIORITY_MATCH_ALL;
            }
            else if( (tmp = strstr( tmp_fname_trim, f_fname_trim )) )
            {
                /* contains the movie name */
                tmp += strlen( f_fname_trim );
                if( whiteonly( tmp ) )
                {
                    /* chars in front of the movie name */
                    i_prio = SLAVE_PRIORITY_MATCH_RIGHT;
                }
                else
                {
                    /* chars after (and possibly in front of)
                     * the movie name */
                    i_prio = SLAVE_PRIORITY_MATCH_LEFT;
                }
            }
            else if( j == -1 )
            {
                /* doesn't contain the movie name, prefer files in f_dir over subdirs */
                i_prio = SLAVE_PRIORITY_MATCH_NONE;
            }
            if( i_prio >= i_fuzzy )
            {
                struct stat st;
                char *path;

                size_t i_len = strlen( psz_dir );
                const char *psz_format;
                if ( i_len == 0 )
                    continue;
                if( psz_dir[i_len - 1] == DIR_SEP_CHAR )
                    psz_format = "%s%s";
                else
                    psz_format = "%s"DIR_SEP"%s";

                if( asprintf( &path, psz_format, psz_dir, psz_name ) < 0 )
                    continue;

                if( strcmp( path, psz_fname )
                 && vlc_stat( path, &st ) == 0
                 && S_ISREG( st.st_mode ) )
                {
                    msg_Dbg( p_this,
                            "autodetected subtitle: %s with priority %d",
                            path, i_prio );
                    char *psz_uri = vlc_path2uri( path, NULL );
                    input_item_slave_t *p_sub = psz_uri != NULL ?
                        input_item_slave_New( psz_uri, SLAVE_TYPE_SPU, i_prio )
                        : NULL;
                    if( p_sub )
                    {
                        p_sub->b_forced = true;
                        INSERT_ELEM( pp_slaves, i_slaves, i_slaves, p_sub );
                    }
                    free( psz_uri );
                }
                free( path );
            }
        }
        closedir( dir );
    }
    if( subdirs )
    {
        for( j = 0; subdirs[j]; j++ )
            free( subdirs[j] );
        free( subdirs );
    }
    free( f_dir );
    free( f_fname_trim );
    free( f_fname_noext );
    free( psz_fname );

    for( int i = 0; i < i_slaves; i++ )
    {
        input_item_slave_t *p_sub = pp_slaves[i];

        bool b_reject = false;
        char *psz_ext = strrchr( p_sub->psz_uri, '.' );
        if( !psz_ext )
            continue;
        psz_ext++;

        if( !strcasecmp( psz_ext, "sub" ) )
        {
            for( int j = 0; j < i_slaves; j++ )
            {
                input_item_slave_t *p_sub_inner = pp_slaves[j];

                /* check that the filenames without extension match */
                if( strncasecmp( p_sub->psz_uri, p_sub_inner->psz_uri,
                    strlen( p_sub->psz_uri ) - 3 ) )
                    continue;

                char *psz_ext_inner = strrchr( p_sub_inner->psz_uri, '.' );
                if( !psz_ext_inner )
                    continue;
                psz_ext_inner++;

                /* check that we have an idx file */
                if( !strcasecmp( psz_ext_inner, "idx" ) )
                {
                    b_reject = true;
                    break;
                }
            }
        }
        else if( !strcasecmp( psz_ext, "cdg" ) )
        {
            if( p_sub->i_priority < SLAVE_PRIORITY_MATCH_ALL )
                b_reject = true;
        }
        if( b_reject )
        {
            pp_slaves[i] = NULL;
            input_item_slave_Delete( p_sub );
        }
    }

    *ppp_slaves = pp_slaves; /* in case of realloc */
    *p_slaves = i_slaves;
    return VLC_SUCCESS;
}
Exemple #6
0
Fichier : scc.c Projet : 7ym0n/note
/*********************************************************** 
 * 功能:	得到文件扩展名
 * fname:	文件名称
 **********************************************************/
char *get_file_ext(char *fname)
{
	char *p;
	p = strrchr(fname,'.');
	return p+1;
}
Exemple #7
0
int main (int argc, char **argv)
{
    int				k;
    int				fd;
    uint32_t			driverVersion = 0;
    uint32_t			numAdapters;
    int				startSelfTest = -1;
    int				healthCheck = 0;
    int				checkBattery = 1;
    char			*device = MEGA_DEVICE;
    struct query_object {
	int			    adapter;
	int			    channel;
	int			    id;
    }				*object = NULL;
    int				numObjects = 0;
    uint8_t			readLog[LOG_PAGE_MAX] = { 0, };
    int				reportPhysical = 1;
    int				showVersion = 0;
#ifdef	MEGA_SAS_CTL
    int				sas = 1;
#else
    int				sas = 0;
#endif

    if ((me = strrchr (argv[0], '/')))
	++me;
    else
	me = argv[0];

    if (argc > 1)
    {
	if ((object = (struct query_object *) malloc ((argc - 1) * sizeof (*object))) == NULL)
	{
	    perror ("malloc");
	    return 1;
	}
    }

    for (k = 1; k < argc; ++k)
    {
	if (argv[k][0] == '-')
	{
	    char		*s;

	    for (s = argv[k] + 1; *s; ++s)
	    {
		if (*s == 'v')
		{
		    ++verbosity;
		    continue;
		}
		if (*s == 'e')
		{
		    /* read error log pages */
		    readLog[0x02] = 1;	/* write errors */
		    readLog[0x03] = 1;	/* read errors */
		    readLog[0x05] = 1;	/* read errors */
		    continue;
		}
		if (*s == 's')
		{
		    /* read self test log page */
		    readLog[0x10] = 1;
		    continue;
		}
		if (*s == 't')
		{
		    /* read temperature log page */
		    readLog[0x0d] = 1;
		    continue;
		}
		if (*s == 'l')
		{
		    /* read specific log page */
		    char		*t;
		    unsigned long	u;

		    if ((++k) >= argc)
			usage (2, "no log page specified");
		    u = strtoul (argv[k], &t, 0);
		    if (*t)
			usage (2, "invalid log page \"%s\"", argv[k]);
		    if (u >= sizeof (readLog) / sizeof (readLog[0]))
			usage (2, "log page out of range: \"%s\"", argv[k]);
		    readLog[u] = 1;
		    continue;
		}
		if (*s == 'D')
		{
		    /* specify device file */
		    if ((++k) >= argc)
			usage (2, "no device specified");
		    device = argv[k];
		    continue;
		}
		if (*s == 'p')
		{
		    reportPhysical = 0;;
		    continue;
		}
		if (*s == 'B')
		{
		    /* skip battery check */
		    checkBattery = 0;
		    continue;
		}
		if (*s == 'H')
		{
		    /* perform adapter health check */
		    ++healthCheck;
		    continue;
		}
		if (*s == 'T')
		{
		    /* start self test */
		    if ((++k) >= argc)
			usage (2, "must specify short or long self-test");
		    if (!strcmp (argv[k], "short"))
			startSelfTest = SCSI_SELFTEST_BACKGROUND_SHORT;
		    else if (!strcmp (argv[k], "long"))
			startSelfTest = SCSI_SELFTEST_BACKGROUND_LONG;
		    else
			usage (2, "invalid self test: \"%s\"; must specify short or long", argv[k]);
		    continue;
		}
		else if ((*s == '?') || (*s == 'h'))
		    usage (0, NULL);
		else if (*s == 'V')
		{
		    ++showVersion;
		    continue;
		}
		usage (2, "invalid flag \"%s\"", s);
	    }
	}
	else
	{
	    char		*s;
	    char		*t;
	    unsigned long	l;

	    s = argv[k];
	    object[numObjects].adapter = -1;
	    object[numObjects].channel = -1;
	    object[numObjects].id = -1;

	    if (*s)
	    {
		if (tolower (*s) != 'a')
		    usage (2, "invalid specifier \"%s\"", argv[k]);
		++s;
		l = strtoul (s, &t, 10);
		if (s == t)
		    usage (2, "invalid specifier \"%s\"", argv[k]);
#ifndef	MEGA_SAS_CTL
		if (l >= MAX_CONTROLLERS)
		    usage (2, "adapter out of range: \"%s\"", argv[k]);
#endif
		object[numObjects].adapter = l;
		s = t;
	    }

	    if (*s)
	    {
		if (tolower (*s) != (sas ? 'e' : 'c'))
		    usage (2, "invalid specifier \"%s\"", argv[k]);
		++s;
		l = strtoul (s, &t, 10);
		if (s == t)
		    usage (2, "invalid specifier \"%s\"", argv[k]);
#ifndef	MEGA_SAS_CTL
		if (l >= MAX_MBOX_CHANNELS)
		    usage (2, "channel out of range: \"%s\"", argv[k]);
#endif
		object[numObjects].channel = l;
		s = t;
	    }

	    if (*s)
	    {
		if (tolower (*s) != (sas ? 's' : 't'))
		    usage (2, "invalid specifier \"%s\"", argv[k]);
		++s;
		l = strtoul (s, &t, 10);
		if (s == t)
		    usage (2, "invalid specifier \"%s\"", argv[k]);
#ifndef	MEGA_SAS_CTL
		if (l > MAX_MBOX_TARGET)
		    usage (2, "target out of range: \"%s\"", argv[k]);
#endif
		object[numObjects].id = l;
		s = t;
	    }

	    ++numObjects;
	}
    }

    if (showVersion)
    {
	if (verbosity)
	    fprintf (stdout, "%s: version %s by Jefferson Ogata\n", me, version);
	else
	    fprintf (stdout, "%s\n", version);
	return 0;
    }

    if (healthCheck)
    {
	int			set = 0;

	for (k = 0; k < numObjects; ++k)
	    if ((object[k].channel >= 0) || (object[k].id >= 0))
		usage (2, "for health check, must specify adapter only");
	for (k = 0; k < sizeof readLog / sizeof (readLog[0]); ++k)
	    if (readLog[k])
	    {
		set = 1;
		break;
	    }
	if (set == 0)
	{
	    /* No specific log pages requested; check read/write/verify errors and temperature. */
	    readLog[0x02] = 1;
	    readLog[0x03] = 1;
	    readLog[0x05] = 1;
	    readLog[0x0d] = 1;
	}
    }

    if ((fd = open (device, O_RDONLY)) < 0)
    {
	fprintf (stderr, "unable to open device %s: %s\n", device, strerror (errno));
	return 1;
    }

#ifndef	MEGA_SAS_CTL
    if (megaGetDriverVersion (fd, &driverVersion) < 0)
    {
	fprintf (stderr, "unable to determine megaraid driver version: %s\n", megaErrorString ());
	return 1;
    }

    if (driverVersion < MEGA_MIN_VERSION)
    {
	fprintf (stderr, "megaraid driver version %x too old.\n", driverVersion);
	return 1;
    }
#endif

    if (megaGetNumAdapters (fd, &numAdapters, sas) < 0)
    {
	fprintf (stderr, "unable to find any adapters: %s\n", megaErrorString ());
	return 1;
    }

    if (verbosity > 2)
	fprintf (stderr, "%u adapters, driver version %08x\n\n", numAdapters, driverVersion);

    /* Default to enumerating all adapters. */
    if (numObjects == 0)
    {
	if (object)
	    free (object);
	if ((object = (struct query_object *) malloc (numAdapters * sizeof (*object))) == NULL)
	{
	    perror ("malloc");
	    return 1;
	}
	for (k = 0; k < numAdapters; ++k)
	{
	    object[k].adapter = k;
	    object[k].channel = -1;
	    object[k].id = -1;
	}
	numObjects = k;
    }

    for (k = 0; k < numObjects; ++k)
    {
	int				adapter = object[k].adapter;
	int				channel = object[k].channel;
	int				id = object[k].id;
	char				name[32];
	struct adapter_config		*a;
	uint32_t			c;
	uint32_t			i;
	int				j;

	if (id >= 0)
	    snprintf (name, sizeof name, "a%u%c%u%c%u", adapter, sas ? 'e' : 'c', channel, sas ? 's' : 't', id);
	else if (channel >= 0)
	    snprintf (name, sizeof name, "a%u%c%u", adapter, sas ? 'e' : 'c', channel);
	else
	    snprintf (name, sizeof name, "a%u", adapter);

	if (adapter >= numAdapters)
	{
	    fprintf (stderr, "%s: no such adapter\n", name);
	    continue;
	}

	if ((a = getAdapterConfig (fd, adapter, sas)) == NULL)
	{
	    fprintf (stderr, "%s: cannot read adapter configuration: %s\n", name, megaErrorString ());
	    break;
	}

	if (healthCheck)
	{
	    int				adapterReported = 0;
	    struct logical_drive_info	*l;

	    if (checkBattery && (!a->battery.healthy))
	    {
		if (!(adapterReported++))
		    describeAdapter (stdout, a, verbosity);
	    }

#ifndef	MEGA_SAS_CTL
	    /* Scan all physical devices. */
	    for (c = 0; c < a->num_channels; ++c)
	    {
		for (i = 0; i <= MAX_MBOX_TARGET; ++i)
		{
		    uint8_t			target = (a->channel[c] << 4) | i;

		    (void) getPhysicalDriveInfo (a, target, 1);
		}
	    }
#endif

	    for (i = 0, l = a->logical; i < a->num_logicals; ++i, ++l)
	    {
		int				reportDrive = 0;

		if ((l->state != LdStateOptimal) && (l->state != LdStateDeleted))
		    ++reportDrive;

		if (reportDrive)
		{
		    if (!(adapterReported++))
			describeAdapter (stdout, a, verbosity);
		    describeLogicalDrive (stdout, l, verbosity);
		}
	    }

	    for (i = 0; i < a->num_physicals; ++i)
	    {
		struct physical_drive_info	*d = a->physical_list[i];
		int				reportDrive = 0;
		struct log_page_list		*log;

		if (d == NULL)
		    break;
		if (!(d->present))
		    continue;

//describePhysicalDrive (stdout, d, verbosity);

		/* check for drive problems */
		if ((d->state == PdStateRebuild) || (d->span && (d->state == PdStateFailed)))
		    ++reportDrive;
		if (d->media_errors)
		    ++reportDrive;
		if (d->predictive_failures)
		    ++reportDrive;

		/* check interesting log pages */
		for (j = 0; j < sizeof (readLog) / sizeof (readLog[0]); ++j)
		{
		    if (readLog[j] == 0)
			continue;

		    if ((log = getDriveLogPage (d, j)) == NULL)
			continue;

		    if (log->log.problem)
			++reportDrive;
		}

		if (reportDrive)
		{
		    if (!(adapterReported++))
			describeAdapter (stdout, a, verbosity);
		    describePhysicalDrive (stdout, d, verbosity);
		    for (j = 0; j < sizeof (readLog) / sizeof (readLog[0]); ++j)
		    {
			if (readLog[j] == 0)
			    continue;

			if ((log = getDriveLogPage (d, j)) == NULL)
			    continue;

			dumpLogPage (stdout, &log->log, NULL, 0, verbosity);
		    }
		}
	    }
	    continue;
	}

	if (channel >= 0)
	{
	    for (c = 0; c < a->num_channels; ++c)
		if (channel == a->channel[c])
		    break;
	    if (c >= a->num_channels)
	    {
		fprintf (stderr, "%s: no such channel\n", name);
		continue;
	    }
	}

	if ((channel < 0) && (id < 0))
	{
	    struct logical_drive_info	*l;
	    int				x;

	    describeAdapter (stdout, a, verbosity);

#ifndef	MEGA_SAS_CTL
	    /* Scan all physical devices. */
	    for (c = 0; c < a->num_channels; ++c)
	    {
		for (i = 0; i <= MAX_MBOX_TARGET; ++i)
		{
		    uint8_t			target = (a->channel[c] << 4) | i;

		    (void) getPhysicalDriveInfo (a, target, 1);
		}
	    }
#endif

	    for (i = 0, l = a->logical; i < a->num_logicals; ++i, ++l)
		describeLogicalDrive (stdout, l, verbosity);

	    x = 0;

	    for (i = 0; i < a->num_physicals; ++i)
	    {
		struct physical_drive_info	*d = a->physical_list[i];

		if (d == NULL)
		    break;
		if (!(d->present))
		    continue;

		if (d->state == PdStateHotspare)
		{
		    if (x == 0)
			fprintf (stdout, "hot spares  :");
		    else if ((x % 8) == 0)
			fprintf (stdout, "            :");
		    fprintf (stdout, "  %-8s", d->name);
		    if (((++x) % 8) == 0)
			fprintf (stdout, "\n");
		}
	    }
	    if (x % 8)
		fprintf (stdout, "\n");

	    x = 0;
	    for (i = 0; i < a->num_physicals; ++i)
	    {
		struct physical_drive_info	*d = a->physical_list[i];

		if (d == NULL)
		    break;
		if (!(d->present))
		    continue;

		if ((!(d->span)) && (d->state != PdStateHotspare))
		{
		    if (x == 0)
			fprintf (stdout, "unconfigured:");
		    else if ((x % 8) == 0)
			fprintf (stdout, "            :");
		    fprintf (stdout, "  %-8s", d->name);
		    if (((++x) % 8) == 0)
			fprintf (stdout, "\n");
		}
	    }
	    if (x % 8)
		fprintf (stdout, "\n");
	}

	for (c = 0; c < a->num_channels; ++c)
	{
	    if ((channel >= 0) && (channel != a->channel[c]))
		continue;

#ifndef	MEGA_SAS_CTL
	    if (id >= 0)
	    {
		uint8_t			target = (a->channel[c] << 4) | id;
		(void) getPhysicalDriveInfo (a, target, 1);
	    }
	    else
	    {
		/* Scan all devices on this channel. */
		for (i = 0; i <= MAX_MBOX_TARGET; ++i)
		{
		    uint8_t			target = (a->channel[c] << 4) | i;

		    (void) getPhysicalDriveInfo (a, target, 1);
		}
	    }
#endif

	    for (i = 0; i < a->num_physicals; ++i)
	    {
		struct physical_drive_info	*d = a->physical_list[i];

		if (d == NULL)
		    break;

		if (d->channel != a->channel[c])
		    continue;

		if ((id >= 0) && (id != d->id))
		    continue;

		if (startSelfTest >= 0)
		{
		    uint8_t		diag[256];

		    memset (diag, 0, sizeof diag);
		    if (megaScsiSendDiagnostic (&a->target, d->target, diag, sizeof diag, startSelfTest, 0, 0) < 0)
			fprintf (stderr, "self test: %s\n", megaErrorString ());
		}

		if (reportPhysical)
		{
		    describePhysicalDrive (stdout, d, verbosity);
		    for (j = 0; j < sizeof (readLog) / sizeof (readLog[0]); ++j)
		    {
			struct log_page_list	*log;

			if (readLog[j] == 0)
			    continue;

			if ((log = getDriveLogPage (d, j)) == NULL)
			    continue;

			dumpLogPage (stdout, &log->log, &log->buf, sizeof (log->buf), verbosity);
		    }
		}
	    }
	}

	fprintf (stdout, "\n");
    }

    return 0;
}
Exemple #8
0
csLibraryHandle csLoadLibrary (const char* iName)
{
  csLibraryHandle handle;
  DWORD errorCode;

  CS_ALLOC_STACK_ARRAY (char, dllPath, strlen (iName) + 5);
  strcpy (dllPath, iName);
  char* dot = strrchr (dllPath, '.');
  if ((!dot) || (strcasecmp (dot, ".dll") != 0))
  {
    if (dot && (strcasecmp (dot, ".csplugin") == 0))
    {
      strcpy (dot, ".dll");
    }
    else
    {
      strcat (dllPath, ".dll");
    }
  }

  handle = LoadLibraryEx (dllPath, 0, LOADLIBEX_FLAGS);
  errorCode = GetLastError();

#ifdef __CYGWIN__
 // A load attempt might fail if the DLL depends implicitly upon some other
 // DLLs which reside in the Cygwin /bin directory.  To deal with this case, we
 // add the Cygwin /bin directory to the PATH environment variable and retry.
 if (handle == 0)
 {
   char *OLD_PATH = new char[4096];
   char *DLLDIR = new char[1024];
   GetEnvironmentVariable("PATH", OLD_PATH, 4096);
   if (cygwin_conv_to_win32_path ("/bin/",DLLDIR))
   {
     ErrorMessages.Push(
       "LoadLibraryEx() '/bin/' Cygwin/Win32 path conversion failed.");
     delete[] DLLDIR;
     delete[] OLD_PATH;
     return 0;
   }
   SetEnvironmentVariable("PATH", DLLDIR);
   handle = LoadLibraryEx (dllPath, 0, LOADLIBEX_FLAGS);
   errorCode = GetLastError();
   SetEnvironmentVariable("PATH", OLD_PATH);
   delete[] DLLDIR;
   delete[] OLD_PATH;
 }
#endif

  if (handle == 0)
  {
    char *buf = cswinGetErrorMessage (errorCode);
    csString s;
    s << "LoadLibraryEx(" << dllPath << ") error " << (int)errorCode << ": "
      << buf;
    ErrorMessages.Push (s);
    delete[] buf;
    return 0;
  }

  typedef const char* (*pfnGetPluginCompiler)();
  pfnGetPluginCompiler get_plugin_compiler = 
    (pfnGetPluginCompiler) csGetLibrarySymbol (handle, "plugin_compiler");
  if (!get_plugin_compiler)
  {
    csString s;
    s << dllPath << ": DLL does not export \"plugin_compiler\".";
    ErrorMessages.Push (s);
    FreeLibrary ((HMODULE)handle);
    return 0;
  }
  const char* plugin_compiler = get_plugin_compiler();
  if (strcmp(plugin_compiler, CS_COMPILER_NAME) != 0)
  {
    csString s;
    s << dllPath << ": plugin compiler does not match application compiler: "
      << plugin_compiler << " != " CS_COMPILER_NAME;
    ErrorMessages.Push (s);
    FreeLibrary ((HMODULE)handle);
    return 0;
  }

  return handle;
}
Exemple #9
0
static int statserv_sc_main(yaz_sc_t s, int argc, char **argv)
{
    char sep;
#ifdef WIN32
    /* We need to initialize the thread list */
    ThreadList_Initialize();
/* WIN32 */
#endif


#ifdef WIN32
    sep = '\\';
#else
    sep = '/';
#endif
    if ((me = strrchr(argv[0], sep)))
        me++; /* get the basename */
    else
        me = argv[0];
    programname = argv[0];

    if (control_block.options_func(argc, argv))
        return 1;

    xml_config_open();
    
    xml_config_bend_start();

#ifdef WIN32
    xml_config_add_listeners();

    yaz_log(log_server, "Starting server %s", me);
    if (!pListener && *control_block.default_listen)
        add_listener(control_block.default_listen, 0);
#else
/* UNIX */
    if (control_block.inetd)
        inetd_connection(control_block.default_proto);
    else
    {
        static int hand[2];
        if (control_block.background)
        {
            /* create pipe so that parent waits until child has created
               PID (or failed) */
            if (pipe(hand) < 0)
            {
                yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
                return 1;
            }
            switch (fork())
            {
            case 0: 
                break;
            case -1:
                return 1;
            default:
                close(hand[1]);
                while(1)
                {
                    char dummy[1];
                    int res = read(hand[0], dummy, 1);
                    if (res < 0 && yaz_errno() != EINTR)
                    {
                        yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
                        break;
                    }
                    else if (res >= 0)
                        break;
                }
                close(hand[0]);
                _exit(0);
            }
            /* child */
            close(hand[0]);
            if (setsid() < 0)
                return 1;
            
            close(0);
            close(1);
            close(2);
            open("/dev/null", O_RDWR);
            if (dup(0) == -1)
                return 1;
            if (dup(0) == -1)
                return 1;
        }
        xml_config_add_listeners();

        if (!pListener && *control_block.default_listen)
            add_listener(control_block.default_listen, 0);
        
        if (!pListener)
            return 1;

        if (*control_block.pid_fname)
        {
            FILE *f = fopen(control_block.pid_fname, "w");
            if (!f)
            {
                yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s", 
                        control_block.pid_fname);
                exit(0);
            }
            fprintf(f, "%ld", (long) getpid());
            fclose(f);
        }
        
        if (control_block.background)
            close(hand[1]);


        yaz_log(log_server, "Starting server %s pid=%ld", programname, 
                (long) getpid());
#if 0
        sigset_t sigs_to_block;
        
        sigemptyset(&sigs_to_block);
        sigaddset(&sigs_to_block, SIGTERM);
        pthread_sigmask(SIG_BLOCK, &sigs_to_block, 0);
        /* missing... */
#endif
        if (control_block.dynamic)
            signal(SIGCHLD, catchchld);
    }
    signal(SIGPIPE, SIG_IGN);
    signal(SIGTERM, sigterm);
    if (*control_block.setuid)
    {
        struct passwd *pw;
        
        if (!(pw = getpwnam(control_block.setuid)))
        {
            yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
            return(1);
        }
        if (setuid(pw->pw_uid) < 0)
        {
            yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
            exit(1);
        }
    }
/* UNIX */
#endif
    if (pListener == NULL)
        return 1;
    if (s)
        yaz_sc_running(s);
    yaz_log(YLOG_DEBUG, "Entering event loop.");
    return iochan_event_loop(&pListener);
}
Exemple #10
0
csRef<iString> csGetPluginMetadata (const char* fullPath, 
				    csRef<iDocument>& metadata)
{
  // @@@ There's a small inefficiency here.  This function, when given a
  // filename of <blah>.dll or <blah>.csplugin, first checks <blah>.dll for
  // embedded metadata and then for the existence of a <blah>.csplugin file.
  // However, the csScanPluginDir() function already emits a <blah>.csplugin
  // file name when such a file was found, <blah>.dll otherwise.  This
  // information can probably be reused.

  CS_ALLOC_STACK_ARRAY (char, dllPath, strlen (fullPath) + 5);
  strcpy (dllPath, fullPath);
  char* dot = strrchr (dllPath, '.');

  bool isCsPlugin = (dot && (strcasecmp (dot, ".csplugin") == 0));
  if (!dot || isCsPlugin || strcasecmp (dot, ".dll") != 0)
  {
    if (isCsPlugin)
      strcpy (dot, ".dll");
    else
      strcat (dllPath, ".dll");
  }

  csRef<iString> result;
  metadata = 0;

#if defined(CS_EMBED_PLUGIN_META)
  result = InternalGetPluginMetadata (dllPath, metadata);
#endif

  // Check whether a .csplugin file exists as well
  // @@@ This makes the assumption that such might only exists if this function
  // was called with a <blah>.csplugin filename.
  if (isCsPlugin)
  {
    csPhysicalFile file (fullPath, "rb");

    if (file.GetStatus() == VFS_STATUS_OK)
    {
      if (metadata.IsValid())
      {
	csString errstr;
	errstr.Format ("'%s' contains embedded metadata, "
	  "but external '%s' exists as well. Ignoring the latter.",
	  dllPath, fullPath);
	result.AttachNew (new scfString (errstr));
      }
      else
      {
        csRef<iDocumentSystem> docsys =
	  csPtr<iDocumentSystem>(new csTinyDocumentSystem ());
	csRef<iDocument> doc = docsys->CreateDocument();

	char const* errmsg = doc->Parse (&file, true);
	if (errmsg == 0)	// Parse successful.
	  metadata = doc;
	else			// Parse failed.
	{
	  csString errstr;
	  errstr.Format ("Error parsing metadata from '%s': %s",
	    fullPath, errmsg);
	  result.AttachNew (new scfString (errstr));
	}
      }
    }
  }

  return result;
}
Exemple #11
0
void InternalScanPluginDir (iStringArray*& messages,
			    const char* dir, 
			    csRef<iStringArray>& plugins,
			    bool recursive)
{
  csStringHash files;
  csStringHash dirs;

  csString filemask;

  // The directory sometimes has a trailing path separator attached.
  if (!strlen(dir) || dir[strlen(dir)-1] == CS_PATH_SEPARATOR)
      filemask << dir  << "*.*";
  else
      filemask << dir << CS_PATH_SEPARATOR << "*.*";

  WIN32_FIND_DATA findData;
  HANDLE hSearch = FindFirstFile (filemask, &findData);
  if (hSearch != INVALID_HANDLE_VALUE)
  {
    do
    {
      if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
	/*
	  instead of processing them immediately, first a list of
	  directories is filled.
	 */
	if (recursive && (strcmp (findData.cFileName, ".") != 0)
	  && (strcmp (findData.cFileName, "..") != 0))
	{
	  // Add file names in lower case, as Win32 doesn't care about FS case.
	  AddLower (dirs, findData.cFileName);
	}
      }
      else
      {
	/*
	  instead of processing them immediately, first a list of
	  plugin files is created.
	 */
	char* ext = strrchr (findData.cFileName, '.');
        if (ext && ((strcasecmp (ext, ".dll") == 0) || 
	  (strcasecmp (ext, ".csplugin") == 0)))
	{
	  AddLower (files, findData.cFileName);
	}
      }
    }
    while (FindNextFile (hSearch, &findData));
    FindClose (hSearch);
  }
  else
  {
    DWORD errorCode = GetLastError();

    /*
      The plugin paths list also contains non-existent entries -
      don't emit an error for those.
     */
    if (errorCode != ERROR_PATH_NOT_FOUND)
    {
      AppendWin32Error ("FindFirst() call failed",
	errorCode,
	messages);
    }
  }

  // Now go over all the files.  This way files in a dir will have precedence
  // over files a subdir.
  {
    csStringHash::GlobalIterator fileIt(files.GetIterator());
    csString fullPath;

    csRef<iString> msg;

    while (fileIt.HasNext())
    {
      csStringID id = fileIt.Next();

      const char* fileName = files.Request (id);

      const char* ext = strrchr (fileName, '.');
      // ignore .csplugins, there are checked explicitly.
      if ((strcasecmp (ext, ".dll") == 0))
      {
	fullPath.Clear();
	// The directory sometimes has a trailing path separator attached.
	if (!strlen(dir) || dir[strlen(dir)-1] == CS_PATH_SEPARATOR)
	  fullPath << dir << fileName;
	else
	  fullPath << dir << CS_PATH_SEPARATOR << fileName;

	/*
	  Check whether the DLL has a companion .csplugin.
	 */
	char cspluginFile [MAX_PATH + 10];

	strcpy (cspluginFile, fileName);
	char* dot = strrchr (cspluginFile, '.');
	strcpy (dot, ".csplugin");

	csStringID cspID = files.Request (cspluginFile);
	if (cspID != csInvalidStringID)
	{
	  char cspluginPath [MAX_PATH + 10];

	  strcpy (cspluginPath, fullPath);
	  char* dot = strrchr (cspluginPath, '.');
	  strcpy (dot, ".csplugin");

          plugins->Push (cspluginPath);
	}
	else
	{
          plugins->Push (fullPath);
	}
      }
    }

    // release some memory.
    files.Clear();
  }
  {
    csStringHash::GlobalIterator dirIt(dirs.GetIterator());
    csString fullPath;

    while (dirIt.HasNext())
    {
      csStringID id = dirIt.Next();

      fullPath.Clear();
      fullPath << dir << CS_PATH_SEPARATOR << dirs.Request (id);

      iStringArray* subdirMessages = 0;
      InternalScanPluginDir (subdirMessages, fullPath, plugins,
	recursive);
      
      if (subdirMessages != 0)
      {
	for (size_t i = 0; i < subdirMessages->GetSize (); i++)
	{
	  AppendStrVecString (messages, subdirMessages->Get (i));
	}

	subdirMessages->DecRef();
      }
    }
  }
}
Exemple #12
0
int
main(int argc, char **argv)
{
	pdf_cmap *cmap;
	fz_error error;
	fz_stream *fi;
	FILE *fo;
	char name[256];
	char *realname;
	int i, k;
	int fd;

	if (argc < 3)
	{
		fprintf(stderr, "usage: cmapdump output.c lots of cmap files\n");
		return 1;
	}

	fo = fopen(argv[1], "wb");
	if (!fo)
	{
		fprintf(stderr, "cmapdump: could not open output file '%s'\n", argv[1]);
		return 1;
	}

	fprintf(fo, "#include \"fitz.h\"\n");
	fprintf(fo, "#include \"mupdf.h\"\n");
	fprintf(fo, "\n");

	for (i = 2; i < argc; i++)
	{
		realname = strrchr(argv[i], '/');
		if (!realname)
			realname = strrchr(argv[i], '\\');
		if (realname)
			realname ++;
		else
			realname = argv[i];

		if (strlen(realname) > (sizeof name - 1))
		{
			fprintf(stderr, "cmapdump: file name too long\n");
			return 1;
		}

		strcpy(name, realname);
		clean(name);

		fd = open(argv[i], O_BINARY | O_RDONLY, 0666);
		if (fd < 0)
		{
			fz_throw("cmapdump: could not open input file '%s'\n", argv[i]);
			return 1;
		}

		fi = fz_openfile(fd);

		error = pdf_parsecmap(&cmap, fi);
		if (error)
		{
			fz_catch(error, "cmapdump: could not parse input cmap '%s'\n", argv[i]);
			return 1;
		}

		fprintf(fo, "/* %s */\n\n", cmap->cmapname);

		fprintf(fo, "static const pdf_range pdf_cmap_%s_ranges[] =\n{\n", name);
		if (cmap->rlen == 0)
		{
			fprintf(fo, "\t/* dummy entry for non-c99 compilers */\n");
			fprintf(fo, "\t{ 0x0, 0x0, PDF_CMAP_RANGE, 0 }\n");
		}
		for (k = 0; k < cmap->rlen; k++)
		{
			fprintf(fo, "\t{ 0x%04x, 0x%04x, %s %d },\n",
				cmap->ranges[k].low, cmap->ranges[k].high,
				flagtoname(cmap->ranges[k].flag),
				cmap->ranges[k].offset);
		}
		fprintf(fo, "};\n\n");

		if (cmap->tlen == 0)
		{
			fprintf(fo, "static const unsigned short pdf_cmap_%s_table[1] = { 0 };\n\n", name);
		}
		else
		{
			fprintf(fo, "static const unsigned short pdf_cmap_%s_table[%d] =\n{",
				name, cmap->tlen);
			for (k = 0; k < cmap->tlen; k++)
			{
				if (k % 8 == 0)
					fprintf(fo, "\n\t");
				fprintf(fo, "%d,", cmap->table[k]);
			}
			fprintf(fo, "\n};\n\n");
		}

		fprintf(fo, "pdf_cmap pdf_cmap_%s =\n", name);
		fprintf(fo, "{\n");
		fprintf(fo, "\t-1, ");
		fprintf(fo, "\"%s\", ", cmap->cmapname);
		fprintf(fo, "\"%s\", nil, ", cmap->usecmapname);
		fprintf(fo, "%d,\n", cmap->wmode);

		fprintf(fo, "\t%d, /* codespace table */\n", cmap->ncspace);
		fprintf(fo, "\t{\n");

		if (cmap->ncspace == 0)
		{
			fprintf(fo, "\t/* dummy entry for non-c99 compilers */\n");
			fprintf(fo, "\t{ 0, 0x0, 0x0 },\n");
		}
		for (k = 0; k < cmap->ncspace; k++)
		{
			fprintf(fo, "\t\t{ %d, 0x%04x, 0x%04x },\n",
				cmap->cspace[k].n, cmap->cspace[k].low, cmap->cspace[k].high);
		}
		fprintf(fo, "\t},\n");

		fprintf(fo, "\t%d, %d, (pdf_range*) pdf_cmap_%s_ranges,\n",
			cmap->rlen, cmap->rlen, name);

		fprintf(fo, "\t%d, %d, (unsigned short*) pdf_cmap_%s_table,\n",
			cmap->tlen, cmap->tlen, name);

		fprintf(fo, "};\n\n");

		fz_close(fi);
	}

	if (fclose(fo))
	{
		fprintf(stderr, "cmapdump: could not close output file '%s'\n", argv[1]);
		return 1;
	}

	return 0;
}
Exemple #13
0
Disk*
opendisk(char *disk, int rdonly, int noctl)
{
	char *p, *q;
	Disk *d;

	d = malloc(sizeof(*d));
	if(d == nil)
		return nil;

	d->fd = d->wfd = d->ctlfd = -1;
	d->rdonly = rdonly;

	d->fd = open(disk, OREAD);
	if(d->fd < 0) {
		werrstr("cannot open disk file");
		free(d);
		return nil;
	}

	if(rdonly == 0) {
		d->wfd = open(disk, OWRITE);
		if(d->wfd < 0)
			d->rdonly = 1;
	}

	if(noctl)
		return openfile(d);

	p = malloc(strlen(disk) + 4);	/* 4: slop for "ctl\0" */
	if(p == nil) {
		close(d->wfd);
		close(d->fd);
		free(d);
		return nil;
	}
	strcpy(p, disk);

	/* check for floppy(3) disk */
	if(strlen(p) >= 7) {
		q = p+strlen(p)-7;
		if(q[0] == 'f' && q[1] == 'd' && isdigit((uchar)q[2]) && strcmp(q+3, "disk") == 0) {
			strcpy(q+3, "ctl");
			if((d->ctlfd = open(p, ORDWR)) >= 0) {
				*q = '\0';
				d->prefix = p;
				d->type = Tfloppy;
				return openfile(d);
			}
		}
	}

	/* attempt to find sd(3) disk or partition */
	if(q = strrchr(p, '/'))
		q++;
	else
		q = p;

	strcpy(q, "ctl");
	if((d->ctlfd = open(p, ORDWR)) >= 0) {
		*q = '\0';
		d->prefix = p;
		d->type = Tsd;
		d->part = strdup(disk+(q-p));
		if(d->part == nil){
			close(d->ctlfd);
			close(d->wfd);
			close(d->fd);
			free(p);
			free(d);
			return nil;
		}
		return opensd(d);
	}

	*q = '\0';
	d->prefix = p;
	/* assume we just have a normal file */
	d->type = Tfile;
	return openfile(d);
}
Exemple #14
0
static inline void TranslateFilename( int c,char * tmp,size_t tmplen )
{
 int i;
 char * p;
 size_t len;
 gchar *msg = NULL;

 switch ( guiIntfStruct.StreamType )
  {
   case STREAMTYPE_STREAM:
        av_strlcpy(tmp, guiIntfStruct.Filename, tmplen);
        break;
   case STREAMTYPE_FILE:
          if ( ( guiIntfStruct.Filename )&&( guiIntfStruct.Filename[0] ) )
           {
            if ( (p = strrchr(guiIntfStruct.Filename, '/')) )
              av_strlcpy(tmp, p + 1, tmplen);
            else
              av_strlcpy(tmp, guiIntfStruct.Filename, tmplen);
            len=strlen( tmp );
            if ( ( len > 3 )&&( tmp[len - 3] == '.' ) ) tmp[len - 3]=0;
            else if ( ( len > 4 )&&( tmp[len - 4] == '.' ) ) tmp[len - 4]=0;
            else if ( ( len > 5 )&&( tmp[len - 5] == '.' ) ) tmp[len - 5]=0;
           }
          else
           {
            msg = g_filename_from_utf8( MSGTR_NoFileLoaded, -1, NULL, NULL, NULL );
            av_strlcpy( tmp, ( msg ? msg : MSGTR_NoFileLoaded ), tmplen );
           }
          break;
#ifdef CONFIG_DVDREAD
   case STREAMTYPE_DVD:
          if ( guiIntfStruct.DVD.current_chapter )
           {
            msg = g_filename_from_utf8( MSGTR_Chapter, -1, NULL, NULL, NULL );
            snprintf( tmp, tmplen, ( msg ? msg : MSGTR_Chapter ), guiIntfStruct.DVD.current_chapter );
           }
          else
           {
            msg = g_filename_from_utf8( MSGTR_NoChapter, -1, NULL, NULL, NULL );
            av_strlcat( tmp, ( msg ? msg : MSGTR_NoChapter ), tmplen );
           }
          break;
#endif
#ifdef CONFIG_VCD
   case STREAMTYPE_VCD:
        msg = g_filename_from_utf8( MSGTR_VCDTrack, -1, NULL, NULL, NULL );
        snprintf( tmp, tmplen, ( msg ? msg : MSGTR_VCDTrack ), guiIntfStruct.Track );
	break;
#endif
   default:
     msg = g_filename_from_utf8( MSGTR_NoMediaOpened, -1, NULL, NULL, NULL );
     av_strlcpy( tmp, ( msg ? msg : MSGTR_NoMediaOpened ), tmplen );
  }
 g_free(msg);
 if ( c )
  {
   for ( i=0;i < (int)strlen( tmp );i++ )
    {
     int t=0;
     if ( c == 1 ) { if ( ( tmp[i] >= 'A' )&&( tmp[i] <= 'Z' ) ) t=32; }
     if ( c == 2 ) { if ( ( tmp[i] >= 'a' )&&( tmp[i] <= 'z' ) ) t=-32; }
     tmp[i]=(char)( tmp[i] + t );
    }
  }
}
Exemple #15
0
int main (int argc, char *argv[]) {
    const char *me;
    krb5_data crealm, srealm, transit;
    krb5_error_code r;
    int expand_only = 0;

    me = strrchr (argv[0], '/');
    me = me ? me+1 : argv[0];

    while (argc > 3 && argv[1][0] == '-') {
	if (!strcmp ("-v", argv[1]))
	    verbose++, argc--, argv++;
	else if (!strcmp ("-x", argv[1]))
	    expand_only++, argc--, argv++;
	else
	    goto usage;
    }

    if (argc != 4) {
    usage:
	printf ("usage: %s [-v] [-x] clientRealm serverRealm transitEncoding\n",
		me);
	return 1;
    }

    crealm.data = argv[1];
    crealm.length = strlen(argv[1]);
    srealm.data = argv[2];
    srealm.length = strlen(argv[2]);
    transit.data = argv[3];
    transit.length = strlen(argv[3]);

    if (expand_only) {

	printf ("client realm: %s\n", argv[1]);
	printf ("server realm: %s\n", argv[2]);
	printf ("transit enc.: %s\n", argv[3]);

	if (argv[3][0] == 0) {
	    printf ("no other realms transited\n");
	    return 0;
	}

	r = foreach_realm (print_a_realm, NULL, &crealm, &srealm, &transit);
	if (r)
	    printf ("--> returned error %ld\n", (long) r);
	return r != 0;

    } else {

	/* Actually check the values against the supplied krb5.conf file.  */
	krb5_context ctx;
	r = krb5_init_context (&ctx);
	if (r) {
	    com_err (me, r, "initializing krb5 context");
	    return 1;
	}
	r = krb5_check_transited_list (ctx, &transit, &crealm, &srealm);
	if (r == KRB5KRB_AP_ERR_ILL_CR_TKT) {
	    printf ("NO\n");
	} else if (r == 0) {
	    printf ("YES\n");
	} else {
	    printf ("kablooey!\n");
	    com_err (me, r, "checking transited-realm list");
	    return 1;
	}
	return 0;
    }
}
Exemple #16
0
void *uwsgi_python_autoreloader_thread(void *foobar) {

	PyObject *new_thread = uwsgi_python_setup_thread("uWSGIAutoReloader");
	if (!new_thread) return NULL;

	PyObject *modules = PyImport_GetModuleDict();

	if (uwsgi.mywid == 1) {
		uwsgi_log("Python auto-reloader enabled\n");
	}

	PyObject *times_dict = PyDict_New();
	char *filename;
	for(;;) {
		UWSGI_RELEASE_GIL;
		sleep(up.auto_reload);
		UWSGI_GET_GIL;
		// do not start monitoring til the first app is loaded (required for lazy mode)
		if (uwsgi_apps_cnt == 0) continue;
#ifdef UWSGI_PYTHON_OLD
                int pos = 0;
#else
                Py_ssize_t pos = 0;
#endif
		PyObject *mod_name, *mod;
                while (PyDict_Next(modules, &pos, &mod_name, &mod)) {
			int found = 0;
			struct uwsgi_string_list *usl = up.auto_reload_ignore;
			while(usl) {
				if (!strcmp(usl->value, PyString_AsString(mod_name))) {
					found = 1;
					break;
				}
				usl = usl->next;
			}
			if (found) continue;
			if (!PyObject_HasAttrString(mod, "__file__")) continue;
			PyObject *mod_file = PyObject_GetAttrString(mod, "__file__");
			if (!mod_file) continue;
#ifdef PYTHREE
			PyObject *zero = PyUnicode_AsUTF8String(mod_file);
			char *mod_filename = PyString_AsString(zero);
#else
			char *mod_filename = PyString_AsString(mod_file);
#endif
			if (!mod_filename) {
#ifdef PYTHREE
				Py_DECREF(zero);
#endif
				continue;
			}
			char *ext = strrchr(mod_filename, '.');
			if (ext && (!strcmp(ext+1, "pyc") || !strcmp(ext+1, "pyd") || !strcmp(ext+1, "pyo"))) {
				filename = uwsgi_concat2n(mod_filename, strlen(mod_filename)-1, "", 0);
			}
			else {
				filename = uwsgi_concat2(mod_filename, "");
			}
			if (uwsgi_check_python_mtime(times_dict, filename)) {
				UWSGI_RELEASE_GIL;
				return NULL;
			}
			free(filename);
#ifdef PYTHREE
			Py_DECREF(zero);
#endif
		}
	}

	return NULL;
}
Exemple #17
0
int
main(int argc, char *argv[])
{
    int                     n;
    int                     fd[2];
    pid_t                   pid;
    char                    *pager, *argv0;
    char                    line[1024];
    FILE                    *fp;

    if(argc != 2){
        printf("usage: a.out <pathname>\n");
        return -1;
    }

    if((fp = fopen(argv[1], "r")) == NULL){
        printf("open file [%s] error: %s\n", argv[1], strerror(errno));
        return -2;
    }
    
    if(pipe(fd) < 0){
        perror("pipe");
        return -3;
    }

    if((pid = fork()) < 0){
        perror("fork");
        return -4;
    }else if(pid > 0){
        close(fd[0]);
        while(fgets(line, sizeof(line), fp) != NULL){
            n = strlen(line);
            if(write(fd[1], line, n) != n){
                perror("write");
                return -5;
            }
        }
        if(ferror(fp)){ /*读文件结束或者读文件出错,fgets都会返回NULL,用ferror来判断是不是发生了错误*/
            printf("read file [%s] error\n", argv[1]);
            return -6;
        }

        close(fd[1]);

        /*等待子进程退出*/
        if(waitpid(pid, NULL, 0) < 0){
            perror("waitpid");
            return -7;
        }

        return 0;
    }else{
        close(fd[1]);
        /*要先判断是不相等了才进行文件符复制*/
        if(fd[0] != STDIN_FILENO){
            if(dup2(fd[0], STDIN_FILENO) != STDIN_FILENO){
                perror("dup2");
                return -8;
            }
            close(fd[0]);/*要关闭该文件描述符,因为被复制出来了,共享文件描述符,以后都不用了*/
        }
        /*文件描述符已被复制,子进程的标准输入是管道了,即复制前的fd[0]*/
        /*获取页的大小*/
        if((pager = getenv("PAGER")) == NULL)
            pager = DEF_PAGER;
        if((argv0 = strrchr(pager, '/')) != NULL)
            argv0++;
        else
            argv0 = pager;

        if(execl(pager, argv0, (char *)0) < 0){
            perror("execl");
            return -9;
        }
        return 0;
    }
    
}
int proc_file(char *rqfile)
    {
    char afn[256], rfn[256];
    FILE *afp = NULL, *rfp = NULL;
    char ibuf[2048];
    int ilen, len, ret = 0;
    char amode[8] = "";
    char atest[100] = "";
    int akeysz=0;
    unsigned char iVec[20], aKey[40];
    int dir = -1, err = 0, step = 0;
    unsigned char plaintext[2048];
    unsigned char ciphertext[2048];
    char *rp;
    EVP_CIPHER_CTX ctx;
    int numkeys=1;

    if (!rqfile || !(*rqfile))
	{
	printf("No req file\n");
	return -1;
	}
    strcpy(afn, rqfile);

    if ((afp = fopen(afn, "r")) == NULL)
	{
	printf("Cannot open file: %s, %s\n", 
	       afn, strerror(errno));
	return -1;
	}
    strcpy(rfn,afn);
    rp=strstr(rfn,"req/");
    assert(rp);
    memcpy(rp,"rsp",3);
    rp = strstr(rfn, ".req");
    memcpy(rp, ".rsp", 4);
    if ((rfp = fopen(rfn, "w")) == NULL)
	{
	printf("Cannot open file: %s, %s\n", 
	       rfn, strerror(errno));
	fclose(afp);
	afp = NULL;
	return -1;
	}
    while (!err && (fgets(ibuf, sizeof(ibuf), afp)) != NULL)
	{
	ilen = strlen(ibuf);
	/*	printf("step=%d ibuf=%s",step,ibuf);*/
	if(step == 3 && !strcmp(amode,"ECB"))
	    {
	    memset(iVec, 0, sizeof(iVec));
	    step = (dir)? 4: 5;  /* no ivec for ECB */
	    }
	switch (step)
	    {
	case 0:  /* read preamble */
	    if (ibuf[0] == '\n')
		{ /* end of preamble */
		if (*amode == '\0')
		    {
		    printf("Missing Mode\n");
		    err = 1;
		    }
		else
		    {
		    fputs(ibuf, rfp);
		    ++ step;
		    }
		}
	    else if (ibuf[0] != '#')
		{
		printf("Invalid preamble item: %s\n", ibuf);
		err = 1;
		}
	    else
		{ /* process preamble */
		char *xp, *pp = ibuf+2;
		int n;
		if(*amode)
		    { /* insert current time & date */
		    time_t rtim = time(0);
		    fprintf(rfp, "# %s", ctime(&rtim));
		    }
		else
		    {
		    fputs(ibuf, rfp);
		    if(!strncmp(pp,"INVERSE ",8) || !strncmp(pp,"DES ",4)
		       || !strncmp(pp,"TDES ",5)
		       || !strncmp(pp,"PERMUTATION ",12)
		       || !strncmp(pp,"SUBSTITUTION ",13)
		       || !strncmp(pp,"VARIABLE ",9))
			{
			/* get test type */
			if(!strncmp(pp,"DES ",4))
			    pp+=4;
			else if(!strncmp(pp,"TDES ",5))
			    pp+=5;
			xp = strchr(pp, ' ');
			n = xp-pp;
			strncpy(atest, pp, n);
			atest[n] = '\0';
			/* get mode */
			xp = strrchr(pp, ' '); /* get mode" */
			n = strlen(xp+1)-1;
			strncpy(amode, xp+1, n);
			amode[n] = '\0';
			/* amode[3] = '\0'; */
			printf("Test=%s, Mode=%s\n",atest,amode);
			}
		    }
		}
	    break;

	case 1:  /* [ENCRYPT] | [DECRYPT] */
	    if(ibuf[0] == '\n')
		break;
	    if (ibuf[0] == '[')
		{
		fputs(ibuf, rfp);
		++step;
		if (strncasecmp(ibuf, "[ENCRYPT]", 9) == 0)
		    dir = 1;
		else if (strncasecmp(ibuf, "[DECRYPT]", 9) == 0)
		    dir = 0;
		else
		    {
		    printf("Invalid keyword: %s\n", ibuf);
		    err = 1;
		    }
		break;
		}
	    else if (dir == -1)
		{
		err = 1;
		printf("Missing ENCRYPT/DECRYPT keyword\n");
		break;
		}
	    else 
		step = 2;

	case 2: /* KEY = xxxx */
	    if(*ibuf == '\n')
		{
	        fputs(ibuf, rfp);
		break;
                }
	    if(!strncasecmp(ibuf,"COUNT = ",8))
		{
	        fputs(ibuf, rfp);
		break;
                }
	    if(!strncasecmp(ibuf,"COUNT=",6))
		{
	        fputs(ibuf, rfp);
		break;
                }
	    if(!strncasecmp(ibuf,"NumKeys = ",10))
		{
		numkeys=atoi(ibuf+10);
		break;
		}
	  
	    fputs(ibuf, rfp);
	    if(!strncasecmp(ibuf,"KEY = ",6))
		{
		akeysz=64;
		len = hex2bin((char*)ibuf+6, strlen(ibuf+6)-1, aKey);
		if (len < 0)
		    {
		    printf("Invalid KEY\n");
		    err=1;
		    break;
		    }
		PrintValue("KEY", aKey, len);
		++step;
		}
	    else if(!strncasecmp(ibuf,"KEYs = ",7))
		{
		akeysz=64*3;
		len=hex2bin(ibuf+7,strlen(ibuf+7)-1,aKey);
		if(len != 8)
		    {
		    printf("Invalid KEY\n");
		    err=1;
		    break;
		    }
		memcpy(aKey+8,aKey,8);
		memcpy(aKey+16,aKey,8);
		ibuf[4]='\0';
		PrintValue("KEYs",aKey,len);
		++step;
		}
	    else if(!strncasecmp(ibuf,"KEY",3))
		{
		int n=ibuf[3]-'1';

		akeysz=64*3;
		len=hex2bin(ibuf+7,strlen(ibuf+7)-1,aKey+n*8);
		if(len != 8)
		    {
		    printf("Invalid KEY\n");
		    err=1;
		    break;
		    }
		ibuf[4]='\0';
		PrintValue(ibuf,aKey,len);
		if(n == 2)
		    ++step;
		}
	    else
		{
		printf("Missing KEY\n");
		err = 1;
		}
	    break;

	case 3: /* IV = xxxx */
	    fputs(ibuf, rfp);
	    if (strncasecmp(ibuf, "IV = ", 5) != 0)
		{
		printf("Missing IV\n");
		err = 1;
		}
	    else
		{
		len = hex2bin((char*)ibuf+5, strlen(ibuf+5)-1, iVec);
		if (len < 0)
		    {
		    printf("Invalid IV\n");
		    err =1;
		    break;
		    }
		PrintValue("IV", iVec, len);
		step = (dir)? 4: 5;
		}
	    break;

	case 4: /* PLAINTEXT = xxxx */
	    fputs(ibuf, rfp);
	    if (strncasecmp(ibuf, "PLAINTEXT = ", 12) != 0)
		{
		printf("Missing PLAINTEXT\n");
		err = 1;
		}
	    else
		{
		int nn = strlen(ibuf+12);
		if(!strcmp(amode,"CFB1"))
		    len=bint2bin(ibuf+12,nn-1,plaintext);
		else
		    len=hex2bin(ibuf+12, nn-1,plaintext);
		if (len < 0)
		    {
		    printf("Invalid PLAINTEXT: %s", ibuf+12);
		    err =1;
		    break;
		    }
		if (len >= sizeof(plaintext))
		    {
		    printf("Buffer overflow\n");
		    }
		PrintValue("PLAINTEXT", (unsigned char*)plaintext, len);
		if (strcmp(atest, "Monte") == 0)  /* Monte Carlo Test */
		    {
		    do_mct(amode,akeysz,numkeys,aKey,iVec,dir,plaintext,len,rfp);
		    }
		else
		    {
		    assert(dir == 1);
		    ret = DESTest(&ctx, amode, akeysz, aKey, iVec, 
				  dir,  /* 0 = decrypt, 1 = encrypt */
				  ciphertext, plaintext, len);
		    OutputValue("CIPHERTEXT",ciphertext,len,rfp,
				!strcmp(amode,"CFB1"));
		    }
		step = 6;
		}
	    break;

	case 5: /* CIPHERTEXT = xxxx */
	    fputs(ibuf, rfp);
	    if (strncasecmp(ibuf, "CIPHERTEXT = ", 13) != 0)
		{
		printf("Missing KEY\n");
		err = 1;
		}
	    else
		{
		if(!strcmp(amode,"CFB1"))
		    len=bint2bin(ibuf+13,strlen(ibuf+13)-1,ciphertext);
		else
		    len = hex2bin(ibuf+13,strlen(ibuf+13)-1,ciphertext);
		if (len < 0)
		    {
		    printf("Invalid CIPHERTEXT\n");
		    err =1;
		    break;
		    }
		
		PrintValue("CIPHERTEXT", ciphertext, len);
		if (strcmp(atest, "Monte") == 0)  /* Monte Carlo Test */
		    {
		    do_mct(amode, akeysz, numkeys, aKey, iVec, 
			   dir, ciphertext, len, rfp);
		    }
		else
		    {
		    assert(dir == 0);
		    ret = DESTest(&ctx, amode, akeysz, aKey, iVec, 
				  dir,  /* 0 = decrypt, 1 = encrypt */
				  plaintext, ciphertext, len);
		    OutputValue("PLAINTEXT",(unsigned char *)plaintext,len,rfp,
				!strcmp(amode,"CFB1"));
		    }
		step = 6;
		}
	    break;

	case 6:
	    if (ibuf[0] != '\n')
		{
		err = 1;
		printf("Missing terminator\n");
		}
	    else if (strcmp(atest, "MCT") != 0)
		{ /* MCT already added terminating nl */
		fputs(ibuf, rfp);
		}
	    step = 1;
	    break;
	    }
	}
    if (rfp)
	fclose(rfp);
    if (afp)
	fclose(afp);
    return err;
    }
Exemple #19
0
jsgf_rule_t *
jsgf_import_rule(jsgf_t * jsgf, char *name)
{
    char *c, *path, *newpath;
    size_t namelen, packlen;
    void *val;
    jsgf_t *imp;
    int import_all;

    /* Trim the leading and trailing <> */
    namelen = strlen(name);
    path = ckd_malloc(namelen - 2 + 6); /* room for a trailing .gram */
    strcpy(path, name + 1);
    /* Split off the first part of the name */
    c = strrchr(path, '.');
    if (c == NULL) {
        E_ERROR("Imported rule is not qualified: %s\n", name);
        ckd_free(path);
        return NULL;
    }
    packlen = c - path;
    *c = '\0';

    /* Look for import foo.* */
    import_all = (strlen(name) > 2
                  && 0 == strcmp(name + namelen - 3, ".*>"));

    /* Construct a filename. */
    for (c = path; *c; ++c)
        if (*c == '.')
            *c = '/';
    strcat(path, ".gram");
    newpath = path_list_search(jsgf->searchpath, path);
    if (newpath == NULL) {
        E_ERROR("Failed to find grammar %s\n", path);
        ckd_free(path);
        return NULL;
    }
    ckd_free(path);

    path = newpath;
    E_INFO("Importing %s from %s to %s\n", name, path, jsgf->name);

    /* FIXME: Also, we need to make sure that path is fully qualified
     * here, by adding any prefixes from jsgf->name to it. */
    /* See if we have parsed it already */
    if (hash_table_lookup(jsgf->imports, path, &val) == 0) {
        E_INFO("Already imported %s\n", path);
        imp = val;
        ckd_free(path);
    }
    else {
        /* If not, parse it. */
        imp = jsgf_parse_file(path, jsgf);
        val = hash_table_enter(jsgf->imports, path, imp);
        if (val != (void *) imp) {
            E_WARN("Multiply imported file: %s\n", path);
        }
    }
    if (imp != NULL) {
        hash_iter_t *itor;
        /* Look for public rules matching rulename. */
        for (itor = hash_table_iter(imp->rules); itor;
             itor = hash_table_iter_next(itor)) {
            hash_entry_t *he = itor->ent;
            jsgf_rule_t *rule = hash_entry_val(he);
            int rule_matches;
            char *rule_name = importname2rulename(name);

            if (import_all) {
                /* Match package name (symbol table is shared) */
                rule_matches =
                    !strncmp(rule_name, rule->name, packlen + 1);
            }
            else {
                /* Exact match */
                rule_matches = !strcmp(rule_name, rule->name);
            }
            ckd_free(rule_name);
            if (rule->is_public && rule_matches) {
                void *val;
                char *newname;

                /* Link this rule into the current namespace. */
                c = strrchr(rule->name, '.');
                assert(c != NULL);
                newname = jsgf_fullname(jsgf, c);

                E_INFO("Imported %s\n", newname);
                val = hash_table_enter(jsgf->rules, newname,
                                       jsgf_rule_retain(rule));
                if (val != (void *) rule) {
                    E_WARN("Multiply defined symbol: %s\n", newname);
                }
                if (!import_all) {
                    hash_table_iter_free(itor);
                    return rule;
                }
            }
        }
    }

    return NULL;
}
Exemple #20
0
int main(int argc,char *argv[]){
  char *basename;
  codebook *b=NULL;
  int entries=0;
  int dim=0;
  long i,j,target=-1,protect=-1;
  FILE *out=NULL;

  int argnum=0;

  argv++;
  if(*argv==NULL){
    usage();
    exit(1);
  }

  while(*argv){
    if(*argv[0]=='-'){

      argv++;
	
    }else{
      switch (argnum++){
      case 0:case 1:
	{
	  /* yes, this is evil.  However, it's very convenient to parse file
	     extentions */
	  
	  /* input file.  What kind? */
	  char *dot;
	  char *ext=NULL;
	  char *name=strdup(*argv++);
	  dot=strrchr(name,'.');
	  if(dot)
	    ext=dot+1;
	  else{
	    ext="";
	    
	  }
	  
	  
	  /* codebook */
	  if(!strcmp(ext,"vqh")){
	    
	    basename=strrchr(name,'/');
	    if(basename)
	      basename=strdup(basename)+1;
	    else
	      basename=strdup(name);
	    dot=strrchr(basename,'.');
	    if(dot)*dot='\0';
	    
	    b=codebook_load(name);
	    dim=b->dim;
	    entries=b->entries;
	  }
	  
	  /* data file; we do actually need to suck it into memory */
	  /* we're dealing with just one book, so we can de-interleave */ 
	  if(!strcmp(ext,"vqd") && !points){
	    int cols;
	    long lines=0;
	    char *line;
	    float *vec;
	    FILE *in=fopen(name,"r");
	    if(!in){
	      fprintf(stderr,"Could not open input file %s\n",name);
	      exit(1);
	    }
	    
	    reset_next_value();
	    line=setup_line(in);
	    /* count cols before we start reading */
	    {
	      char *temp=line;
	      while(*temp==' ')temp++;
	      for(cols=0;*temp;cols++){
		while(*temp>32)temp++;
		while(*temp==' ')temp++;
	      }
	    }
	    vec=alloca(cols*sizeof(float));
	    /* count, then load, to avoid fragmenting the hell out of
	       memory */
	    while(line){
	      lines++;
	      for(j=0;j<cols;j++)
		if(get_line_value(in,vec+j)){
		  fprintf(stderr,"Too few columns on line %ld in data file\n",lines);
		  exit(1);
		}
	      if((lines&0xff)==0)spinnit("counting samples...",lines*cols);
	      line=setup_line(in);
	    }
	    pointlist=_ogg_malloc((cols*lines+entries*dim)*sizeof(float));
	    
	    rewind(in);
	    line=setup_line(in);
	    while(line){
	      lines--;
	      for(j=0;j<cols;j++)
		if(get_line_value(in,vec+j)){
		  fprintf(stderr,"Too few columns on line %ld in data file\n",lines);
		  exit(1);
		}
	      /* deinterleave, add to heap */
	      add_vector(b,vec,cols);
	      if((lines&0xff)==0)spinnit("loading samples...",lines*cols);
	      
	      line=setup_line(in);
	    }
	    fclose(in);
	  }
	}
	break;
      case 2:
	target=atol(*argv++);
	if(target==0)target=entries;
	break;
      case 3:
	protect=atol(*argv++);
	break;
      case 4:
	{
	  char *buff=alloca(strlen(*argv)+5);
	  sprintf(buff,"%s.vqh",*argv);
	  basename=*argv++;

	  out=fopen(buff,"w");
	  if(!out){
	    fprintf(stderr,"unable ot open %s for output",buff);
	    exit(1);
	  }
	}
	break;
      default:
	usage();
      }
    }
  }
  if(!entries || !points || !out)usage();
  if(target==-1)usage();

  /* add guard points */
  for(i=0;i<entries;i++)
    for(j=0;j<dim;j++)
      pointlist[points++]=b->valuelist[i*dim+j];
  
  points/=dim;

  /* set up auxiliary vectors for error tracking */
  {
    encode_aux_nearestmatch *nt=NULL;
    long pointssofar=0;
    long *pointindex;
    long indexedpoints=0;
    long *entryindex;
    long *reventry;
    long *membership=_ogg_malloc(points*sizeof(long));
    long *firsthead=_ogg_malloc(entries*sizeof(long));
    long *secondary=_ogg_malloc(points*sizeof(long));
    long *secondhead=_ogg_malloc(entries*sizeof(long));

    long *cellcount=_ogg_calloc(entries,sizeof(long));
    long *cellcount2=_ogg_calloc(entries,sizeof(long));
    float *cellerror=_ogg_calloc(entries,sizeof(float));
    float *cellerrormax=_ogg_calloc(entries,sizeof(float));
    long cellsleft=entries;
    for(i=0;i<points;i++)membership[i]=-1;
    for(i=0;i<entries;i++)firsthead[i]=-1;
    for(i=0;i<points;i++)secondary[i]=-1;
    for(i=0;i<entries;i++)secondhead[i]=-1;

    for(i=0;i<points;i++){
      /* assign vectors to the nearest cell.  Also keep track of second
	 nearest for error statistics */
      float *ppt=pointlist+i*dim;
      int    firstentry=closest(b,ppt,-1);
      int    secondentry=closest(b,ppt,firstentry);
      float firstmetric=_dist(dim,b->valuelist+dim*firstentry,ppt);
      float secondmetric=_dist(dim,b->valuelist+dim*secondentry,ppt);
      
      if(!(i&0xff))spinnit("initializing... ",points-i);
    
      membership[i]=firsthead[firstentry];
      firsthead[firstentry]=i;
      secondary[i]=secondhead[secondentry];
      secondhead[secondentry]=i;

      if(i<points-entries){
	cellerror[firstentry]+=secondmetric-firstmetric;
	cellerrormax[firstentry]=max(cellerrormax[firstentry],
				     _heuristic(b,ppt,secondentry));
	cellcount[firstentry]++;
	cellcount2[secondentry]++;
      }
    }

    /* which cells are most heavily populated?  Protect as many from
       dispersal as the user has requested */
    {
      long **countindex=_ogg_calloc(entries,sizeof(long *));
      for(i=0;i<entries;i++)countindex[i]=cellcount+i;
      qsort(countindex,entries,sizeof(long *),longsort);
      for(i=0;i<protect;i++){
	int ptr=countindex[i]-cellcount;
	cellerrormax[ptr]=9e50f;
      }
    }

    {
      fprintf(stderr,"\r");
      for(i=0;i<entries;i++){
	/* decompose index */
	int entry=i;
	for(j=0;j<dim;j++){
	  fprintf(stderr,"%d:",entry%b->c->thresh_tree->quantvals);
	  entry/=b->c->thresh_tree->quantvals;
	}
	
	fprintf(stderr,":%ld/%ld, ",cellcount[i],cellcount2[i]);
      }
      fprintf(stderr,"\n");
    }

    /* do the automatic cull request */
    while(cellsleft>target){
      int bestcell=-1;
      float besterror=0;
      float besterror2=0;
      long head=-1;
      char spinbuf[80];
      sprintf(spinbuf,"cells left to eliminate: %ld : ",cellsleft-target);

      /* find the cell with lowest removal impact */
      for(i=0;i<entries;i++){
	if(b->c->lengthlist[i]>0){
	  if(bestcell==-1 || cellerrormax[i]<=besterror2){
	    if(bestcell==-1 || cellerrormax[i]<besterror2 || 
	       besterror>cellerror[i]){
	      besterror=cellerror[i];
	      besterror2=cellerrormax[i];
	      bestcell=i;
	    }
	  }
	}
      }

      fprintf(stderr,"\reliminating cell %d                              \n"
	      "     dispersal error of %g max/%g total (%ld hits)\n",
	      bestcell,besterror2,besterror,cellcount[bestcell]);

      /* disperse it.  move each point out, adding it (properly) to
         the second best */
      b->c->lengthlist[bestcell]=0;
      head=firsthead[bestcell];
      firsthead[bestcell]=-1;
      while(head!=-1){
	/* head is a point number */
	float *ppt=pointlist+head*dim;
	int firstentry=closest(b,ppt,-1);
	int secondentry=closest(b,ppt,firstentry);
	float firstmetric=_dist(dim,b->valuelist+dim*firstentry,ppt);
	float secondmetric=_dist(dim,b->valuelist+dim*secondentry,ppt);
	long next=membership[head];

	if(head<points-entries){
	  cellcount[firstentry]++;
	  cellcount[bestcell]--;
	  cellerror[firstentry]+=secondmetric-firstmetric;
	  cellerrormax[firstentry]=max(cellerrormax[firstentry],
				       _heuristic(b,ppt,secondentry));
	}

	membership[head]=firsthead[firstentry];
	firsthead[firstentry]=head;
	head=next;
	if(cellcount[bestcell]%128==0)
	  spinnit(spinbuf,cellcount[bestcell]+cellcount2[bestcell]);

      }

      /* now see that all points that had the dispersed cell as second
         choice have second choice reassigned */
      head=secondhead[bestcell];
      secondhead[bestcell]=-1;
      while(head!=-1){
	float *ppt=pointlist+head*dim;
	/* who are we assigned to now? */
	int firstentry=closest(b,ppt,-1);
	/* what is the new second closest match? */
	int secondentry=closest(b,ppt,firstentry);
	/* old second closest is the cell being disbanded */
	float oldsecondmetric=_dist(dim,b->valuelist+dim*bestcell,ppt);
	/* new second closest error */
	float secondmetric=_dist(dim,b->valuelist+dim*secondentry,ppt);
	long next=secondary[head];

	if(head<points-entries){
	  cellcount2[secondentry]++;
	  cellcount2[bestcell]--;
	  cellerror[firstentry]+=secondmetric-oldsecondmetric;
	  cellerrormax[firstentry]=max(cellerrormax[firstentry],
				       _heuristic(b,ppt,secondentry));
	}
	
	secondary[head]=secondhead[secondentry];
	secondhead[secondentry]=head;
	head=next;

	if(cellcount2[bestcell]%128==0)
	  spinnit(spinbuf,cellcount2[bestcell]);
      }

      cellsleft--;
    }

    /* paring is over.  Build decision trees using points that now fall
       through the thresh matcher. */
    /* we don't free membership; we flatten it in order to use in lp_split */

    for(i=0;i<entries;i++){
      long head=firsthead[i];
      spinnit("rearranging membership cache... ",entries-i);
      while(head!=-1){
	long next=membership[head];
	membership[head]=i;
	head=next;
      }
    }

    free(secondhead);
    free(firsthead);
    free(cellerror);
    free(cellerrormax);
    free(secondary);

    pointindex=_ogg_malloc(points*sizeof(long));
    /* make a point index of fall-through points */
    for(i=0;i<points;i++){
      int best=_best(b,pointlist+i*dim,1);
      if(best==-1)
	pointindex[indexedpoints++]=i;
      spinnit("finding orphaned points... ",points-i);
    }

    /* make an entry index */
    entryindex=_ogg_malloc(entries*sizeof(long));
    target=0;
    for(i=0;i<entries;i++){
      if(b->c->lengthlist[i]>0)
	entryindex[target++]=i;
    }

    /* make working space for a reverse entry index */
    reventry=_ogg_malloc(entries*sizeof(long));

    /* do the split */
    nt=b->c->nearest_tree=
      _ogg_calloc(1,sizeof(encode_aux_nearestmatch));

    nt->alloc=4096;
    nt->ptr0=_ogg_malloc(sizeof(long)*nt->alloc);
    nt->ptr1=_ogg_malloc(sizeof(long)*nt->alloc);
    nt->p=_ogg_malloc(sizeof(long)*nt->alloc);
    nt->q=_ogg_malloc(sizeof(long)*nt->alloc);
    nt->aux=0;

    fprintf(stderr,"Leaves added: %d              \n",
            lp_split(pointlist,points,
                     b,entryindex,target,
                     pointindex,indexedpoints,
                     membership,reventry,
                     0,&pointssofar));
    free(membership);
    free(reventry);
    free(pointindex);

    /* hack alert.  I should just change the damned splitter and
       codebook writer */
    for(i=0;i<nt->aux;i++)nt->p[i]*=dim;
    for(i=0;i<nt->aux;i++)nt->q[i]*=dim;
    
    /* recount hits.  Build new lengthlist. reuse entryindex storage */
    for(i=0;i<entries;i++)entryindex[i]=1;
    for(i=0;i<points-entries;i++){
      int best=_best(b,pointlist+i*dim,1);
      float *a=pointlist+i*dim;
      if(!(i&0xff))spinnit("counting hits...",i);
      if(best==-1){
	fprintf(stderr,"\nINTERNAL ERROR; a point count not be matched to a\n"
		"codebook entry.  The new decision tree is broken.\n");
	exit(1);
      }
      entryindex[best]++;
    }
    for(i=0;i<nt->aux;i++)nt->p[i]/=dim;
    for(i=0;i<nt->aux;i++)nt->q[i]/=dim;
    
    /* the lengthlist builder doesn't actually deal with 0 hit entries.
       So, we pack the 'sparse' hit list into a dense list, then unpack
       the lengths after the build */
    {
      int upper=0;
      long *lengthlist=_ogg_calloc(entries,sizeof(long));
      for(i=0;i<entries;i++){
	if(b->c->lengthlist[i]>0)
	  entryindex[upper++]=entryindex[i];
	else{
	  if(entryindex[i]>1){
	    fprintf(stderr,"\nINTERNAL ERROR; _best matched to unused entry\n");
	    exit(1);
	  }
	}
      }
      
      /* sanity check */
      if(upper != target){
	fprintf(stderr,"\nINTERNAL ERROR; packed the wrong number of entries\n");
	exit(1);
      }
    
      build_tree_from_lengths(upper,entryindex,lengthlist);
      
      upper=0;
      for(i=0;i<entries;i++){
	if(b->c->lengthlist[i]>0)
	  b->c->lengthlist[i]=lengthlist[upper++];
      }

    }
  }
  /* we're done.  write it out. */
  write_codebook(out,basename,b->c);

  fprintf(stderr,"\r                                        \nDone.\n");
  return(0);
}
Exemple #21
0
/* create a new finfo record, open FITS file */
static Finfo FinfoNew(char *fname)
{
  int i, len;
  char *e=NULL;
  char *f=NULL;
  char *s=NULL;
  unsigned char header[8];
  Finfo finfo;

  /* sanity check */
  if( !fname ) return NULL;
  /* return existing finfo, if possible */
  if( (finfo=FinfoLookup(fname)) ) return finfo;
  /* allocate record */
  if( !(finfo = (Finfo)xcalloc(sizeof(FinfoRec), 1)) ){
    fprintf(stderr, "ERROR: can't allocate rec for image\n");
    return NULL;
  }
  /* save file name */
  finfo->fname = xstrdup(fname);
  /* check for file type */
  if( (s = strrchr(fname, '.')) && !strcasecmp(s, ".png") ){
    /* its a PNG */
    finfo->ftype = FTYPE_PNG;
  } else {
    /* assume FITS type */
    finfo->ftype = FTYPE_FITS;
  }
  /* open file */
  switch(finfo->ftype){
  case FTYPE_PNG:
    /* code taken from "PNG: The Definitive Guide" by Greg Roelofs,
       Chapter 13 "Reading PNG Images" */
    /* set data path */
    datapath = getenv("JS9_DATAPATH");
    /* look for path of the PNG file */
    s = Find(fname, "r", NULL, datapath);
    if( s && *s ){
      if( !(finfo->fp = fopen(s, "rb")) ){
	fprintf(stderr, "ERROR: can't open PNG file '%s'\n", fname);
	goto error;
      }
      fread(header, 1, 8, finfo->fp);
      if( png_sig_cmp(header, 0, 8) ){
	fprintf(stderr, "ERROR: not recognized as a PNG file '%s'\n", fname);
	goto error;
      }
      /* initialize stuff */
      finfo->png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
					      NULL, NULL, NULL);
      if( !finfo->png_ptr ){
	fprintf(stderr, "ERROR: png_create_read_struct failed '%s'\n", fname);
	goto error;
      }
      finfo->info_ptr = png_create_info_struct(finfo->png_ptr);
      if( !finfo->info_ptr ){
	fprintf(stderr, "ERROR: png_create_info_struct failed '%s'\n", fname);
	goto error;
      }
      if( setjmp(png_jmpbuf(finfo->png_ptr)) ){
	fprintf(stderr, "ERROR: during png init_io '%s'\n", fname);
	goto error;
      }
      png_init_io(finfo->png_ptr, finfo->fp);
      png_set_sig_bytes(finfo->png_ptr, 8);
      png_read_info(finfo->png_ptr, finfo->info_ptr);
      /* get the text chunks that come before the image */
      if( png_get_text(finfo->png_ptr, finfo->info_ptr,
		       &(finfo->text_ptr), &(finfo->num_text)) > 0 ){
	/* process all known PNG keywords */
	for(i=0; i<finfo->num_text; i++){
	  if( !strcmp(finfo->text_ptr[i].key, FITSFILE) ){
	    finfo->fitsfile = xstrdup(finfo->text_ptr[i].text);
	    /* remove the extension that was used to generate png */
	    s = strchr(finfo->fitsfile, '[');
	    if( s ){
	      *s = '\0';
	    }
	  }
	}
      }
    } else {
      fprintf(stderr, "ERROR: can't locate PNG file for '%s' (%s)\n",
	      fname, datapath);
      goto error;
    }
    break;
    /* look for an error */
  case FTYPE_FITS:
    /* fits file can have an extension */
    f = FileRoot(fname);
    /* set data path */
    datapath = getenv("JS9_DATAPATH");
    /* look for path of the FITS file */
    s = Find(f, "r", NULL, datapath);
    xfree(f);
    if( s && *s ){
      len = strlen(s) + 1;
      /* construct full path to fits file + extension */
      e = FileExtension(fname);
      if( e ){
        len += strlen(e);
      }
      finfo->fitsfile = xmalloc(len);
      strcpy(finfo->fitsfile, s);
      if( e ){
        strcat(finfo->fitsfile, e);
      }
      xfree(s);
    } else {
      fprintf(stderr, "ERROR: can't locate FITS file for '%s' (%s)\n",
	      fname, datapath);
      goto error;
    }
    break;
  default:
    fprintf(stderr, "ERROR: unknown file type '%s'\n", fname);
    goto error;
    break;
  }
  /* add this finfo to end of list of existing finfos */
  FinfoListAdd(&finfohead, finfo);
  /* return the news */
  return finfo;
error:
  /* free up struct and return nothing */
  _FinfoFree(finfo);
  return NULL;
}
Exemple #22
0
static int tcl_mv_cp(Tcl_Interp * irp, int argc, char **argv, int copy)
{
  char *p, *fn = NULL, *oldpath = NULL, *s = NULL, *s1 = NULL;
  char *newfn = NULL, *newpath = NULL;
  int ok = 0, only_first, skip_this;
  FILE *fdb_old, *fdb_new;
  filedb_entry *fdbe_old, *fdbe_new;
  long where;

  BADARGS(3, 3, " oldfilepath newfilepath");
  Context;
  malloc_strcpy(fn, argv[1]);
  p = strrchr(fn, '/');
  if (p != NULL) {
    *p = 0;
    malloc_strcpy(s, fn);
    strcpy(fn, p + 1);
    if (!resolve_dir("/", s, &oldpath, -1)) {
      /* Tcl can do * anything */
      Tcl_AppendResult(irp, "-1", NULL);	/* Invalid source */
      my_free(fn);
      my_free(oldpath);
      return TCL_OK;
    }
    my_free(s);
  } else
    malloc_strcpy(oldpath, "/");
  malloc_strcpy(s, argv[2]);
  if (!resolve_dir("/", s, &newpath, -1)) {
    /* Destination is not just a directory */
    p = strrchr(s, '/');
    if (!p) {
      malloc_strcpy(newfn, s);
      s[0] = 0;
    } else {
      *p = 0;
      malloc_strcpy(newfn, p + 1);
    }
    my_free(newpath);
    if (!resolve_dir("/", s, &newpath, -1)) {
      Tcl_AppendResult(irp, "-2", NULL);	/* Invalid desto */
      my_free(newpath);
      my_free(s);
      my_free(newfn);
      return TCL_OK;
    }
  } else
    malloc_strcpy(newfn, "");
  my_free(s);

  /* Stupidness checks */
  if ((!strcmp(oldpath, newpath)) &&
      (!newfn[0] || !strcmp(newfn, fn))) {
    my_free(newfn);
    my_free(fn);
    my_free(oldpath);
    my_free(newpath);
    Tcl_AppendResult(irp, "-3", NULL);	/* Stupid copy to self */
    return TCL_OK;
  }
  /* Be aware of 'cp * this.file' possibility: ONLY COPY FIRST ONE */
  if ((strchr(fn, '?') || strchr(fn, '*')) && newfn[0])
    only_first = 1;
  else
    only_first = 0;

  fdb_old = filedb_open(oldpath, 0);
  if (!strcmp(oldpath, newpath))
    fdb_new = fdb_old;
  else
    fdb_new = filedb_open(newpath, 0);
  if (!fdb_old || !fdb_new) {
    my_free(newfn);
    my_free(fn);
    my_free(oldpath);
    my_free(newpath);
    if (fdb_old)
      filedb_close(fdb_old);
    else if (fdb_new)
      filedb_close(fdb_new);
    Tcl_AppendResult(irp, "-5", NULL);	/* DB access failed */
    return -1;
  }

  filedb_readtop(fdb_old, NULL);
  fdbe_old = filedb_matchfile(fdb_old, ftell(fdb_old), fn);
  if (!fdbe_old) {
    my_free(newfn);
    my_free(fn);
    my_free(oldpath);
    my_free(newpath);
    if (fdb_new != fdb_old)
      filedb_close(fdb_new);
    filedb_close(fdb_old);
    Tcl_AppendResult(irp, "-4", NULL);  /* No match */
    return -2;
  }
  while (fdbe_old) {
    where = ftell(fdb_old);
    skip_this = 0;
    if (!(fdbe_old->stat & (FILE_HIDDEN | FILE_DIR))) {
      s = nmalloc(strlen(dccdir) + strlen(oldpath)
		  + strlen(fdbe_old->filename) + 2);
      s1 = nmalloc(strlen(dccdir) + strlen(newpath)
		   + strlen(newfn[0] ? newfn : fdbe_old->filename) + 2);
      sprintf(s, "%s%s%s%s", dccdir, oldpath,
	      oldpath[0] ? "/" : "", fdbe_old->filename);
      sprintf(s1, "%s%s%s%s", dccdir, newpath,
	      newpath[0] ? "/" : "", newfn[0] ? newfn : fdbe_old->filename);
      if (!strcmp(s, s1)) {
	Tcl_AppendResult(irp, "-3", NULL); /* Stupid copy to self */
	skip_this = 1;
      }
      /* Check for existence of file with same name in new dir */
      filedb_readtop(fdb_new, NULL);
      fdbe_new = filedb_matchfile(fdb_new, ftell(fdb_new),
				  newfn[0] ? newfn : fdbe_old->filename);
      if (fdbe_new) {
	/* It's ok if the entry in the new dir is a normal file (we'll
	 * just scrap the old entry and overwrite the file) -- but if
	 * it's a directory, this file has to be skipped.
	 */
	if (fdbe_new->stat & FILE_DIR) {
	  /* Skip */
	  skip_this = 1;
	} else {
	  filedb_delfile(fdb_new, fdbe_new->pos);
	}
	free_fdbe(&fdbe_new);
      }
      if (!skip_this) {
	if ((fdbe_old->sharelink) || (copyfile(s, s1) == 0)) {
	  /* Raw file moved okay: create new entry for it */
	  ok++;
	  fdbe_new = malloc_fdbe();
	  fdbe_new->stat = fdbe_old->stat;
	  /* We don't have to worry about any entries to be
	   * NULL, because malloc_strcpy takes care of that.
	   */
	  malloc_strcpy(fdbe_new->flags_req, fdbe_old->flags_req);
	  malloc_strcpy(fdbe_new->chan, fdbe_old->chan);
	  malloc_strcpy(fdbe_new->filename, fdbe_old->filename);
	  malloc_strcpy(fdbe_new->desc, fdbe_old->desc);
	  if (newfn[0])
	    malloc_strcpy(fdbe_new->filename, newfn);
	  malloc_strcpy(fdbe_new->uploader, fdbe_old->uploader);
	  fdbe_new->uploaded = fdbe_old->uploaded;
	  fdbe_new->size = fdbe_old->size;
	  fdbe_new->gots = fdbe_old->gots;
	  malloc_strcpy(fdbe_new->sharelink, fdbe_old->sharelink);
	  filedb_addfile(fdb_new, fdbe_new);
	  if (!copy) {
	    unlink(s);
	    filedb_delfile(fdb_old, fdbe_old->pos);
	  }
	  free_fdbe(&fdbe_new);
	}
      }
      my_free(s);
      my_free(s1);
    }
    free_fdbe(&fdbe_old);
    fdbe_old = filedb_matchfile(fdb_old, where, fn);
    if (ok && only_first) {
      free_fdbe(&fdbe_old);
    }
  }
  if (fdb_old != fdb_new)
    filedb_close(fdb_new);
  filedb_close(fdb_old);
  if (!ok)
    Tcl_AppendResult(irp, "-4", NULL);	/* No match */
  else {
    char x[30];

    sprintf(x, "%d", ok);
    Tcl_AppendResult(irp, x, NULL);
  }
  my_free(newfn);
  my_free(fn);
  my_free(oldpath);
  my_free(newpath);
  return TCL_OK;
}
Exemple #23
0
/*
 * hpgps_receive - receive data from the serial interface
 */
static void
hpgps_receive(
	struct recvbuf *rbufp
	)
{
	register struct hpgpsunit *up;
	struct refclockproc *pp;
	struct peer *peer;
	l_fp trtmp;
	char tcodechar1;        /* identifies timecode format */
	char tcodechar2;        /* identifies timecode format */
	char timequal;          /* time figure of merit: 0-9 */
	char freqqual;          /* frequency figure of merit: 0-3 */
	char leapchar;          /* leapsecond: + or 0 or - */
	char servchar;          /* request for service: 0 = no, 1 = yes */
	char syncchar;          /* time info is invalid: 0 = no, 1 = yes */
	short expectedsm;       /* expected timecode byte checksum */
	short tcodechksm;       /* computed timecode byte checksum */
	int i,m,n;
	int month, day, lastday;
	char *tcp;              /* timecode pointer (skips over the prompt) */
	char prompt[BMAX];      /* prompt in response from receiver */

	/*
	 * Initialize pointers and read the receiver response
	 */
	peer = rbufp->recv_peer;
	pp = peer->procptr;
	up = pp->unitptr;
	*pp->a_lastcode = '\0';
	pp->lencode = refclock_gtlin(rbufp, pp->a_lastcode, BMAX, &trtmp);

#ifdef DEBUG
	if (debug)
	    printf("hpgps: lencode: %d timecode:%s\n",
		   pp->lencode, pp->a_lastcode);
#endif

	/*
	 * If there's no characters in the reply, we can quit now
	 */
	if (pp->lencode == 0)
	    return;

	/*
	 * If linecnt is greater than zero, we are getting information only,
	 * such as the receiver identification string or the receiver status
	 * screen, so put the receiver response at the end of the status
	 * screen buffer. When we have the last line, write the buffer to
	 * the clockstats file and return without further processing.
	 *
	 * If linecnt is zero, we are expecting either the timezone
	 * or a timecode. At this point, also write the response
	 * to the clockstats file, and go on to process the prompt (if any),
	 * timezone, or timecode and timestamp.
	 */


	if (up->linecnt-- > 0) {
		if ((int)(pp->lencode + 2) <= (SMAX - (up->lastptr - up->statscrn))) {
			*up->lastptr++ = '\n';
			memcpy(up->lastptr, pp->a_lastcode, pp->lencode);
			up->lastptr += pp->lencode;
		}
		if (up->linecnt == 0) 
		    record_clock_stats(&peer->srcadr, up->statscrn);
               
		return;
	}

	record_clock_stats(&peer->srcadr, pp->a_lastcode);
	pp->lastrec = trtmp;
            
	up->lastptr = up->statscrn;
	*up->lastptr = '\0';
	up->pollcnt = 2;

	/*
	 * We get down to business: get a prompt if one is there, issue
	 * a clear status command if it contains an error indication.
	 * Next, check for either the timezone reply or the timecode reply
	 * and decode it.  If we don't recognize the reply, or don't get the
	 * proper number of decoded fields, or get an out of range timezone,
	 * or if the timecode checksum is bad, then we declare bad format
	 * and exit.
	 *
	 * Timezone format (including nominal prompt):
	 * scpi > -H,-M<cr><lf>
	 *
	 * Timecode format (including nominal prompt):
	 * scpi > T2yyyymmddhhmmssMFLRVcc<cr><lf>
	 *
	 */

	strlcpy(prompt, pp->a_lastcode, sizeof(prompt));
	tcp = strrchr(pp->a_lastcode,'>');
	if (tcp == NULL)
	    tcp = pp->a_lastcode; 
	else
	    tcp++;
	prompt[tcp - pp->a_lastcode] = '\0';
	while ((*tcp == ' ') || (*tcp == '\t')) tcp++;

	/*
	 * deal with an error indication in the prompt here
	 */
	if (strrchr(prompt,'E') > strrchr(prompt,'s')){
#ifdef DEBUG
		if (debug)
		    printf("hpgps: error indicated in prompt: %s\n", prompt);
#endif
		if (write(pp->io.fd, "*CLS\r\r", 6) != 6)
		    refclock_report(peer, CEVNT_FAULT);
	}

	/*
	 * make sure we got a timezone or timecode format and 
	 * then process accordingly
	 */
	m = sscanf(tcp,"%c%c", &tcodechar1, &tcodechar2);

	if (m != 2){
#ifdef DEBUG
		if (debug)
		    printf("hpgps: no format indicator\n");
#endif
		refclock_report(peer, CEVNT_BADREPLY);
		return;
	}

	switch (tcodechar1) {

	    case '+':
	    case '-':
		m = sscanf(tcp,"%d,%d", &up->tzhour, &up->tzminute);
		if (m != MTZONE) {
#ifdef DEBUG
			if (debug)
			    printf("hpgps: only %d fields recognized in timezone\n", m);
#endif
			refclock_report(peer, CEVNT_BADREPLY);
			return;
		}
		if ((up->tzhour < -12) || (up->tzhour > 13) || 
		    (up->tzminute < -59) || (up->tzminute > 59)){
#ifdef DEBUG
			if (debug)
			    printf("hpgps: timezone %d, %d out of range\n",
				   up->tzhour, up->tzminute);
#endif
			refclock_report(peer, CEVNT_BADREPLY);
			return;
		}
		return;

	    case 'T':
		break;

	    default:
#ifdef DEBUG
		if (debug)
		    printf("hpgps: unrecognized reply format %c%c\n",
			   tcodechar1, tcodechar2);
#endif
		refclock_report(peer, CEVNT_BADREPLY);
		return;
	} /* end of tcodechar1 switch */


	switch (tcodechar2) {

	    case '2':
		m = sscanf(tcp,"%*c%*c%4d%2d%2d%2d%2d%2d%c%c%c%c%c%2hx",
			   &pp->year, &month, &day, &pp->hour, &pp->minute, &pp->second,
			   &timequal, &freqqual, &leapchar, &servchar, &syncchar,
			   &expectedsm);
		n = NTCODET2;

		if (m != MTCODET2){
#ifdef DEBUG
			if (debug)
			    printf("hpgps: only %d fields recognized in timecode\n", m);
#endif
			refclock_report(peer, CEVNT_BADREPLY);
			return;
		}
		break;

	    default:
#ifdef DEBUG
		if (debug)
		    printf("hpgps: unrecognized timecode format %c%c\n",
			   tcodechar1, tcodechar2);
#endif
		refclock_report(peer, CEVNT_BADREPLY);
		return;
	} /* end of tcodechar2 format switch */
           
	/* 
	 * Compute and verify the checksum.
	 * Characters are summed starting at tcodechar1, ending at just
	 * before the expected checksum.  Bail out if incorrect.
	 */
	tcodechksm = 0;
	while (n-- > 0) tcodechksm += *tcp++;
	tcodechksm &= 0x00ff;

	if (tcodechksm != expectedsm) {
#ifdef DEBUG
		if (debug)
		    printf("hpgps: checksum %2hX doesn't match %2hX expected\n",
			   tcodechksm, expectedsm);
#endif
		refclock_report(peer, CEVNT_BADREPLY);
		return;
	}

	/* 
	 * Compute the day of year from the yyyymmdd format.
	 */
	if (month < 1 || month > 12 || day < 1) {
		refclock_report(peer, CEVNT_BADTIME);
		return;
	}

	if ( ! isleap_4(pp->year) ) {				/* Y2KFixes */
		/* not a leap year */
		if (day > day1tab[month - 1]) {
			refclock_report(peer, CEVNT_BADTIME);
			return;
		}
		for (i = 0; i < month - 1; i++) day += day1tab[i];
		lastday = 365;
	} else {
		/* a leap year */
		if (day > day2tab[month - 1]) {
			refclock_report(peer, CEVNT_BADTIME);
			return;
		}
		for (i = 0; i < month - 1; i++) day += day2tab[i];
		lastday = 366;
	}

	/*
	 * Deal with the timezone offset here. The receiver timecode is in
	 * local time = UTC + :PTIME:TZONE, so SUBTRACT the timezone values.
	 * For example, Pacific Standard Time is -8 hours , 0 minutes.
	 * Deal with the underflows and overflows.
	 */
	pp->minute -= up->tzminute;
	pp->hour -= up->tzhour;

	if (pp->minute < 0) {
		pp->minute += 60;
		pp->hour--;
	}
	if (pp->minute > 59) {
		pp->minute -= 60;
		pp->hour++;
	}
	if (pp->hour < 0)  {
		pp->hour += 24;
		day--;
		if (day < 1) {
			pp->year--;
			if ( isleap_4(pp->year) )		/* Y2KFixes */
			    day = 366;
			else
			    day = 365;
		}
	}

	if (pp->hour > 23) {
		pp->hour -= 24;
		day++;
		if (day > lastday) {
			pp->year++;
			day = 1;
		}
	}

	pp->day = day;

	/*
	 * Decode the MFLRV indicators.
	 * NEED TO FIGURE OUT how to deal with the request for service,
	 * time quality, and frequency quality indicators some day. 
	 */
	if (syncchar != '0') {
		pp->leap = LEAP_NOTINSYNC;
	}
	else {
		pp->leap = LEAP_NOWARNING;
		switch (leapchar) {

		    case '0':
			break;
                     
		    /* See http://bugs.ntp.org/1090
		     * Ignore leap announcements unless June or December.
		     * Better would be to use :GPSTime? to find the month,
		     * but that seems too likely to introduce other bugs.
		     */
		    case '+':
			if ((month==6) || (month==12))
			    pp->leap = LEAP_ADDSECOND;
			break;
                     
		    case '-':
			if ((month==6) || (month==12))
			    pp->leap = LEAP_DELSECOND;
			break;
                     
		    default:
#ifdef DEBUG
			if (debug)
			    printf("hpgps: unrecognized leap indicator: %c\n",
				   leapchar);
#endif
			refclock_report(peer, CEVNT_BADTIME);
			return;
		} /* end of leapchar switch */
	}

	/*
	 * Process the new sample in the median filter and determine the
	 * reference clock offset and dispersion. We use lastrec as both
	 * the reference time and receive time in order to avoid being
	 * cute, like setting the reference time later than the receive
	 * time, which may cause a paranoid protocol module to chuck out
	 * the data.
	 */
	if (!refclock_process(pp)) {
		refclock_report(peer, CEVNT_BADTIME);
		return;
	}
	pp->lastref = pp->lastrec;
	refclock_receive(peer);

	/*
	 * If CLK_FLAG4 is set, ask for the status screen response.
	 */
	if (pp->sloppyclockflag & CLK_FLAG4){
		up->linecnt = 22; 
		if (write(pp->io.fd, ":SYSTEM:PRINT?\r", 15) != 15)
		    refclock_report(peer, CEVNT_FAULT);
	}
}
Exemple #24
0
static window_event_result browser_handler(UI_DIALOG *const dlg, const d_event &event, ui_file_browser *const b)
{
	window_event_result rval = window_event_result::ignored;

	if (event.type == EVENT_UI_DIALOG_DRAW)
	{
		ui_dputs_at( dlg, 10, 5, b->message );

		ui_dprintf_at( dlg, 20, 32,"N&ame" );
		ui_dprintf_at( dlg, 20, 86,"&Files" );
		ui_dprintf_at( dlg, 210, 86,"&Dirs" );
		
		ui_dputs_at(dlg, 20, 60, b->spaces.data());
		ui_dputs_at( dlg, 20, 60, b->view_dir );
		
		return window_event_result::handled;
	}

	if (GADGET_PRESSED(b->button2.get()))
	{
		b->filename_list.reset();
		b->directory_list.reset();
		return window_event_result::close;
	}
	
	if (GADGET_PRESSED(b->help_button.get()))
	{
		ui_messagebox( -1, -1, 1, "Sorry, no help is available!", "Ok" );
		rval = window_event_result::handled;
	}
	
	if (event.type == EVENT_UI_LISTBOX_MOVED)
	{
		if ((ui_event_get_gadget(event) == b->listbox1.get()) && (b->listbox1->current_item >= 0) && b->filename_list[b->listbox1->current_item])
			ui_inputbox_set_text(b->user_file.get(), b->filename_list[b->listbox1->current_item]);

		if ((ui_event_get_gadget(event) == b->listbox2.get()) && (b->listbox2->current_item >= 0) && b->directory_list[b->listbox2->current_item])
			ui_inputbox_set_text(b->user_file.get(), b->directory_list[b->listbox2->current_item]);

		rval = window_event_result::handled;
	}
	
	if (GADGET_PRESSED(b->button1.get()) || GADGET_PRESSED(b->user_file.get()) || event.type == EVENT_UI_LISTBOX_SELECTED)
	{
		char *p;
		
		if (ui_event_get_gadget(event) == b->listbox2.get())
			strcpy(b->user_file->text.get(), b->directory_list[b->listbox2->current_item]);
		
		strncpy(b->filename, b->view_dir, PATH_MAX);
		
		p = b->user_file->text.get();
		while (!strncmp(p, "..", 2))	// shorten the path manually
		{
			char *sep = strrchr(b->filename, '/');
			if (sep)
				*sep = 0;
			else
				*b->filename = 0;	// look directly in search paths
			
			p += 2;
			if (*p == '/')
				p++;
		}
		
		if (*b->filename && *p)
			strncat(b->filename, "/", PATH_MAX - strlen(b->filename));
		strncat(b->filename, p, PATH_MAX - strlen(b->filename));
		
		if (!PHYSFS_isDirectory(b->filename))
		{
			if (RAIIPHYSFS_File{PHYSFS_openRead(b->filename)})
			{
				// Looks like a valid filename that already exists!
				return window_event_result::close;
			}
			
			// File doesn't exist, but can we create it?
			if (RAIIPHYSFS_File TempFile{PHYSFS_openWrite(b->filename)})
			{
				TempFile.reset();
				// Looks like a valid filename!
				PHYSFS_delete(b->filename);
				return window_event_result::close;
			}
		}
		else
		{
			if (b->filename[strlen(b->filename) - 1] == '/')	// user typed a separator on the end
				b->filename[strlen(b->filename) - 1] = 0;
			
			strcpy(b->view_dir, b->filename);
			b->filename_list = file_getfilelist(b->filespec, b->view_dir);
			if (!b->filename_list)
			{
				b->directory_list.reset();
				return window_event_result::close;
			}
			
			ui_inputbox_set_text(b->user_file.get(), b->filespec);
			b->directory_list = file_getdirlist(b->view_dir);
			if (!b->directory_list)
			{
				b->filename_list.reset();
				return window_event_result::close;
			}
			
			ui_listbox_change(dlg, b->listbox1.get(), b->filename_list.get_count(), b->filename_list.get());
			ui_listbox_change(dlg, b->listbox2.get(), b->directory_list.get_count(), b->directory_list.get());
			
			//i = TICKER;
			//while ( TICKER < i+2 );
			
		}
		
		rval = window_event_result::handled;
	}
	
	return rval;
}
Exemple #25
0
/*
 * NAME:	hfs->rename()
 * DESCRIPTION:	change the name of and/or move a file or directory
 */
int hfs_rename(hfsvol *vol, char *srcpath, char *dstpath)
{
  hfsvol *srcvol;
  CatDataRec src, dst;
  long srcid, dstid;
  CatKeyRec key;
  char srcname[HFS_MAX_FLEN + 1], dstname[HFS_MAX_FLEN + 1];
  unsigned char record[HFS_CATRECMAXLEN];
  int found, isdir, moving, reclen;
  node n;

  if (v_getvol(&vol) < 0 ||
      v_resolve(&vol, srcpath, &src, &srcid, srcname, 0) <= 0)
    return -1;

  isdir  = (src.cdrType == cdrDirRec);
  srcvol = vol;

  found = v_resolve(&vol, dstpath, &dst, &dstid, dstname, 0);
  if (found < 0)
    return -1;

  if (vol != srcvol)
    {
      ERROR(EINVAL, "can't move across volumes");
      return -1;
    }

  if (dstid == 0)
    {
      ERROR(ENOENT, "bad destination path");
      return -1;
    }

  if (found &&
      dst.cdrType == cdrDirRec &&
      dst.u.dir.dirDirID != src.u.dir.dirDirID)
    {
      dstid = dst.u.dir.dirDirID;
      strcpy(dstname, srcname);

      found = v_catsearch(vol, dstid, dstname, 0, 0, 0);
      if (found < 0)
	return -1;
    }

  moving = (srcid != dstid);

  if (found)
    {
      char *ptr;

      ptr = strrchr(dstpath, ':');
      if (ptr == 0)
	ptr = dstpath;
      else
	++ptr;

      if (*ptr)
	strcpy(dstname, ptr);

      if (! moving && strcmp(srcname, dstname) == 0)
	return 0;  /* source and destination are the same */

      if (moving || d_relstring(srcname, dstname))
	{
	  ERROR(EEXIST, "can't use destination name");
	  return -1;
	}
    }

  /* can't move anything into the root directory's parent */

  if (moving && dstid == HFS_CNID_ROOTPAR)
    {
      ERROR(EINVAL, "can't move above root directory");
      return -1;
    }

  if (moving && isdir)
    {
      long id;

      /* can't move root directory anywhere */

      if (src.u.dir.dirDirID == HFS_CNID_ROOTDIR)
	{
	  ERROR(EINVAL, "can't move root directory");
	  return -1;
	}

      /* make sure we aren't trying to move a directory inside itself */

      for (id = dstid; id != HFS_CNID_ROOTDIR; id = dst.u.dthd.thdParID)
	{
	  if (id == src.u.dir.dirDirID)
	    {
	      ERROR(EINVAL, "can't move directory inside itself");
	      return -1;
	    }

	  if (v_getdthread(vol, id, &dst, 0) <= 0)
	    return -1;
	}
    }

  if (vol->flags & HFS_READONLY)
    {
      ERROR(EROFS, 0);
      return -1;
    }

  /* change volume name */

  if (dstid == HFS_CNID_ROOTPAR)
    {
      if (strlen(dstname) > HFS_MAX_VLEN)
	{
	  ERROR(ENAMETOOLONG, 0);
	  return -1;
	}

      strcpy(vol->mdb.drVN, dstname);
      vol->flags |= HFS_UPDATE_MDB;
    }

  /* remove source record */

  r_makecatkey(&key, srcid, srcname);
  r_packcatkey(&key, record, 0);

  if (bt_delete(&vol->cat, record) < 0)
    return -1;

  /* insert destination record */

  r_makecatkey(&key, dstid, dstname);
  r_packcatkey(&key, record, &reclen);
  r_packcatdata(&src, HFS_RECDATA(record), &reclen);

  if (bt_insert(&vol->cat, record, reclen) < 0)
    return -1;

  /* update thread record */

  if (isdir)
    {
      if (v_getdthread(vol, src.u.dir.dirDirID, &dst, &n) <= 0)
	return -1;

      dst.u.dthd.thdParID = dstid;
      strcpy(dst.u.dthd.thdCName, dstname);

      if (v_putcatrec(&dst, &n) < 0)
	return -1;
    }
  else
    {
      found = v_getfthread(vol, src.u.fil.filFlNum, &dst, &n);
      if (found < 0)
	return -1;

      if (found)
	{
	  dst.u.fthd.fthdParID = dstid;
	  strcpy(dst.u.fthd.fthdCName, dstname);

	  if (v_putcatrec(&dst, &n) < 0)
	    return -1;
	}
    }

  /* update directory valences */

  if (moving)
    {
      if (v_adjvalence(vol, srcid, isdir, -1) < 0 ||
	  v_adjvalence(vol, dstid, isdir,  1) < 0)
	return -1;
    }

  return 0;
}
Exemple #26
0
int ui_get_filename(char (&filename)[PATH_MAX], const char *const filespec, const char *const message)
{
	char		InputText[PATH_MAX];
	char		*p;
	UI_DIALOG	*dlg;
	int			rval = 0;
	auto b = make_unique<ui_file_browser>();
	if ((p = strrchr(filename, '/')))
	{
		*p++ = 0;
		strcpy(b->view_dir, filename);
		strcpy(InputText, p);
	}
	else
	{
		strcpy(b->view_dir, "");
		strcpy(InputText, filename);
	}

	b->filename_list = file_getfilelist(filespec, b->view_dir);
	if (!b->filename_list)
	{
		return 0;
	}
	
	b->directory_list = file_getdirlist(b->view_dir);
	if (!b->directory_list)
	{
		b->filename_list.reset();
		return 0;
	}

	//ui_messagebox( -2,-2, 1,"DEBUG:0", "Ok" );
	for (int i=0; i<35; i++)
		b->spaces[i] = ' ';
	b->spaces[34] = 0;

	dlg = ui_create_dialog( 200, 100, 400, 370, static_cast<dialog_flags>(DF_DIALOG | DF_MODAL), browser_handler, b.get());

	b->user_file  = ui_add_gadget_inputbox<40>(dlg, 60, 30, InputText);

	b->listbox1 = ui_add_gadget_listbox(dlg,  20, 110, 125, 200, b->filename_list.get_count(), b->filename_list.get());
	b->listbox2 = ui_add_gadget_listbox(dlg, 210, 110, 100, 200, b->directory_list.get_count(), b->directory_list.get());

	b->button1 = ui_add_gadget_button( dlg,     20, 330, 60, 25, "Ok", NULL );
	b->button2 = ui_add_gadget_button( dlg,    100, 330, 60, 25, "Cancel", NULL );
	b->help_button = ui_add_gadget_button( dlg, 180, 330, 60, 25, "Help", NULL );

	dlg->keyboard_focus_gadget = b->user_file.get();

	b->button1->hotkey = KEY_CTRLED + KEY_ENTER;
	b->button2->hotkey = KEY_ESC;
	b->help_button->hotkey = KEY_F1;
	b->listbox1->hotkey = KEY_ALTED + KEY_F;
	b->listbox2->hotkey = KEY_ALTED + KEY_D;
	b->user_file->hotkey = KEY_ALTED + KEY_A;

	ui_gadget_calc_keys(dlg);

	b->filename = filename;
	b->filespec = filespec;
	b->message = message;
	
	event_process_all();

	//key_flush();

	rval = static_cast<bool>(b->filename_list);
	b->filename_list.reset();
	b->directory_list.reset();
	return rval;
}
Exemple #27
0
int main( int pArgc, const char** pArgs )
{
   const char* lQueryPtr;
   char  lQuery[4096];
   char  lOp[12];
   char* lPathEnd;
   union semun lNULL;
   int   lLock;        /* Semaphore */
   int   lMemId;       /* Shared memory */
   struct sembuf lSemOp;
   union  semun lArg;

   int          lDuration;
   char         lTrackName[80];
   char         lUser[80];
   unsigned int lChkSum;
   int          lCraft;

   int          lTotalTime;
   int          lNbLap;
   int          lNbPlayer;


   #ifdef _NO_IPC_
 
      gGlobalState.Read();
   #endif


   #ifdef _FAST_CGI_
   while( FCGI_Accept() >= 0 )
   #endif
   {
      lQuery[0] = 0;
      lOp[0]    = 0;

      if( getenv( "DOCUMENT_NAME" ) != NULL )
      {
         if( pArgc >=2 )
         {
            sprintf( lQuery, "=%s", pArgs[1] );
         }

      }
      else
      {
         /* Send the header required by the server in in CGI mode */
         printf("Content-type: text/plain%c%c", 10, 10);


         lQueryPtr = getenv( "QUERY_STRING" );


         if( lQueryPtr != NULL )
         {
            StrMaxCopy( lQuery, lQueryPtr, 4096 );
            UnpadQuery( lQuery );
         }
      }

      #ifndef _FAST_CGI_
         /* Change the local directory */
         lPathEnd = strrchr( pArgs[0], '/' );

         if( lPathEnd != NULL )
         {
            *lPathEnd = 0;
            chdir( pArgs[0] );
         }
      #endif



      sscanf( lQuery, "=%11s", lOp );


      if( !strcmp( lOp, "RESET" ) )
      {
         printf( "RESET OK\n\n" );

         #ifdef _NO_IPC_
            /*
            // gGlobalState.Clear();
            // sleep( 2 );
            // return 0;
            // break;
            */
         #else

            lLock  = semget( IR_SEM_KEY, 1, 0777 );
            lMemId = shmget( IR_SHMEM_KEY, 1 /*sizeof( ISState )*/, 0666 );

            if( lLock != -1 )
            {

               semctl( lLock, 0, IPC_RMID, lNULL );
            }

            if( lMemId != -1 )
            {
               shmctl( lMemId, IPC_RMID, NULL );
            }

         #endif


         #ifdef _FAST_CGI_
            break;
         #endif

      }
      else
      {
         ISState* lState = NULL;

         #ifdef _NO_IPC_
            lState = &gGlobalState;

         #else


            lSemOp.sem_flg = 0;  /*Avoid corruption but must not core-dump SEM_UNDO;  // Risky but prevents dead-lock */
            lSemOp.sem_num  = 0;

            /* First try to create the structure for the first time */
            /* Lock the data struct */
            lLock = semget( IR_SEM_KEY, 1, 0777|IPC_CREAT|IPC_EXCL );

            if( lLock != -1 )
            {
               
               /* Initialize the newly created semaphore */
               lArg.val = 1;
 
               semctl( lLock, 0, SETVAL, lArg );
            }
            else
            {
               lLock = semget( IR_SEM_KEY, 1, 0777 );
            }

            if( lLock == -1 )
            {
               printf( "Unable to get semaphore\n" );
            }
            else
            {
               lSemOp.sem_op   = -1;

               if( semop( lLock, &lSemOp, 1 ) == -1 )
               {
                  printf( "Unable to decrement semaphore\n" );
                  lLock = -1;
               }
               else
               {

                  /* From here we can work safely */

                  lMemId = shmget( IR_SHMEM_KEY, sizeof( ISState ), 0666|IPC_CREAT|IPC_EXCL );

                  if( lMemId != -1 )
                  {
                     lState = (ISState*)shmat( lMemId, NULL, 0 );

                     if( (int)lState == -1 )
                     {
                        lState = NULL;
                     }

                     if( lState == NULL )
                     {
                        printf( "Unable to attach shmem\n" );
                     }
                     else
                     {
                        StateRead( lState );

                     }
                  }
                  else
                  {
                     lMemId = shmget( IR_SHMEM_KEY, sizeof( ISState ), 0666 );

                     if( lMemId == -1 )
                     {
                        printf( "Unable to get shmem\n" );
                     }
                     else
                     {
                        lState = (ISState*)shmat( lMemId, NULL, 0 );

                        if( (int)lState == -1 )
                        {
                           lState = NULL;
                        }

                        if( lState == NULL )
                        {
                           printf( "Unable to attach shmem\n" );
                        }
                     }
                  }
               }
            }

         #endif
   
         if( lState != NULL )
         {
            if( !strcmp( lOp, "BESTLAPS" )  )
            {

               /* Return the score table */
               StatePrintLap( lState, 0 );
            }
            else if( !strcmp( lOp, "BESTLAPS1" )  )
            {
               StatePrintLap( lState, 1 );
            }
            else if( !strcmp( lOp, "BESTLAPS2" )  )
            {
               StatePrintLap( lState, 2 );
            }
            else if( !strcmp( lOp, "BESTTIME1" )  )
            {
               StatePrintRace( lState, 0 );
            }
            else if( !strcmp( lOp, "BESTTIME2" )  )
            {
               StatePrintRace( lState, 1 );
            }
            else if( !strcmp( lOp, "BESTTIME3" )  )
            {
               StatePrintRace( lState, 2 );
            }
            else if( !strcmp( lOp, "BESTTIME4" )  )
            {
               StatePrintRace( lState, 3 );
            }
            else if( !strcmp( lOp, "BESTTIME5" )  )
            {
               StatePrintRace( lState, 4 );
            }
            else if( !strcmp( lOp, "LAPTIME" ) )
            {

               if( sscanf( lQuery, "%*s %d %s %s %u %d", &lDuration, lTrackName, lUser, &lChkSum, &lCraft )==5 )
               {
                  Unpad( lTrackName );
                  Unpad( lUser );
                  Filter( lUser );

                  StateAddLapRecord( lState, lTrackName, lChkSum, lUser, lDuration, lCraft );                  
               }
               printf( "OK\n\n" );
            }
            else if( !strcmp( lOp, "RESULT" ) )
            {
               if( sscanf( lQuery, "%*s %d %s %s %u %d %d %d %d", &lDuration, lTrackName, lUser, &lChkSum, &lCraft, &lTotalTime, &lNbLap, &lNbPlayer )==8 )
               {
                  Unpad( lTrackName );
                  Unpad( lUser );
                  Filter( lUser );

                  StateAddLapRecord( lState, lTrackName, lChkSum, lUser, lDuration, lCraft );
                  StateAddRaceRecord( lState, lTrackName, lChkSum, lUser, lTotalTime, lCraft, lNbLap, lNbPlayer );
               }
               printf( "OK\n\n" );
   
            }
            else if( !strcmp( lOp, "RESET_WEEK" ) )
            {
               StateResetWeekly( lState );
               printf( "RESET_WEEK OK\n\n" );
            }
            else
            {
               printf( "Score Server (c)1997 GrokkSoft inc.\n\n" );
            }
         }

         #ifdef _NO_IPC_
            lState = NULL;
         #else
   
            /* Release lock */
            if( lLock != -1 )
            {
               lSemOp.sem_op   = 1;

               semop( lLock, &lSemOp, 1 );

               /* Release memory */
               if( lState != NULL )
               {
                  shmdt( (char*)lState );
               }
            }
                  
         #endif               
      }
   }

   return 0;
}
Exemple #28
0
struct model *load_obj_from_memory(const char *filename, unsigned char *data, int len)
{
	char dirname[1024];
	char *line, *next, *p, *s;
	struct model *model;
	struct mesh *mesh;
	int fvp[20], fvt[20], fvn[20];
	int first, material;
	int i, n;

	printf("loading obj model '%s'\n", filename);

	strlcpy(dirname, filename, sizeof dirname);
	p = strrchr(dirname, '/');
	if (!p) p = strrchr(dirname, '\\');
	if (p) *p = 0;
	else strlcpy(dirname, "", sizeof dirname);

	mtl_count = 0;
	position.len = 0;
	texcoord.len = 0;
	normal.len = 0;
	element.len = 0;
	part.len = 0;

	first = 0;
	material = 0;

	data[len-1] = 0; /* over-write final newline to zero-terminate */

	for (line = (char*)data; line; line = next) {
		next = strchr(line, '\n');
		if (next)
			*next++ = 0;

		s = strtok(line, SEP);
		if (!s) {
			continue;
		} else if (!strcmp(s, "v")) {
			char *x = strtok(NULL, SEP);
			char *y = strtok(NULL, SEP);
			char *z = strtok(NULL, SEP);
			add_position(atof(x), atof(y), atof(z));
		} else if (!strcmp(s, "vt")) {
			char *u = strtok(NULL, SEP);
			char *v = strtok(NULL, SEP);
			add_texcoord(atof(u), atof(v));
		} else if (!strcmp(s, "vn")) {
			char *x = strtok(NULL, SEP);
			char *y = strtok(NULL, SEP);
			char *z = strtok(NULL, SEP);
			add_normal(atof(x), atof(y), atof(z));
		} else if (!strcmp(s, "f")) {
			n = 0;
			s = strtok(NULL, SEP);
			while (s) {
				if (*s) {
					splitfv(s, fvp+n, fvn+n, fvt+n);
					n++;
				}
				s = strtok(NULL, SEP);
			}
			for (i = 1; i < n - 1; i++) {
				add_triangle(fvp[0], fvn[0], fvt[0],
					fvp[i], fvn[i], fvt[i],
					fvp[i+1], fvn[i+1], fvt[i+1]);
			}
		} else if (!strcmp(s, "mtllib")) {
			s = strtok(NULL, SEP);
			mtllib(dirname, s);
		} else if (!strcmp(s, "usemtl")) {
			if (element.len > first)
				push_part(&part, first, element.len, material);
			s = strtok(NULL, SEP);
			material = usemtl(s);
			first = element.len;
		}
	}

	if (element.len > first)
		push_part(&part, first, element.len, material);

	printf("\t%d parts; %d vertices; %d triangles", part.len, vertex.len/8, element.len/3);

	mesh = malloc(sizeof(struct mesh));
	mesh->tag = TAG_MESH;
	mesh->enabled = 1<<ATT_POSITION | 1<<ATT_NORMAL | 1<<ATT_TEXCOORD;
	mesh->skel = NULL;
	mesh->inv_bind_matrix = NULL;
	mesh->count = part.len;
	mesh->part = malloc(part.len * sizeof(struct part));
	memcpy(mesh->part, part.data, part.len * sizeof(struct part));

	glGenVertexArrays(1, &mesh->vao);
	glGenBuffers(1, &mesh->vbo);
	glGenBuffers(1, &mesh->ibo);

	glBindVertexArray(mesh->vao);
	glBindBuffer(GL_ARRAY_BUFFER, mesh->vbo);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->ibo);

	glBufferData(GL_ARRAY_BUFFER, vertex.len * 4, vertex.data, GL_STATIC_DRAW);

	glEnableVertexAttribArray(ATT_POSITION);
	glEnableVertexAttribArray(ATT_NORMAL);
	glEnableVertexAttribArray(ATT_TEXCOORD);
	glVertexAttribPointer(ATT_POSITION, 3, GL_FLOAT, 0, 32, (void*)0);
	glVertexAttribPointer(ATT_NORMAL, 3, GL_FLOAT, 0, 32, (void*)20);
	glVertexAttribPointer(ATT_TEXCOORD, 2, GL_FLOAT, 0, 32, (void*)12);

	glBufferData(GL_ELEMENT_ARRAY_BUFFER, element.len * 2, element.data, GL_STATIC_DRAW);

	model = malloc(sizeof *model);
	model->skel = NULL;
	model->mesh = mesh;
	model->anim = NULL;
	return model;
}
Exemple #29
0
//-----------------------------------------------
// Cut module name to 11 sym
//-----------------------------------------------
static void flat_module_name_make( char* tgt, const char* name )
{
    char *p = strrchr(name,'/');
    strncpy(tgt, (p) ? p+1 : name, 12);
    tgt[11] = 0;
}
Exemple #30
0
static void setup_display(void) {
	XGCValues gv;
	XSetWindowAttributes attr;
	XColor dummy;
	XModifierKeymap *modmap;
	/* used in scanning windows (XQueryTree) */
	unsigned int i, j, nwins;
	Window dw1, dw2, *wins;
	XWindowAttributes winattr;

	LOG_ENTER("setup_display()");

	dpy = XOpenDisplay(opt_display);
	if (!dpy) {
		LOG_ERROR("can't open display %s\n", opt_display);
		exit(1);
	}
	XSetErrorHandler(handle_xerror);
	/* XSynchronize(dpy, True); */

	/* Standard & EWMH atoms */
	ewmh_init();

	font = XLoadQueryFont(dpy, opt_font);
	if (!font) font = XLoadQueryFont(dpy, DEF_FONT);
	if (!font) {
		LOG_ERROR("couldn't find a font to use: try starting with -fn fontname\n");
		exit(1);
	}

	move_curs = XCreateFontCursor(dpy, XC_fleur);
	resize_curs = XCreateFontCursor(dpy, XC_plus);

	/* find out which modifier is NumLock - we'll use this when grabbing
	 * every combination of modifiers we can think of */
	modmap = XGetModifierMapping(dpy);
	for (i = 0; i < 8; i++) {
		for (j = 0; j < (unsigned int)modmap->max_keypermod; j++) {
			if (modmap->modifiermap[i*modmap->max_keypermod+j] == XKeysymToKeycode(dpy, XK_Num_Lock)) {
				numlockmask = (1<<i);
				LOG_DEBUG("XK_Num_Lock is (1<<0x%02x)\n", i);
			}
		}
	}
	XFreeModifiermap(modmap);

	/* set up GC parameters - same for each screen */
	gv.function = GXinvert;
	gv.subwindow_mode = IncludeInferiors;
	gv.line_width = 1;  /* opt_bw */
	gv.font = font->fid;

	/* set up root window attributes - same for each screen */
	attr.event_mask = ChildMask | EnterWindowMask | ColormapChangeMask;

	/* SHAPE extension? */
#ifdef SHAPE
	{
		int e_dummy;
		have_shape = XShapeQueryExtension(dpy, &shape_event, &e_dummy);
	}
#endif
	/* Xrandr extension? */
#ifdef RANDR
	{
		int e_dummy;
		have_randr = XRRQueryExtension(dpy, &randr_event_base, &e_dummy);
		if (!have_randr) {
			LOG_DEBUG("XRandR is not supported on this display.\n");
		}
	}
#endif

	/* now set up each screen in turn */
	num_screens = ScreenCount(dpy);
	if (num_screens < 0) {
		LOG_ERROR("Can't count screens\n");
		exit(1);
	}
	screens = xmalloc(num_screens * sizeof(ScreenInfo));
	for (i = 0; i < (unsigned int)num_screens; i++) {
		char *ds, *colon, *dot;
		ds = DisplayString(dpy);
		/* set up DISPLAY environment variable to use */
		colon = strrchr(ds, ':');
		screens[i].display = xmalloc(14 + strlen(ds));
		strcpy(screens[i].display, "DISPLAY=");
		strcat(screens[i].display, ds);
		if (colon && num_screens > 1) {
			colon = strrchr(screens[i].display, ':');
			dot = strchr(colon, '.');
			if (!dot)
				dot = colon + strlen(colon);
			snprintf(dot, 5, ".%d", i);
		}

		screens[i].screen = i;
		screens[i].root = RootWindow(dpy, i);
#ifdef RANDR
		if (have_randr) {
			XRRSelectInput(dpy, screens[i].root, RRScreenChangeNotifyMask);
		}
#endif
#ifdef VWM
		screens[i].vdesk = KEY_TO_VDESK(XK_1);
#endif

		XAllocNamedColor(dpy, DefaultColormap(dpy, i), opt_fg, &screens[i].fg, &dummy);
		XAllocNamedColor(dpy, DefaultColormap(dpy, i), opt_bg, &screens[i].bg, &dummy);
#ifdef VWM
		XAllocNamedColor(dpy, DefaultColormap(dpy, i), opt_fc, &screens[i].fc, &dummy);
#endif

		screens[i].invert_gc = XCreateGC(dpy, screens[i].root, GCFunction | GCSubwindowMode | GCLineWidth | GCFont, &gv);

		XChangeWindowAttributes(dpy, screens[i].root, CWEventMask, &attr);
		grab_keys_for_screen(&screens[i]);
		screens[i].docks_visible = 1;

		/* scan all the windows on this screen */
		LOG_XENTER("XQueryTree(screen=%d)", i);
		XQueryTree(dpy, screens[i].root, &dw1, &dw2, &wins, &nwins);
		LOG_XDEBUG("%d windows\n", nwins);
		LOG_XLEAVE();
		for (j = 0; j < nwins; j++) {
			XGetWindowAttributes(dpy, wins[j], &winattr);
			if (!winattr.override_redirect && winattr.map_state == IsViewable)
				make_new_client(wins[j], &screens[i]);
		}
		XFree(wins);
		ewmh_init_screen(&screens[i]);
	}
	ewmh_set_net_active_window(NULL);
	LOG_LEAVE();
}