Exemple #1
0
 ITERATE ( vector<string>, it, dirs ) {
     string dir = *it;
     if ( !dir.empty() && !NStr::EndsWith(dir, "/") ) {
         dir += '/';
     }
     string file = args["file"].AsString();
     path = file;
     if ( CFile(path).Exists() ) {
         break;
     }
     path = dir + file;
     if ( CFile(path).Exists() ) {
         break;
     }
     SIZE_TYPE p1 = file.rfind('/');
     if ( p1 == NPOS ) {
         p1 = 0;
     }
     else {
         p1 += 1;
     }
     SIZE_TYPE p2 = file.find('.', p1);
     if ( p2 != NPOS ) {
         path = dir + file.substr(p1, p2-p1) + "/alignment/" + file;
         if ( CFile(path).Exists() ) {
             break;
         }
         path = dir + file.substr(p1, p2-p1) + "/exome_alignment/" + file;
         if ( CFile(path).Exists() ) {
             break;
         }
     }
     path.clear();
 }
//polls directory with _dirname and collect names of playlists 
void CSelectPlayList::LoadPlaylists( std::string _dirname )
{
	/* poll the directory and collect data */
	struct dirent* entry = NULL;
	
	DIR* dir = opendir( _dirname.c_str() );
	
//	std::cout << "Open direcory" << std::endl;
	
	if( NULL == dir )
		return;
	
//	std::cout << "Read direcory" << std::endl;

	if( NULL == ( entry = readdir( dir ) ) )
	{
		/* perhaps some errors, 
		but currently no checks, just exit, 
		assume empty folder */
		return;
	}
	
	while( entry != NULL )
	{
		struct stat status;
		std::string fullname;
		
		fullname += _dirname + "/" + entry->d_name; 
		
		std::cout << "get entry status " << fullname << std::endl;
		
		if( 0 == stat( fullname.c_str(), &status ) )
		{
			if( S_ISREG( status.st_mode ) )
			{
				/* regular file, add it to playlist */
				
				/* check filename extension, has to be mp3  */
				
			
				if( CFile::FILE_RADIOBOX == CFile( fullname ).getType() )
				{
					this->playlists.push_back( CFile( fullname ).getFileName() );
				}
				else
					std::cout << 
						"Baypass file with " << 
						fullname << 
						" extension" << std::endl;
			}
		}
	
		entry = readdir( dir );
	}
		
	closedir( dir );

}
Exemple #3
0
bool
CSoapServerApplication::x_ProcessWsdlRequest(CCgiResponse& response,
                                             const CCgiRequest& request) const
{
    const TCgiEntries& entries = request.GetEntries();
    if (entries.empty()) {
        return false;
    }
    for(TCgiEntries::const_iterator i = entries.begin();
        i != entries.end(); ++i) {
        if (NStr::CompareNocase(i->first, "wsdl") == 0) {
            response.WriteHeader();
            if (!m_Wsdl.empty()) {
                int len = (int)CFile(m_Wsdl).GetLength();
                if (len > 0) {
                    char* buf = new char[len];
                    ifstream iw(m_Wsdl.c_str());
                    iw.read(buf,len);
                    response.out().write(buf,len);
                    delete [] buf;
                }
            }
            return true;
        }
    }
    return false;
}
void CPlayLocation::Show()
{
//	sleep( 1 );
	frame = CLCD::getInstance()->ShowPlayingFile( CFile( playlist->GetCurrentLocation() ).getFileName(),  playlist->GetPositionPercents(), playlist->GetTimePlayed(), frame );

	if( CBaseDec::STOP == playlist->GetState() )
		remove = true;
}
/*
 *	CBoardDevice::Init()
 *
 *  Initializes the device
 *
 *	Returns:	True if the initializing was successful and false if it failed.
 */
bool CBoardDevice::Init(GtkFixed *board_area, CBoardDeviceGroup *device_group)
{
	this->device_group = device_group;

	// Load the bitmap
	GdkPixbuf *bg_pixbuf = gdk_pixbuf_new_from_stream(CFile(image_file.c_str()).get_input_stream(), NULL, NULL);
	if(bg_pixbuf == NULL)
		return false;

	bitmap_x = bitmap_y = 0;
	
	width = gdk_pixbuf_get_width(bg_pixbuf);
	height = gdk_pixbuf_get_height(bg_pixbuf);

	// Check if the type is LED, PUSH or TOGGLE
	if(!strcmp(type.c_str(), "LED") ||
	   !strcmp(type.c_str(), "PUSH") ||
	   !strcmp(type.c_str(), "TOGGLE"))
	{
		// Set the appropriate width and height of the bitmap
		width = width / 2;

		// Check if PUSH because pushbuttons have the value 1 if they are up
		if(!strcmp(type.c_str(), "PUSH"))
			bitmap_x = 1;
	}
	// Check if the type is SSLED
	else if(!strcmp(type.c_str(), "SSLED"))
	{
		// Set the appropriate width and height of the bitmap
		width = width / 8;
		height = height / 16;
	}
	
	GtkWidget *bg_viewport = gtk_viewport_new(NULL, NULL);
	gtk_widget_set_events(bg_viewport, GDK_BUTTON_RELEASE_MASK);
	g_signal_connect(G_OBJECT(bg_viewport), "button-press-event", G_CALLBACK(device_button_pressed), this);
	g_signal_connect(G_OBJECT(bg_viewport), "button-release-event", G_CALLBACK(device_button_released), this);
	gtk_widget_show(bg_viewport);
	
	GtkWidget *bg_image = gtk_image_new_from_pixbuf(bg_pixbuf);
	gtk_widget_show(bg_image);
	
	gtk_container_add((GtkContainer*)bg_viewport, bg_image);
	gtk_viewport_set_shadow_type((GtkViewport*)bg_viewport, GTK_SHADOW_NONE);
	gtk_widget_set_size_request(bg_viewport, width, height);
	gtk_adjustment_set_upper(gtk_viewport_get_hadjustment((GtkViewport*)bg_viewport), width);
	gtk_adjustment_set_upper(gtk_viewport_get_vadjustment((GtkViewport*)bg_viewport), height);
	gtk_fixed_put(board_area, bg_viewport, coords.x, coords.y);
	
	g_object_unref(bg_pixbuf);
	
	viewport = (GtkViewport*)bg_viewport;
	
	ShowCorrectImage();

	return true;
}
LRESULT CDIBitmap::Save(string BitmapFileName,LPRECT lpRect){
	if (m_hDC == NULL) return 0;	//	Openしていないファイル

	RECT rc;
	if (lpRect==NULL) {
		SetRect(&rc,0,0,m_nSizeX,m_nSizeY);
		lpRect = &rc;
	}

	WARNING(rc.left < 0 || rc.top < 0 || rc.right>m_nSizeX || rc.bottom>m_nSizeY,
		"CDIBitmap::Saveで矩形外が指定されている。");

	//	ビットマップメモリ確保
	long lPitch = ((lpRect->right - lpRect->left)*3 + 3) & ~3;	// 一ライン当たりのバイト数
	long size = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)
		+lPitch * (lpRect->bottom - lpRect->top);	//	これが画像ファイルサイズ(のはず)

	auto_array<BYTE> bitmap(size);

	//	ビットマップヘッダーの定義
	BITMAPFILEHEADER *BF = (BITMAPFILEHEADER*)(BYTE*)bitmap;
	BF->bfType			= 0x4D42;
	BF->bfSize			= size;
	BF->bfReserved1		= 0;
	BF->bfReserved2		= 0;
	BF->bfOffBits		= sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
	
	BITMAPINFOHEADER *BI = (BITMAPINFOHEADER*)((BYTE*)bitmap + sizeof(BITMAPFILEHEADER));
	BI->biSize			= sizeof(BITMAPINFOHEADER);
	BI->biWidth			= lpRect->right	 - lpRect->left;	// size to be saved...
	BI->biHeight		= lpRect->bottom - lpRect->top;
	BI->biPlanes		= 1;
	BI->biBitCount		= 24;		//	フルカラー
	BI->biCompression	= 0;		//	非圧縮
	BI->biSizeImage		= 0;		//	非圧縮のときは0
	BI->biXPelsPerMeter	= 3780;	//	96dpi(こんなところ見ているソフトはないだろうけど)
	BI->biYPelsPerMeter	= 3780;
	BI->biClrUsed		= 0;
	BI->biClrImportant	= 0;

	BYTE *image = (BYTE*)bitmap + sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);

	//	イメージ転送なりり!
	int y2 = lpRect->bottom-lpRect->top-1;		//	上下は反転させる必要がある
	for(int y=lpRect->top;y<lpRect->bottom;y++,y2--){
		int x2 = 0;
		for(int x=lpRect->left;x<lpRect->right;x++,x2++){
			COLORREF c = ::GetPixel(m_hDC,x,y);	//	まあ、ちょっとぐらい遅くてもええわな^^
			*(image + x2*3 + y2*lPitch + 0) = GetBValue(c);	//	B
			*(image + x2*3 + y2*lPitch + 1) = GetGValue(c);	//	G
			*(image + x2*3 + y2*lPitch + 2) = GetRValue(c);	//	R
		}
	}

	return CFile().Write(BitmapFileName,bitmap,size);	//	そんだけ:p
}
void CTest::CreateFile(const string& path, size_t offset, size_t size)
{
    CFileIO fio;
    fio.Open(path, CFileIO::eCreate, CFileIO::eReadWrite);
    assert((offset + size) <= m_BufLen);
    size_t n = fio.Write(m_Buf + offset, size);
    assert(n == size);
    fio.Close();
    assert(CFile(path).Exists());
}
 CBDB_BlobDeMuxPersistent(const string& path,
     double    vol_max = 1.5 * (1024.00*1024.00*1024.00),
     unsigned  rec_max = 3 * 1000000)
     : CBDB_BlobDeMux(vol_max, rec_max)
     , m_Path(path)
 {
     if ( !m_Path.empty()  &&  CFile(m_Path).Exists()) {
         CNcbiIfstream istr(m_Path.c_str());
         Load(istr);
     }
 }
Exemple #9
0
void CBam2GraphApp::ProcessFile(const string& file)
{
    const CArgs& args = GetArgs();

    string path;
    if ( NStr::StartsWith(file, "http://") ||
         NStr::StartsWith(file, "https://") ||
         NStr::StartsWith(file, "ftp://") ||
         CFile(file).Exists() ) {
        path = file;
    }
    else {
        string dir;
        if ( args["dir"] ) {
            dir = args["dir"].AsString();
        }
        else {
            vector<string> reps;
            NStr::Split("traces02:traces04", ":", reps);
            ITERATE ( vector<string>, it, reps ) {
                string path = CFile::MakePath(CFile::MakePath(NCBI_GetTestDataPath(), *it), dir);
                if ( !CDirEntry(dir).Exists() ) {
                    dir = path;
                    break;
                }
            }
        }

        path = CFile::MakePath(dir, file);
        if ( !CFile(path).Exists() ) {
            vector<string> tt;
            NStr::Split(CFile(file).GetBase(), ".", tt);
            if ( tt.size() > 0 ) {
                path = CFile::MakePath(dir, tt[0]);
                path = CFile::MakePath(path, "alignment");
                path = CFile::MakePath(path, file);
            }
        }
    }
Exemple #10
0
bool CZipCompression::DecompressFileIntoDir(const string& src_file,
        const string& dst_dir,
        size_t        buf_size)
{
    CZipCompressionFile cf(GetLevel(), m_WindowBits, m_MemLevel, m_Strategy);
    cf.SetFlags(cf.GetFlags() | GetFlags());

    bool need_restore_attr = false;
    SFileInfo info;
    string dir, name, ext;
    string dst_file;

    // Open compressed file, and define name of the destination file
    if ( F_ISSET(fRestoreFileAttr) ) {
        if ( !cf.Open(src_file, CCompressionFile::eMode_Read, &info) ) {
            SetError(cf.GetErrorCode(), cf.GetErrorDescription());
            return false;
        }
        if ( info.name.empty() ) {
            // Header is possible broken, ignore it
            CFile::SplitPath(src_file, &dir, &name, &ext);
            dst_file = CFile::MakePath(dst_dir, name);
        } else {
            need_restore_attr = true;
            dst_file = CFile::MakePath(dst_dir, info.name);
        }
    } else {
        if ( !cf.Open(src_file, CCompressionFile::eMode_Read, 0) ) {
            SetError(cf.GetErrorCode(), cf.GetErrorDescription());
            return false;
        }
        CFile::SplitPath(src_file, &dir, &name, &ext);
        dst_file = CFile::MakePath(dst_dir, name);
    }
    // Decompress file
    if ( !CCompression::x_DecompressFile(cf, dst_file, buf_size) ) {
        if ( cf.GetErrorCode() ) {
            SetError(cf.GetErrorCode(), cf.GetErrorDescription());
        }
        cf.Close();
        return false;
    }
    // Close output file and return result
    bool status = cf.Close();
    SetError(cf.GetErrorCode(), cf.GetErrorDescription());
    // Restore time stamp if needed
    if ( status  &&  need_restore_attr ) {
        CFile(dst_file).SetTimeT(&info.mtime);
    }
    return status;
}
Exemple #11
0
 ITERATE ( vector<string>, it, dirs ) {
     string dir = *it;
     if ( !CDirEntry(dir).Exists() ) {
         continue;
     }
     path = CFile::MakePath(dir, file);
     if ( !CFile(path).Exists() ) {
         SIZE_TYPE p1 = file.rfind('/');
         if ( p1 == NPOS ) {
             p1 = 0;
         }
         else {
             p1 += 1;
         }
         SIZE_TYPE p2 = file.find('.', p1);
         if ( p2 != NPOS ) {
             path = CFile::MakePath(dir, file.substr(p1, p2-p1) + "/alignment/" + file);
         }
     }
     if ( CFile(path).Exists() ) {
         break;
     }
     path.clear();
 }
CSetupWriteFlash::CSetupWriteFlash( )
{
	title = "Select img.";
	this->flag = false;
	/* poll the directory and collect data */
	struct dirent* entry = NULL;
	
	DIR* dir = opendir( "/tmp" );
	
	if( NULL == dir )
		return;
	
	if( NULL == ( entry = readdir( dir ) ) )
	{
		/* perhaps some errors, 
		but currently no checks, just exit, 
		assume empty folder */
		return;
	}
	
	while( entry != NULL )
	{
		struct stat status;
		std::string fullname;
		
		fullname += std::string("/tmp/") + std::string(entry->d_name); 
		
		if( 0 == stat( fullname.c_str(), &status ) )
		{
			if( S_ISREG( status.st_mode ) )
			{
				/* regular file, add it to playlist */
				
				/* check filename extension, has to be mp3  */
				
				if( CFile::FILE_IMAGE == CFile( fullname ).getType() )
				{
					std::cout << "file " << fullname << std::endl;
					entries.push_back( fullname );
				}
			}
		}

		entry = readdir( dir );
	}
		
	closedir( dir );
}
Exemple #13
0
static void s_ReadLinesFromFile(const string& fn, vector<string>& lines)
{
    CNcbiIfstream fs(fn.c_str(), IOS_BASE::in);
    lines.clear();

    if (CFile(fn).Exists() && ! fs.fail()) {
        char line[256];
        while(true) {
            fs.getline(line, 256);
            if (fs.eof()) break;
            if (line[0] == '#') continue;
            string l(line);
            lines.push_back(l);
        }
    }
    fs.close();
};
Exemple #14
0
void CSoundOgg::load(){
	if(isLoaded())
		return;

	CSoundBuffer::load();
	mFile = CFile(getName());
	mFile.loadData();

	mFileData = (char *)mFile.getData();
	mFilePos = 0;

	ov_callbacks cb;
	cb.read_func = read_func;
	cb.seek_func = seek_func;
	cb.close_func = close_func;
	cb.tell_func = tell_func;

	S32 res = ov_open_callbacks(this, &mOggFile, 0, 0, cb);
}
void CPlayPLRandom::Show()
{
//	sleep( 1 );
	static size_t lastplayed = 	0;

	if( lastplayed != playlist->GetCurrent() )
	{
		frame = 0;
		lastplayed = playlist->GetCurrent();
	}

	frame = CLCD::getInstance()->ShowPlayingFile( CFile( playlist->GetCurrentLocation() ).getFileName(),  playlist->GetPositionPercents(), playlist->GetTimePlayed(), frame );

	playlist->DoAction();	

	if( playlist->IsStopped() )
		remove = true;

//	if( CBaseDec::STOP == playlist->GetState() )
//		remove = true;


}
Exemple #16
0
bool CSoundOgg::isOggFile(const std::string &name){
	CSoundOgg ogg;

	ogg.mFile = CFile(name);

	try {
		ogg.mFile.loadData();
	} catch (CException e) {
		return false;
	}

	ogg.mFileData = (char *)ogg.mFile.getData();
	ogg.mFilePos = 0;

	ov_callbacks cb;
	cb.read_func = read_func;
	cb.seek_func = seek_func;
	cb.close_func = close_func;
	cb.tell_func = tell_func;

	S32 res = ov_test_callbacks(&ogg, &ogg.mOggFile, 0, 0, cb);

	return res == 0 ? true : false;
}
void sUpdateCase(CDir& test_cases_dir, const string& test_name)
{   
    string input = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extInput);
    string output = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extOutput);
    string errors = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extErrors);
    if (!CFile(input).Exists()) {
         BOOST_FAIL("input file " << input << " does not exist.");
    }
    string test_base, test_type;
    NStr::SplitInTwo(test_name, ".", test_base, test_type);
    cerr << "Creating new test case from " << input << " ..." << endl;

    CErrorLogger logger(errors);

    //get a scope
    CRef<CObjectManager> pObjMngr = CObjectManager::GetInstance();
    CGBDataLoader::RegisterInObjectManager(*pObjMngr);
    CRef<CScope> pScope(new CScope(*pObjMngr));
    pScope->AddDefaults();

    //get a writer object
    CNcbiIfstream ifstr(input.c_str(), ios::binary);
    CObjectIStream* pI = CObjectIStream::Open(eSerial_AsnText, ifstr, eTakeOwnership);

    CNcbiOfstream ofstr(output.c_str());
    CBedGraphWriter* pWriter = sGetWriter(*pScope, ofstr);

    if (test_type == "annot") {
        CRef<CSeq_annot> pAnnot(new CSeq_annot);
        *pI >> *pAnnot;
        pWriter->WriteHeader();
        pWriter->WriteAnnot(*pAnnot);
        pWriter->WriteFooter();
        delete pWriter;
        ofstr.flush();
    }
void sUpdateCase(CDir& test_cases_dir, const string& test_name)
{   
    string input = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extInput);
    string output = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extOutput);
    string errors = CDir::ConcatPath( test_cases_dir.GetPath(), test_name + "." + extErrors);
    if (!CFile(input).Exists()) {
         BOOST_FAIL("input file " << input << " does not exist.");
    }
    cerr << "Creating new test case from " << input << " ..." << endl;

    CErrorLogger logger(errors);
    CGvfReader reader(0);
    CNcbiIfstream ifstr(input.c_str());

    typedef CGff2Reader::TAnnotList ANNOTS;
    ANNOTS annots;
    try {
        reader.ReadSeqAnnots(annots, ifstr, &logger);
    }
    catch (...) {
        ifstr.close();
        BOOST_FAIL("Error: " << input << " failed during conversion.");
    }
    ifstr.close();
    cerr << "    Produced new error listing " << output << "." << endl;

    CNcbiOfstream ofstr(output.c_str());
    for (ANNOTS::iterator cit = annots.begin(); cit != annots.end(); ++cit){
        ofstr << MSerial_AsnText << **cit;
        ofstr.flush();
    }
    ofstr.close();
    cerr << "    Produced new ASN1 file " << output << "." << endl;

    cerr << " ... Done." << endl;
}
Exemple #19
0
CTaxDBFileInfo::CTaxDBFileInfo()
    : m_AllTaxidCount(0),
      m_IndexPtr(NULL),
      m_DataPtr(NULL),
      m_DataFileSize(0),
      m_MissingDB(false)
{

    // It is reasonable for this database to not exist.
    m_IndexFN =  SeqDB_ResolveDbPath("taxdb.bti");

    if (m_IndexFN.size()) {
        m_DataFN = m_IndexFN;
        m_DataFN[m_DataFN.size()-1] = 'd';
    }
    
    if (! (m_IndexFN.size() &&
           m_DataFN.size()  &&
           CFile(m_IndexFN).Exists() &&
           CFile(m_DataFN).Exists())) {
        m_MissingDB = true;
        return;
    }
    
    // Size for header data plus one taxid object.
    
    Uint4 data_start = (4 +    // magic
                        4 +    // taxid count
                        16);   // 4 reserved fields
    
    Uint4 idx_file_len = (Uint4) CFile(m_IndexFN).GetLength();
    
    if (idx_file_len < (data_start + sizeof(CSeqDBTaxId))) {
        m_MissingDB = true;
        return;
    }
    
    m_IndexFileMap.reset(new CMemoryFile(m_IndexFN));
    
    m_IndexFileMap->Map();

    // Last check-up of the database validity
    
    
    Uint4 * magic_num_ptr = (Uint4 *)m_IndexFileMap->GetPtr();
    
    const unsigned TAX_DB_MAGIC_NUMBER = 0x8739;
    
    if (TAX_DB_MAGIC_NUMBER != SeqDB_GetStdOrd(magic_num_ptr ++)) {
        m_MissingDB = true;
        m_IndexFileMap.reset();
        ERR_POST("Error: Tax database file has wrong magic number.");
        return;
    }
    
    m_AllTaxidCount = SeqDB_GetStdOrd(magic_num_ptr ++);
    
    // Skip the four reserved fields
    magic_num_ptr += 4;
    
    int taxid_array_size = int((idx_file_len - data_start)/sizeof(CSeqDBTaxId));
    
    if (taxid_array_size != m_AllTaxidCount) {
        m_MissingDB = true;
        m_IndexFileMap.reset();
        ERR_POST("SeqDB: Taxid metadata indicates (" << m_AllTaxidCount
                   << ") entries but file has room for (" << taxid_array_size
                   << ").");
        
        if (taxid_array_size < m_AllTaxidCount) {
            m_AllTaxidCount = taxid_array_size;
        }
        return;
    }
    
    m_DataFileMap.reset(new CMemoryFile(m_DataFN));

    m_DataPtr = (char *) (m_DataFileMap->GetPtr());
    m_DataFileSize = m_DataFileMap->GetSize();
    m_IndexPtr = (CSeqDBTaxId*) magic_num_ptr;
    
}
Exemple #20
0
void CVirtualFS::findFiles(const string &path, const string &extension, FindResult &fr){
	S32 i;
#ifdef _WIN32
	struct	_finddata_t fileinfo;
#else
	struct	dirent **entlist, *ent;
#endif

	CollectionList::iterator col;

	for(col = fileCollections.begin() ; col != fileCollections.end() ; col++){
		if(col->col_type == CFileCollection::QuakePAK){		
		} else 
		if(col->col_type == CFileCollection::NativeCollection){
            string fullPath = path;
            {S32 i=0;
				while((i = fullPath.find('\\', i)) != string::npos){
					fullPath.replace(i, 1, "/");
			}}
			Unz_GetStringForDir((unzFile*)col->zh, fullPath, extension, fr);
		} else 
			if(col->col_type == CFileCollection::Directory){
				string fullPath = fixFileName(path);
				i = fullPath.find(col->mMountPoint, 0);
				if(i != 0){
					return;
				}
				fullPath.replace(0, col->mMountPoint.size(), "");
				if(fullPath[0] == '/')
					fullPath.replace(0, 1, "");

				fullPath = col->colPath + fullPath;
#ifdef _WIN32	
				fullPath += "*." + extension;
				{S32 i=0;
				while((i = fullPath.find('/', i)) != string::npos){
					fullPath.replace(i, 1, "\\");
				}}
				S32 hd;
				hd = _findfirst(fullPath.c_str(), &fileinfo);
				if(hd != -1){
					do {
						fr.push_back(CFile(path + fileinfo.name));
					} while (_findnext(hd, &fileinfo) != -1);
					_findclose(hd);
				}
#else
				S32 numfiles = scandir(fullPath.c_str(), &entlist, NULL, NULL);
				for(S32 i = 0 ; i < numfiles ; i++){
					ent = entlist[i];
					// Skip hidden
					if(ent->d_name[0]=='.')continue;

					// Keep requested files
					if(strncmp(extension.c_str(),
						ent->d_name + strlen(ent->d_name) - extension.length(),
						extension.length()))continue;

					fr.push_back(CFile(path + ent->d_name));
				}
#endif		
			}
	}
}
Exemple #21
0
bool CUser::ParseConfig(CConfig* pConfig, CString& sError) {
	TOption<const CString&> StringOptions[] = {
		{ "nick", &CUser::SetNick },
		{ "quitmsg", &CUser::SetQuitMsg },
		{ "altnick", &CUser::SetAltNick },
		{ "ident", &CUser::SetIdent },
		{ "realname", &CUser::SetRealName },
		{ "chanmodes", &CUser::SetDefaultChanModes },
		{ "bindhost", &CUser::SetBindHost },
		{ "vhost", &CUser::SetBindHost },
		{ "dccbindhost", &CUser::SetDCCBindHost },
		{ "dccvhost", &CUser::SetDCCBindHost },
		{ "timestampformat", &CUser::SetTimestampFormat },
		{ "skin", &CUser::SetSkinName },
		{ "language", &CUser::SetLanguage },
	};
	size_t numStringOptions = sizeof(StringOptions) / sizeof(StringOptions[0]);
	TOption<unsigned int> UIntOptions[] = {
		{ "jointries", &CUser::SetJoinTries },
		{ "maxjoins", &CUser::SetMaxJoins },
	};
	size_t numUIntOptions = sizeof(UIntOptions) / sizeof(UIntOptions[0]);
	TOption<bool> BoolOptions[] = {
		{ "keepbuffer", &CUser::SetKeepBuffer },
		{ "multiclients", &CUser::SetMultiClients },
		{ "denyloadmod", &CUser::SetDenyLoadMod },
		{ "admin", &CUser::SetAdmin },
		{ "denysetbindhost", &CUser::SetDenySetBindHost },
		{ "denysetvhost", &CUser::SetDenySetBindHost },
		{ "appendtimestamp", &CUser::SetTimestampAppend },
		{ "prependtimestamp", &CUser::SetTimestampPrepend },
		{ "ircconnectenabled", &CUser::SetIRCConnectEnabled },
	};
	size_t numBoolOptions = sizeof(BoolOptions) / sizeof(BoolOptions[0]);

	for (size_t i = 0; i < numStringOptions; i++) {
		CString sValue;
		if (pConfig->FindStringEntry(StringOptions[i].name, sValue))
			(this->*StringOptions[i].pSetter)(sValue);
	}
	for (size_t i = 0; i < numUIntOptions; i++) {
		CString sValue;
		if (pConfig->FindStringEntry(UIntOptions[i].name, sValue))
			(this->*UIntOptions[i].pSetter)(sValue.ToUInt());
	}
	for (size_t i = 0; i < numBoolOptions; i++) {
		CString sValue;
		if (pConfig->FindStringEntry(BoolOptions[i].name, sValue))
			(this->*BoolOptions[i].pSetter)(sValue.ToBool());
	}

	VCString vsList;
	VCString::const_iterator vit;
	pConfig->FindStringVector("allow", vsList);
	for (vit = vsList.begin(); vit != vsList.end(); ++vit) {
		AddAllowedHost(*vit);
	}
	pConfig->FindStringVector("ctcpreply", vsList);
	for (vit = vsList.begin(); vit != vsList.end(); ++vit) {
		const CString& sValue = *vit;
		AddCTCPReply(sValue.Token(0), sValue.Token(1, true));
	}

	CString sValue;

	CString sDCCLookupValue;
	pConfig->FindStringEntry("dcclookupmethod", sDCCLookupValue);
	if (pConfig->FindStringEntry("bouncedccs", sValue))  {
		if (sValue.ToBool()) {
			CUtils::PrintAction("Loading Module [bouncedcc]");
			CString sModRet;
			bool bModRet = GetModules().LoadModule("bouncedcc", "", CModInfo::UserModule, this, NULL, sModRet);

			CUtils::PrintStatus(bModRet, sModRet);
			if (!bModRet) {
				sError = sModRet;
				return false;
			}

			if (sDCCLookupValue.Equals("Client")) {
				GetModules().FindModule("bouncedcc")->SetNV("UseClientIP", "1");
			}
		}
	}
	if (pConfig->FindStringEntry("buffer", sValue))
		SetBufferCount(sValue.ToUInt(), true);
	if (pConfig->FindStringEntry("awaysuffix", sValue)) {
		CUtils::PrintMessage("WARNING: AwaySuffix has been depricated, instead try -> LoadModule = awaynick %nick%_" + sValue);
	}
	if (pConfig->FindStringEntry("autocycle", sValue)) {
		if (sValue.Equals("true"))
			CUtils::PrintError("WARNING: AutoCycle has been removed, instead try -> LoadModule = autocycle");
	}
	if (pConfig->FindStringEntry("keepnick", sValue)) {
		if (sValue.Equals("true"))
			CUtils::PrintError("WARNING: KeepNick has been deprecated, instead try -> LoadModule = keepnick");
	}
	if (pConfig->FindStringEntry("statusprefix", sValue)) {
		if (!SetStatusPrefix(sValue)) {
			sError = "Invalid StatusPrefix [" + sValue + "] Must be 1-5 chars, no spaces.";
			CUtils::PrintError(sError);
			return false;
		}
	}
	if (pConfig->FindStringEntry("timezoneoffset", sValue)) {
		SetTimezoneOffset(sValue.ToDouble());
	}
	if (pConfig->FindStringEntry("timestamp", sValue)) {
		if (!sValue.Trim_n().Equals("true")) {
			if (sValue.Trim_n().Equals("append")) {
				SetTimestampAppend(true);
				SetTimestampPrepend(false);
			} else if (sValue.Trim_n().Equals("prepend")) {
				SetTimestampAppend(false);
				SetTimestampPrepend(true);
			} else if (sValue.Trim_n().Equals("false")) {
				SetTimestampAppend(false);
				SetTimestampPrepend(false);
			} else {
				SetTimestampFormat(sValue);
			}
		}
	}
	pConfig->FindStringEntry("pass", sValue);
	// There are different formats for this available:
	// Pass = <plain text>
	// Pass = <md5 hash> -
	// Pass = plain#<plain text>
	// Pass = <hash name>#<hash>
	// Pass = <hash name>#<salted hash>#<salt>#
	// 'Salted hash' means hash of 'password' + 'salt'
	// Possible hashes are md5 and sha256
	if (sValue.Right(1) == "-") {
		sValue.RightChomp();
		sValue.Trim();
		SetPass(sValue, CUser::HASH_MD5);
	} else {
		CString sMethod = sValue.Token(0, false, "#");
		CString sPass = sValue.Token(1, true, "#");
		if (sMethod == "md5" || sMethod == "sha256") {
			CUser::eHashType type = CUser::HASH_MD5;
			if (sMethod == "sha256")
				type = CUser::HASH_SHA256;

			CString sSalt = sPass.Token(1, false, "#");
			sPass = sPass.Token(0, false, "#");
			SetPass(sPass, type, sSalt);
		} else if (sMethod == "plain") {
			SetPass(sPass, CUser::HASH_NONE);
		} else {
			SetPass(sValue, CUser::HASH_NONE);
		}
	}
	CConfig::SubConfig subConf;
	CConfig::SubConfig::const_iterator subIt;
	pConfig->FindSubConfig("pass", subConf);
	if (!sValue.empty() && !subConf.empty()) {
		sError = "Password defined more than once";
		CUtils::PrintError(sError);
		return false;
	}
	subIt = subConf.begin();
	if (subIt != subConf.end()) {
		CConfig* pSubConf = subIt->second.m_pSubConfig;
		CString sHash;
		CString sMethod;
		CString sSalt;
		CUser::eHashType method;
		pSubConf->FindStringEntry("hash", sHash);
		pSubConf->FindStringEntry("method", sMethod);
		pSubConf->FindStringEntry("salt", sSalt);
		if (sMethod.empty() || sMethod.Equals("plain"))
			method = CUser::HASH_NONE;
		else if (sMethod.Equals("md5"))
			method = CUser::HASH_MD5;
		else if (sMethod.Equals("sha256"))
			method = CUser::HASH_SHA256;
		else {
			sError = "Invalid hash method";
			CUtils::PrintError(sError);
			return false;
		}

		SetPass(sHash, method, sSalt);
		if (!pSubConf->empty()) {
			sError = "Unhandled lines in config!";
			CUtils::PrintError(sError);

			CZNC::DumpConfig(pSubConf);
			return false;
		}
		subIt++;
	}
	if (subIt != subConf.end()) {
		sError = "Password defined more than once";
		CUtils::PrintError(sError);
		return false;
	}

	pConfig->FindSubConfig("network", subConf);
	for (subIt = subConf.begin(); subIt != subConf.end(); ++subIt) {
		const CString& sNetworkName = subIt->first;

		CIRCNetwork *pNetwork = FindNetwork(sNetworkName);

		if (!pNetwork) {
			pNetwork = new CIRCNetwork(this, sNetworkName);
		}

		if (!pNetwork->ParseConfig(subIt->second.m_pSubConfig, sError)) {
			return false;
		}
	}

	if (pConfig->FindStringVector("server", vsList, false) || pConfig->FindStringVector("chan", vsList, false) || pConfig->FindSubConfig("chan", subConf, false)) {
		CIRCNetwork *pNetwork = FindNetwork("user");
		if (!pNetwork) {
			pNetwork = AddNetwork("user");
		}

		if (pNetwork) {
			CUtils::PrintMessage("NOTICE: Found deprecated config, upgrading to a network");

			if (!pNetwork->ParseConfig(pConfig, sError, true)) {
				return false;
			}
		}
	}

	pConfig->FindStringVector("loadmodule", vsList);
	for (vit = vsList.begin(); vit != vsList.end(); ++vit) {
		sValue = *vit;
		CString sModName = sValue.Token(0);

		// XXX Legacy crap, added in ZNC 0.089
		if (sModName == "discon_kick") {
			CUtils::PrintMessage("NOTICE: [discon_kick] was renamed, loading [disconkick] instead");
			sModName = "disconkick";
		}

		// XXX Legacy crap, added in ZNC 0.099
		if (sModName == "fixfreenode") {
			CUtils::PrintMessage("NOTICE: [fixfreenode] doesn't do anything useful anymore, ignoring it");
			continue;
		}

		CUtils::PrintAction("Loading Module [" + sModName + "]");
		CString sModRet;
		CString sArgs = sValue.Token(1, true);
		bool bModRet;

		CModInfo ModInfo;
		if (!CZNC::Get().GetModules().GetModInfo(ModInfo, sModName, sModRet)) {
			sError = "Unable to find modinfo [" + sModName + "] [" + sModRet + "]";
			return false;
		}

		if (!ModInfo.SupportsType(CModInfo::UserModule) && ModInfo.SupportsType(CModInfo::NetworkModule)) {
			CUtils::PrintMessage("NOTICE: Module [" + sModName + "] is a network module, loading module for all networks in user.");

			// Do they have old NV?
			CFile fNVFile = CFile(GetUserPath() + "/moddata/" + sModName + "/.registry");

			for (vector<CIRCNetwork*>::iterator it = m_vIRCNetworks.begin(); it != m_vIRCNetworks.end(); ++it) {
				if (fNVFile.Exists()) {
					CString sNetworkModPath = (*it)->GetNetworkPath() + "/moddata/" + sModName;
					if (!CFile::Exists(sNetworkModPath)) {
						CDir::MakeDir(sNetworkModPath);
					}

					fNVFile.Copy(sNetworkModPath + "/.registry");
				}

				bModRet = (*it)->GetModules().LoadModule(sModName, sArgs, CModInfo::NetworkModule, this, *it, sModRet);
				if (!bModRet) {
					break;
				}
			}
		} else {
			bModRet = GetModules().LoadModule(sModName, sArgs, CModInfo::UserModule, this, NULL, sModRet);
		}

		CUtils::PrintStatus(bModRet, sModRet);
		if (!bModRet) {
			sError = sModRet;
			return false;
		}
		continue;
	}

	return true;
}
Exemple #22
0
CDBInterfacesFileConnParams::CDBInterfacesFileConnParams(
        const CDBConnParams& other,
        const string& file
        )
: CDBConnParamsDelegate(other)
{
    string file_name;

    if (!file.empty() && CFile(file).Exists()) {
        file_name = file;
    } else {
        const CNcbiEnvironment env;

        // Get it from a default place ...
        file_name = env.Get("SYBASE") + "/interfaces";
        if (!CFile(file_name).Exists()) {
            file_name = env.Get("HOME") + "/.interfaces";
            if (!CFile(file_name).Exists()) {
                return;
            }
        }
    }

    CNcbiIfstream istr(file_name.c_str());

    if (!istr) {
        return;
    }

    string line;
    string key;
    string host_str;
    string port_str;

    vector<string> arr_param;
    enum EState {eInitial, eKeyRead,  eValueRead};
    EState state = eInitial;
    bool tli_format = false;

    while (NcbiGetlineEOL(istr, line)) {
        if (line[0] == '#' || line.empty()) {
            continue;
        } else if (line[0] == '\t') {
            if (state == eKeyRead) {
                NStr::TruncateSpacesInPlace(line);
                arr_param.clear();
                NStr::Tokenize(line, "\t ", arr_param);

                if (NStr::Equal(arr_param[0], "query")) {
                    if (NStr::Equal(arr_param[1], "tli")) {
                        tli_format = true;
                        const string tli_str = arr_param[arr_param.size() - 1];
                        host_str = tli_str.substr(10 - 1, 8);
                        port_str = tli_str.substr(6 - 1, 4);
                    } else {
                        host_str = arr_param[arr_param.size() - 2];
                        port_str = arr_param[arr_param.size() - 1];
                    }

                    state = eValueRead;
                }
            } else {
                // Skip all values except the first one ...
                continue;
            }
        } else {
            if (state == eInitial) {
                key = line;
                NStr::TruncateSpacesInPlace(key);
                state = eKeyRead;
            } else {
                // Error ...
                DATABASE_DRIVER_ERROR("Invalid interfaces file line: " + line, 20001);
            }
        }

        if (state == eValueRead) {
            Uint4 host = 0;
            unsigned char* b = (unsigned char*) &host;

            if (!host_str.empty() && !port_str.empty()) {
                if (tli_format) {
                    b[0] = NStr::StringToUInt(host_str.substr(0, 2), 0, 16);
                    b[1] = NStr::StringToUInt(host_str.substr(2, 2), 0, 16);
                    b[2] = NStr::StringToUInt(host_str.substr(4, 2), 0, 16);
                    b[3] = NStr::StringToUInt(host_str.substr(6, 2), 0, 16);

                    m_Records[key] = SIRecord(host, NStr::StringToUInt(port_str, 0, 16));
                } else {
                    NStr::TruncateSpacesInPlace(host_str);
                    arr_param.clear();
                    NStr::Tokenize(host_str, ".", arr_param);

                    b[0] = NStr::StringToUInt(arr_param[0]);
                    b[1] = NStr::StringToUInt(arr_param[1]);
                    b[2] = NStr::StringToUInt(arr_param[2]);
                    b[3] = NStr::StringToUInt(arr_param[3]);

                    m_Records[key] = SIRecord(host, NStr::StringToUInt(port_str));
                }
            }

            state = eInitial;
        }
    }
}