Пример #1
1
DAQ_LINKAGE int daq_load_modules(const char *directory_list[])
{
    static const char *extension = MODULE_EXT;
#ifndef WIN32
    char dirpath[NAME_SIZE];
    DIR *dirp;
    struct dirent *de;
    char *p;
    int ret;

#ifdef STATIC_MODULE_LIST
    load_static_modules();
#endif

    for (; directory_list && *directory_list; directory_list++)
    {
        if (!(**directory_list))
            continue;
        if ((dirp = opendir(*directory_list)) == NULL)
        {
            fprintf(stderr,"Unable to open directory \"%s\"\n", *directory_list);
            continue;
        }

        DEBUG("Loading modules in: %s\n", *directory_list);

        while((de = readdir(dirp)) != NULL)
        {
            if (de->d_name == NULL)
                continue;
            p = strrchr(de->d_name, '.');
            if (!p || strcmp(p, extension))
                continue;
            snprintf(dirpath, sizeof(dirpath), "%s/%s", *directory_list, de->d_name);

            ret = daq_load_module(dirpath);
            if (ret == DAQ_SUCCESS)
            {
                DEBUG("Found module %s\n", de->d_name);
            }
            else if (ret == DAQ_ERROR_NOMEM)
            {
                closedir(dirp);
                return DAQ_ERROR_NOMEM;
            }
        }
        closedir(dirp);
    }
#else
    /* Find all shared library files in path */
    char path_buf[PATH_MAX];
    char dyn_lib_name[PATH_MAX];
    char drive[_MAX_DRIVE];
    char dir[_MAX_DIR];
    char fname[_MAX_FNAME];
    char ext[_MAX_EXT];
    HANDLE fSearch;
    WIN32_FIND_DATA FindFileData;
    int pathLen = 0;
    const char *directory;
    int useDrive = 0;

#ifdef STATIC_MODULE_LIST
    load_static_modules();
#endif

    for (; directory_list && *directory_list; directory_list++)
    {
        if (!(**directory_list))
            continue;

        if ((strncpy(path_buf, *directory_list, PATH_MAX) == NULL) ||
            (strlen(path_buf) != strlen(*directory_list)))
        {
            fprintf(stderr, "Path is too long: %s\n", *directory_list);
            continue;
        }

        pathLen = strlen(path_buf);
        if ((path_buf[pathLen - 1] == '\\') ||
            (path_buf[pathLen - 1] == '/'))
        {
            /* A directory was specified with trailing dir character */
            _splitpath(path_buf, drive, dir, fname, ext);
            _makepath(path_buf, drive, dir, "*", MODULE_EXT);
            directory = &dir[0];
            useDrive = 1;
        }
        else /* A directory was specified */
        {
            _splitpath(path_buf, drive, dir, fname, ext);
            if (strcmp(extension, ""))
            {
                fprintf(stderr, "Improperly formatted directory name: %s\n", *directory_list);
                continue;
            }

            _makepath(path_buf, "", path_buf, "*", MODULE_EXT);
            directory = *directory_list;
        }

        fSearch = FindFirstFile(path_buf, &FindFileData);
        while (fSearch != NULL && fSearch != (HANDLE)-1)
        {
            if (useDrive)
                _makepath(dyn_lib_name, drive, directory, FindFileData.cFileName, NULL);
            else
                _makepath(dyn_lib_name, NULL, directory, FindFileData.cFileName, NULL);

            daq_load_module(dyn_lib_name);

            if (!FindNextFile(fSearch, &FindFileData))
            {
                break;
            }
        }
        FindClose(fSearch);
    }
#endif
    return DAQ_SUCCESS;
}
Пример #2
1
void    dumpDirectoryContentsIntoRawFile(char *dir, int fd) {
    DIR           *FD = NULL;
    struct dirent *in_file;
    char          *imagePath;

    // loop over image stack - in order //
    if (NULL == (FD = opendir(dir)))
    {
        fprintf(stderr, "Error : Failed to open input directory - %s\n", strerror(errno));
        free(FD);
        return;
    }

    while ((in_file = readdir(FD)))
    {
        printf("Processing %s\n", in_file->d_name);
        if (!strcmp (in_file->d_name, "."))
            continue;
        if (!strcmp (in_file->d_name, ".."))
            continue;
        //APPLE Dir ISSUE
        if (!strcmp (in_file->d_name, ".DS_Store"))
            continue;

        asprintf(&imagePath, "%s/%s", dir, in_file->d_name);
        appendImageBytesToRaw(fd, imagePath);
    }
    closedir(FD);


    // loop over image stack - strange behaviour (revise order) //
    /*
     int n;
     struct dirent **namelist;

     n = scandir(dir, &namelist, 0, alphasort);
     // error scanning directory
     if (n < 0) {
        perror("scandir");
        exit(-1);
     }
     */
    /*
    while(n--) {
        printf("Processing %s\n", namelist[n]->d_name);

        if (!strcmp (namelist[n]->d_name, "."))
            continue;
        if (!strcmp (namelist[n]->d_name, ".."))
            continue;
        //APPLE Dir ISSUE
        if (!strcmp (namelist[n]->d_name, ".DS_Store"))
            continue;

        asprintf(&imagePath, "%s/%s", dir, namelist[n]->d_name);
        appendImageBytesToRaw(fd, imagePath);
        free(namelist[n]);
    }
    free(namelist);
    */
}
Пример #3
1
int main(){
    int i,line;
    char content[MAX_SCHEDULER][MAXLINE];
    int pipe_fd[2];
    FILE* fptr,*tmp_fptr;
    struct dirent *dirp;
    DIR* dp;
    pid_t pid;
    if((dp=opendir(dirname))==NULL)
        err_sys();
    while((dirp=readdir(dp))!=NULL)
        if(strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0)
            continue;
        else
            break;
    if(dirp==NULL)
        _Exit(0);
    if((tmp_fptr=fopen(tmp_filename,"w"))==NULL)
        err_sys();
    if(pipe(pipe_fd)<0)
        err_sys();
    if((pid=fork())<0){
        err_sys();
    }else if(pid>0){ //parent , read from pipe
        close(pipe_fd[1]);
        if((fptr=fdopen(pipe_fd[0],"r"))==NULL)
            err_sys();
        for(line=0;fgets(content[line],MAXLINE,fptr)>0;line++);
        if(fclose(fptr)==-1)
            err_sys();
        if(waitpid(pid,NULL,0)<0)
            err_sys();
    }else{ //child , write to pipe
        close(pipe_fd[0]);
        if(pipe_fd[1] != STDOUT_FILENO){
            if(dup2(pipe_fd[1],STDOUT_FILENO) != STDOUT_FILENO)
                err_sys();
            close(pipe_fd[1]);
        }
        if(execl("/usr/bin/crontab","crontab","-l",NULL)<0)
            err_sys();
    }
    deal_content(content,&line,dp,dirp);
    if(closedir(dp))
        err_sys();
    for(i=0;i<line;i++)
        fprintf(tmp_fptr,"%s",content[i]);
    if(fclose(tmp_fptr)==-1)
        err_sys();
    if((pid=fork())<0){
        err_sys();
    }else if(pid>0){ //parent
        if(waitpid(pid,NULL,0)<0)
            err_sys();
    }else{ //child
        if(execl("/usr/bin/crontab","crontab",tmp_filename,NULL)<0)
            err_sys();
    }
    if(unlink(tmp_filename)==-1)
        err_sys();
    return 0;
}
Пример #4
0
SoundEngine::SoundEngine(char* dirStr) {
	srand(time(NULL));

	DIR *dir;
	char *fileStr;
	char *wav;
	struct dirent *ent;
	if ((dir = opendir(dirStr)) != NULL) {
		while ((ent = readdir(dir)) != NULL) {

			if (strstr(ent->d_name, ".wav")) {
				fileStr = (char*)malloc(strlen(dirStr) + strlen(ent->d_name) + 2);
				strcpy(fileStr, dirStr);
				strcpy(&fileStr[strlen(dirStr)], "\\");
				strcpy(&fileStr[strlen(dirStr) + 1], ent->d_name);

				wav = readWavFile(fileStr);

				if (strstr(ent->d_name, "_down")) {
					if (strstr(ent->d_name, "_space")) {
						downSpaceSounds.push_back(wav);
					}
					else if (strstr(ent->d_name, "_return")) {
						downReturnSounds.push_back(wav);
					}
					else {
						downSounds.push_back(wav);
					}
				}
				else if (strstr(ent->d_name, "_up")) {
					if (strstr(ent->d_name, "_space")) {
						upSpaceSounds.push_back(wav);
					}
					else if (strstr(ent->d_name, "_return")) {
						upReturnSounds.push_back(wav);
					}
					else {
						upSounds.push_back(wav);
					}
				}
				free(fileStr);
			}
		}
		closedir(dir);
	}
	wav = readWavFile("C:\\Windows\\media\\chimes.wav");

	if (downSounds.empty()) {
		downSounds.push_back(wav);
		wav = _strdup(wav);			//makes deletion more straightforward
	}
	if (downSpaceSounds.empty()) {
		downSpaceSounds.push_back(wav);
		wav = _strdup(wav);
	}
	if (downReturnSounds.empty()) {
		downReturnSounds.push_back(wav);
		wav = _strdup(wav);
	}
	if (upSounds.empty()) {
		upSounds.push_back(wav);
		wav = _strdup(wav);
	}
	if (upSpaceSounds.empty()) {
		upSpaceSounds.push_back(wav);
		wav = _strdup(wav);
	}
	if (upReturnSounds.empty()) {
		upReturnSounds.push_back(wav);
		wav = _strdup(wav);
	}
	delete wav;
}
Пример #5
0
/* Copy files from source_dir to fs */
static errcode_t __populate_fs(ext2_filsys fs, ext2_ino_t parent_ino,
			       const char *source_dir, ext2_ino_t root,
			       struct hdlinks_s *hdlinks)
{
	const char	*name;
	DIR		*dh;
	struct dirent	*dent;
	struct stat	st;
	char		ln_target[PATH_MAX];
	unsigned int	save_inode;
	ext2_ino_t	ino;
	errcode_t	retval;
	int		read_cnt;
	int		hdlink;

	if (chdir(source_dir) < 0) {
		com_err(__func__, errno,
			_("while changing working directory to \"%s\""),
			source_dir);
		return errno;
	}

	if (!(dh = opendir("."))) {
		com_err(__func__, errno,
			_("while opening directory \"%s\""), source_dir);
		return errno;
	}

	while ((dent = readdir(dh))) {
		if ((!strcmp(dent->d_name, ".")) ||
		    (!strcmp(dent->d_name, "..")))
			continue;
		lstat(dent->d_name, &st);
		name = dent->d_name;

		/* Check for hardlinks */
		save_inode = 0;
		if (!S_ISDIR(st.st_mode) && !S_ISLNK(st.st_mode) &&
		    st.st_nlink > 1) {
			hdlink = is_hardlink(hdlinks, st.st_dev, st.st_ino);
			if (hdlink >= 0) {
				retval = add_link(fs, parent_ino,
						  hdlinks->hdl[hdlink].dst_ino,
						  name);
				if (retval) {
					com_err(__func__, retval,
						"while linking %s", name);
					return retval;
				}
				continue;
			} else
				save_inode = 1;
		}

		switch(st.st_mode & S_IFMT) {
		case S_IFCHR:
		case S_IFBLK:
		case S_IFIFO:
			retval = do_mknod_internal(fs, parent_ino, name, &st);
			if (retval) {
				com_err(__func__, retval,
					_("while creating special file "
					  "\"%s\""), name);
				return retval;
			}
			break;
		case S_IFSOCK:
			/* FIXME: there is no make socket function atm. */
			com_err(__func__, 0,
				_("ignoring socket file \"%s\""), name);
			continue;
		case S_IFLNK:
			read_cnt = readlink(name, ln_target,
					    sizeof(ln_target));
			if (read_cnt == -1) {
				com_err(__func__, errno,
					_("while trying to readlink \"%s\""),
					name);
				return errno;
			}
			ln_target[read_cnt] = '\0';
			retval = do_symlink_internal(fs, parent_ino, name,
						     ln_target, root);
			if (retval) {
				com_err(__func__, retval,
					_("while writing symlink\"%s\""),
					name);
				return retval;
			}
			break;
		case S_IFREG:
			retval = do_write_internal(fs, parent_ino, name, name,
						   root);
			if (retval) {
				com_err(__func__, retval,
					_("while writing file \"%s\""), name);
				return retval;
			}
			break;
		case S_IFDIR:
			retval = do_mkdir_internal(fs, parent_ino, name, &st,
						   root);
			if (retval) {
				com_err(__func__, retval,
					_("while making dir \"%s\""), name);
				return retval;
			}
			retval = ext2fs_namei(fs, root, parent_ino,
					      name, &ino);
			if (retval) {
				com_err(name, retval, 0);
					return retval;
			}
			/* Populate the dir recursively*/
			retval = __populate_fs(fs, ino, name, root, hdlinks);
			if (retval) {
				com_err(__func__, retval,
					_("while adding dir \"%s\""), name);
				return retval;
			}
			if (chdir("..")) {
				com_err(__func__, errno,
					_("during cd .."));
				return errno;
			}
			break;
		default:
			com_err(__func__, 0,
				_("ignoring entry \"%s\""), name);
		}

		retval =  ext2fs_namei(fs, root, parent_ino, name, &ino);
		if (retval) {
			com_err(name, retval, 0);
			return retval;
		}

		retval = set_inode_extra(fs, parent_ino, ino, &st);
		if (retval) {
			com_err(__func__, retval,
				_("while setting inode for \"%s\""), name);
			return retval;
		}

		/* Save the hardlink ino */
		if (save_inode) {
			/*
			 * Check whether need more memory, and we don't need
			 * free() since the lifespan will be over after the fs
			 * populated.
			 */
			if (hdlinks->count == hdlinks->size) {
				void *p = realloc(hdlinks->hdl,
						(hdlinks->size + HDLINK_CNT) *
						sizeof(struct hdlink_s));
				if (p == NULL) {
					com_err(name, errno,
						_("Not enough memory"));
					return errno;
				}
				hdlinks->hdl = p;
				hdlinks->size += HDLINK_CNT;
			}
			hdlinks->hdl[hdlinks->count].src_dev = st.st_dev;
			hdlinks->hdl[hdlinks->count].src_ino = st.st_ino;
			hdlinks->hdl[hdlinks->count].dst_ino = ino;
			hdlinks->count++;
		}
	}
	closedir(dh);
	return retval;
}
Пример #6
0
bool FindSaveGame(int nGame, char *psz, int cb, int *pc = NULL)
{
	if (pc != NULL)
		*pc = 0;

    // This is the prefix of the file being looked for

	char szCompare[PATH_MAX];
	sprintf(szCompare, "htsave%d_", nGame);
	int cchCompare = strlen(szCompare);

    // This is the special save game that is only used
    // when the game exits and reloads right away

	char szReinitializeSave[20];
	sprintf(szReinitializeSave, "htsave%d_", knGameReinitializeSave);
	int cchReinitializeSave = strlen(szReinitializeSave);

    // Enum files in this directory

	char szFileSpec[PATH_MAX];
	PrependSavesDirectory("", szFileSpec);
    DIR *pdir = opendir(szFileSpec);
    if (pdir == NULL) {
        return false;
    }

    int c = 0;
    dirent *pdent;
    while ((pdent = readdir(pdir)) != NULL) {
        // Only consider save games, because if the desired save game is
        // not found, we need to count "slots".

        if (strncmp("htsave", pdent->d_name, 6) != 0) {
            continue;
        }

        // Save game found?

        if (strncmp(szCompare, pdent->d_name, cchCompare) == 0) {
			if (psz != NULL)
				strncpyz(psz, pdent->d_name, cb);
			closedir(pdir);
			return true;
		}

        // Count save games but don't count the temporary "Reinitialize"
        // saved game

		if (strncmp(szReinitializeSave, pdent->d_name,
                cchReinitializeSave) == 0) {
			continue;
        }

        // Count this save game as a slot

		c++;
    }
    closedir(pdir);

    // Didn't find the saved game, but did count the number of occupied slots

	if (pc != NULL)
		*pc = c;
	return false;
}
Пример #7
0
void MainWindow::on_object_id_textChanged(const QString &arg1)
{
    // show all faces allready taged with the id of the object_id field
    QString id = ui->object_id->text();

    std::vector<QPixmap> listCrops;

    QString dir_name = Manager::exemplar()->selectedDirectory;//"/home/daniel/BaoDataBase/myDataBase";
    // collect all FaceObjects and imagees with the given id
    DIR *dir;
    struct dirent *ent;
    struct stat info;
    const char *c_str2 = dir_name.toLocal8Bit().data();
    if ((dir = opendir (c_str2)) != NULL) {
      /* print all the files and directories within directory */
      while ((ent = readdir (dir)) != NULL) {
          stat(ent->d_name, &info);
          //if(!S_ISDIR (info.st_mode)) {
            //qDebug() << ent->d_name;
            std::vector<FaceObject> list = readObjectFile(dir_name.toStdString() + "/.metaface/" + ent->d_name + ".txt");
            if(list.size() > 0) {
                for(std::vector<FaceObject>::iterator it = list.begin(); it != list.end(); ++it) {
                    FaceObject fo = *it;
                    if(fo.objectID == id.toStdString()) {
                        qDebug() << "found a face in:" << ent->d_name;
                        QPixmap * img = new QPixmap();
                        QString fileName = QString::fromStdString(ent->d_name);
                        img->load(dir_name + "/" + fileName);
                        //QPixmap::copy(int x, int y, int width, int height )
                        QPixmap imgCroped = img->copy(fo.x, fo.y, fo.width, fo.height);
                        qDebug() << "image crop x:" << fo.x << "y:" << fo.y << "width" << fo.width << "height:" << fo.height;
                        listCrops.push_back(imgCroped);
                    }

                }
            }
      }
      closedir (dir);
    }

    // check how many croped faces are stored in the list
    qDebug() << "there are " << listCrops.size() << " store in the vector";



    //QString imgPath = "/home/daniel/facetag/datasettools2/datasettools80.png";
    //QImage *img = new QImage();
    //bool loaded = img->load(imgPath);
    //if (loaded)
    //{
        /*QTableWidgetItem *thumbnail = new QTableWidgetItem;
        thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img));

        //thumbnailsWidget->setColumnCount(3);
        //thumbnailsWidget->setRowCount(3);
        ui->tableIamges->setItem(0, 0, thumbnail);*/

        //w.setCentralWidget(thumbnailsWidget);
    //} else {
        //qDebug()<<"Image "<<imgPath<<" was not opened!";
   // }
        int row = 0;
        int column = 0;
        int cell = 0;
        for(std::vector<QPixmap>::iterator it = listCrops.begin(); it != listCrops.end(); ++it) {
            QPixmap pm = *it;
            pm = pm.scaledToHeight(80,Qt::SmoothTransformation);
            QTableWidgetItem *thumbnail = new QTableWidgetItem;
            thumbnail->setData(Qt::DecorationRole, pm);
            ui->tableIamges->setItem(column, row, thumbnail);
            if(column == 2) {
                row++;
                cell++;
                column = 0;
            } else {
                row++;
                cell++;
            }
        }

        int maxCells = ui->tableIamges->rowCount() * ui->tableIamges->columnCount();
        while(cell < 9) {
            QTableWidgetItem *thumbnail = new QTableWidgetItem;
            ui->tableIamges->setItem(column, row, thumbnail);
            if(column == 2) {
                row++;
                cell++;
                column = 0;
            } else {
                row++;
                cell++;
            }
        }
}
Пример #8
0
void* connection_handler(void* number)
{
	int thread_num = *(int*)number;
	int read_size;
	char client_message[2000];

	getcwd(current_dir[N], 5000);

	printf("[%d] created.\n", thread_num);

	while(!is_working[thread_num]);

	while( (read_size = recv(client_sockets[thread_num] , client_message , 2000 , 0)) > 0 )
	{
		char* command = strtok(client_message, " ");
		printf("[%d] Command: [%s]\n", thread_num, command);
		if (strcmp("LIST", command) == 0)
		{
			char response[10000];

			DIR           *d;
			struct dirent *dir;
			d = opendir(current_dir[thread_num]);
			if (d)
			{
				strcpy(response, "");
				while ((dir = readdir(d)) != NULL)
				{
					
					strcat(response, dir->d_name);
					strcat(response, "\n");
				}

				closedir(d);
			}

			write(client_sockets[thread_num] , response , strlen(response));
		}
		else if (strcmp("CWD", command) == 0)
		{
			char* path = strtok(NULL, " ");
			printf("[%d] Path: [%s]\n", thread_num, path);			
			

			char response[1000];

			struct stat s;
			int err = stat(path, &s);

			if (err != -1 && S_ISDIR(s.st_mode)) // is a dir
			{
				strcpy(current_dir[thread_num], path);
				sprintf(response, "Ok, current_path = %s\n", current_dir[thread_num]);
			}
			else
			{
				sprintf(response, "Wrong path, sorry.\n");
			}

			
			write(client_sockets[thread_num] , response , strlen(response));
		}

		memset(client_message,0,sizeof(client_message));

		
	}

	close(client_sockets[thread_num]);

	printf("[%d] Connection closed.\n", thread_num);

	pthread_create(&tid[thread_num] , NULL , connection_handler , (void*) &thread_num);
	is_working[thread_num] = 0;

	printf("[%d] destroyed.\n", thread_num);
}
Пример #9
0
int main() {
	std::setlocale(LC_ALL, "de_DE.UTF-8"); // important for utf-8 multibyte chars
	const std::string path = "/home/typology/1/";
	const std::string path2 = "/home/typology/1sorted/";
	 struct dirent *entry;
	  DIR *dp;

	  dp = opendir(path.c_str());
	  if (dp == NULL) {
	    std::cout << "Path \"" << path << "\" does not exist or could not be read." << std::endl;
	    return 1;
	  }

	  std::string source;
	  std::string target;
	  float score;
	  std::vector<std::string> vSource;
	  std::vector<std::string> vTarget;
	  std::vector<float> vScore;
	  std::tuple<int,char> foo;
	  std::vector<std::tuple<std::string,std::string,float>>* vt = new std::vector<std::tuple<std::string,std::string,float>>();
	  std::vector<std::string> filenames;

	  while ((entry = readdir(dp))){
		if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
			continue;
		}
		filenames.push_back(entry->d_name);
	  }
	  closedir(dp);
	  std::sort(filenames.begin(), filenames.end());
	  wchar_t lastChar;
	  wchar_t currentChar;
	  std::string lastfName;

	  mbrtowc(&lastChar, &filenames[0][0], MB_CUR_MAX, NULL); // Convert multibyte sequence (utf-8) to wide character
	  lastfName = filenames[0];
	  for(auto iter = filenames.begin(); iter != filenames.end(); ++iter) {
		  mbrtowc(&currentChar, &((*iter)[0]), 4, NULL);
		  		if(currentChar != lastChar) {
		  			std::sort(vt->begin(),vt->end(),&compareTwoRows);
		  			std::ofstream myfile ((path2 + lastfName).c_str() );
		  			if (myfile.is_open())
		  			{
		  				for (auto i : *vt){
		  					myfile << std::get<0>(i) << '\t' << std::get<1>(i) << '\t' << std::get<2>(i) << '\n';
		  				}
		  			  myfile.close();
		  			}
		  			vt->clear();
		  			lastChar = currentChar;
		  			lastfName = *iter;
		  		}
	    std::ifstream file((path + *iter).c_str());
	    std::cout << "reading file : " << path + *iter << std::endl;
	    for(std::string line; getline(file, line);) {
			std::istringstream ss(line);
			ss >> source >> target;
			ss.ignore(2);
			ss >> score;
			vt->push_back(std::make_tuple (source, target, score));
	    }

  		if(iter == filenames.end() - 1) {
  			std::sort(vt->begin(),vt->end(),&compareTwoRows);
  			std::ofstream myfile ((path2 + lastfName).c_str() );
  			if (myfile.is_open())
  			{
  				for (auto i : *vt){
  					myfile << std::get<0>(i) << '\t' << std::get<1>(i) << '\t' << std::get<2>(i) << '\n';
  				}
  			  myfile.close();
  			}
  		}
	  }
	  delete vt;
	  return 0;
}
Пример #10
0
csFILE *CS_fopen(const char *filename, const char *mode)
{
	extern char cs_DirsepC;
	struct stat statbuf;
	csFILE *result = NULL;
	char *fixed_filename = (char*) filename;

	/* If we are attempting to read from the file, and the file passed
	 * in does not exist, look for a different file in the same directory
	 * that has the same filename with a different case.
	 */

	if ( (*mode == *_STRM_TXTRD) && stat(filename,&statbuf) )
	{
		/* Make a copy of the filename passed in, and separate it into
		 * directory and path components.
		 */

		char *last_path_sep;

		fixed_filename = (char*) malloc(strlen(filename)+1);
		strcpy(fixed_filename,filename);
		last_path_sep = strrchr(fixed_filename,cs_DirsepC);
		if ( last_path_sep )
		{
			/* Unless the directory is the current directory, we'd
			 * better make sure that at least the directory exists!
			 */
			char *filename_part = last_path_sep + 1;
			*last_path_sep = '\0';
			if ( ! stat(fixed_filename,&statbuf) )
			{
				/* Search the contents of the directory for a file which
				 * matches the one passed in, allowing for different
				 * case.
				 */
#if 1
				DIR *directory = opendir(fixed_filename);
				if ( directory )
				{
					struct dirent *entry;
					while ( (entry = readdir(directory)) != 0 )
					{
						if ( ! CS_stricmp(entry->d_name,filename_part) )
						{
							 /* We have a match!  It should be safe to assume that
							  * their lengths are the same, so we'll just copy it
							  * in-place.
							  */
							strcpy(filename_part,entry->d_name);
							break;
						}
					}
					closedir(directory);
				}
#else
				struct dirent *name_list = NULL;
				int num_matches = scandir( fixed_filename, name_list, NULL, NULL);
				if (num_matches > 0)
				{
					int ii;
					for (ii=0;ii < num_matches;ii++ )
					{
						if (!CS_stricmp (name_list[ii].d_name,filename_part))
						{
							 /* We have a match!  It should be safe to assume that
							  * their lengths are the same, so we'll just copy it
							  * in-place.
							  */
							strcpy (filename_part,name_list[ii].d_name);
							break;
						}
					}
					free (name_list);
				}
#endif
				/* Replace the directory/path separator */
				*last_path_sep = cs_DirsepC;
			}
		}
	}
	result = (csFILE*) fopen(fixed_filename,mode);
	if ( filename != fixed_filename )
	{
		free(fixed_filename);
	}
	return result;
}
/* lnstat_scan_dir - find and parse all available statistics files/fields */
struct lnstat_file *lnstat_scan_dir(const char *path, const int num_req_files,
				    const char **req_files)
{
	DIR *dir;
	struct lnstat_file *lnstat_files = NULL;
	struct dirent *de;

	if (!path)
		path = PROC_NET_STAT;

	dir = opendir(path);
	if (!dir) {
		struct lnstat_file *lf;
		/* Old kernel, before /proc/net/stat was introduced */
		fprintf(stderr, "Your kernel doesn't have lnstat support. ");

		/* we only support rtstat, not multiple files */
		if (num_req_files >= 2) {
			fputc('\n', stderr);
			return NULL;
		}

		/* we really only accept rt_cache */
		if (num_req_files && !name_in_array(num_req_files,
						    req_files, "rt_cache")) {
			fputc('\n', stderr);
			return NULL;
		}

		fprintf(stderr, "Fallback to old rtstat-only operation\n");

		lf = alloc_and_open("/proc/net", "rt_cache_stat");
		if (!lf)
			return NULL;
		lf->compat = 1;
		strncpy(lf->basename, "rt_cache", sizeof(lf->basename));

		/* FIXME: support for old files */
		if (lnstat_scan_compat_rtstat_fields(lf) < 0)
			return NULL;

		lf->next = lnstat_files;
		lnstat_files = lf;
		return lnstat_files;
	}

	while ((de = readdir(dir))) {
		struct lnstat_file *lf;

		if (de->d_type != DT_REG)
			continue;

		if (num_req_files && !name_in_array(num_req_files,
						    req_files, de->d_name))
			continue;

		lf = alloc_and_open(path, de->d_name);
		if (!lf)
			return NULL;

		/* fill in field structure */
		if (lnstat_scan_fields(lf) < 0)
			return NULL;

		/* prepend to global list */
		lf->next = lnstat_files;
		lnstat_files = lf;
	}
	closedir(dir);

	return lnstat_files;
}
Пример #12
0
static void
closedirectory(directory_type *dir)
{
closedir(dir);
}
static void *mpc8544_load_device_tree(target_phys_addr_t addr,
                                     uint32_t ramsize,
                                     target_phys_addr_t initrd_base,
                                     target_phys_addr_t initrd_size,
                                     const char *kernel_cmdline)
{
    void *fdt = NULL;
#ifdef CONFIG_FDT
    uint32_t mem_reg_property[] = {0, ramsize};
    char *filename;
    int fdt_size;
    int ret;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);
    if (!filename) {
        goto out;
    }
    fdt = load_device_tree(filename, &fdt_size);
    qemu_free(filename);
    if (fdt == NULL) {
        goto out;
    }

    /* Manipulate device tree in memory. */
    ret = qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,
                               sizeof(mem_reg_property));
    if (ret < 0)
        fprintf(stderr, "couldn't set /memory/reg\n");

    ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start",
                                    initrd_base);
    if (ret < 0)
        fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");

    ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-end",
                                    (initrd_base + initrd_size));
    if (ret < 0)
        fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");

    ret = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",
                                      kernel_cmdline);
    if (ret < 0)
        fprintf(stderr, "couldn't set /chosen/bootargs\n");

    if (kvm_enabled()) {
        struct dirent *dirp;
        DIR *dp;
        char buf[128];

        if ((dp = opendir("/proc/device-tree/cpus/")) == NULL) {
            printf("Can't open directory /proc/device-tree/cpus/\n");
            goto out;
        }

        buf[0] = '\0';
        while ((dirp = readdir(dp)) != NULL) {
            if (strncmp(dirp->d_name, "PowerPC", 7) == 0) {
                snprintf(buf, 128, "/cpus/%s", dirp->d_name);
                break;
            }
        }
        closedir(dp);
        if (buf[0] == '\0') {
            printf("Unknow host!\n");
            goto out;
        }

        mpc8544_copy_soc_cell(fdt, buf, "clock-frequency");
        mpc8544_copy_soc_cell(fdt, buf, "timebase-frequency");
    }

    cpu_physical_memory_write (addr, (void *)fdt, fdt_size);

out:
#endif

    return fdt;
}
Пример #14
0
int main(int argc, const char *argv[])
{
    struct dirent *dp;
    DIR *dfd;
    char filename[20][50] = {0};
    char name[50] = {0};
    int i;
    int fd, rd;
    struct input_event ev[64];

    signal(SIGINT,event_exit);

    dfd = opendir("/dev/input");
    if(!dfd)
    {
        perror("opendir");
        return 1;
    }

    while(dp = readdir(dfd))
    {
        if(strncmp(dp->d_name,"event",5));
        else
            sprintf(filename[filenum++],"/dev/input/%s",dp->d_name);
    }
    closedir(dfd);

    printf("your input devices :\n");
    for (i = 0; i < filenum; i++) 
    {
        if((fds[i] = open(filename[i], O_RDONLY)) < 0)
        {
            perror("open");
            return 1;
        }

        if(ioctl(fds[i],EVIOCGNAME(sizeof(name)),name));
        printf("%d :%s\n",i,name);
    }

    int num = 0;
    printf("which is your choice:");
    scanf("%d",&num);

    fd = fds[num];

    while (1) 
    {
        rd = read(fd, ev, sizeof(struct input_event) * 4);
        if (rd < (int) sizeof(struct input_event)) 
        {
            perror("read");
            return 1;
        }

        for (i = 0; i < rd / sizeof(struct input_event); i++)
        {
            switch(ev[i].type)
            {
                case EV_KEY:
                    printf("Event: time %ld.%ld, type %s, code %d (%s), value %d\n",
                            ev[i].time.tv_sec, ev[i].time.tv_usec, 
                            "Key",
                            ev[i].code,
                            keys[ev[i].code],
                            ev[i].value);
                    break;

                case EV_ABS:
                    printf("Event: time %ld.%06ld, type %d (%s), code %d (%s), value %d\n",
                            ev[i].time.tv_sec, ev[i].time.tv_usec, ev[i].type,
                            "Absolute",
                            ev[i].code,
                            absolutes[ev[i].code],
                            ev[i].value);
                    break;

                case EV_REL:
                    printf("Event: time %ld.%06ld, type %d (%s), code %d (%s), value %d\n",
                            ev[i].time.tv_sec, ev[i].time.tv_usec, ev[i].type,
                            "Relative",
                            ev[i].code,
                            relatives[ev[i].code],
                            ev[i].value);
                    break;

                default:
                    break;
            }//end switch
        }//end for
    }//end while

    return 0;
}
Пример #15
0
/**
    Searches the supplied root directory for the extension provided. Can recursively search downward through the directory tree
    to get all files. It will then return a vector of file paths that fulfill the search requirements.
    USAGE:
    extension should be preceeded by the '.' character to denote it as an extension, if it is not then it will return all files
    and folder names that contain the extension string.
    root_path can point to any folder relative to the execution directory.
        Searching from the execution directory -- Supply "." as the root_path
        Searching from the parent directory of the execution directory -- Supply ".." as the root_path
        Searching child directories within the execution directory -- Supply "<directory path>" or "./<directory path>", both
            will provide correct results.
    recursive_search will:
        if true, continue searching all child directories from the supplied root_path
        if false, search only the supplied root_path, and stop when the directory contents have been worked through.
*/
std::vector<std::string> file_finder::get_files_from_path(std::string extension, std::string root_path, bool recursive_search)
{
    std::vector<std::string> files;

    // test for empty root path
    if (root_path.empty())
    {
        root_path = ".";
    }

    std::stack<std::string> directories, tempstack;
    directories.push(root_path);
    std::string path = "";

    while (!directories.empty())
    {
        path = directories.top();
        directories.pop();

        DIR *root = opendir(path.c_str());

        if (root)
        {
            struct dirent *root_file;
            struct stat _buff;
            DIR *subdir;

            while ((root_file = readdir(root)))
            {
                // check to see if it is a folder!
                if (stat(root_file->d_name, &_buff) != 0x4)
                {
                    // ignore '.' and '..' folder names, which are current and parent folder relative paths
                    if ((strcmp(root_file->d_name, ".") != 0) && (strcmp(root_file->d_name, "..") != 0))
                    {
                        std::string subpath = path + "/" + root_file->d_name;

                        if (recursive_search)
                        {
                            subdir = opendir(subpath.c_str());
                            if (subdir)
                            {
                                tempstack.push(subpath);
                                closedir(subdir);
                            }
                        }
                    }
                }
                // check to see if it is a file with the appropriate extension
                std::string tmp = root_file->d_name;
                if (tmp.find(extension.c_str()) != std::string::npos)
                {
                    // file with extension found! add to files list with full path
                    std::string fullpath = path + "/" + tmp;
                    files.push_back(fullpath);
                }
            }
        }
        closedir(root);
        // Directories are added to tempstack in A->Z order, which makes them pop from Z->A. This Makes sure that directories are
        // searched in the proper order and that the final output is in the proper order.
        while (!tempstack.empty()){
            directories.push(tempstack.top());
            tempstack.pop();
        }
    }
    return files;
}
Пример #16
0
/*
 *	Parse an "include filename" statement
 *
 *	FIXME: Tie this file into the CONF_SECTION for HUP handling!
 */
static int parse_include(policy_lex_file_t *lexer)
{
	char *p;
	policy_lex_t token;
	char filename[1024];
	char buffer[2048];

	token = policy_lex_file(lexer, 0, filename, sizeof(filename));
	if (token != POLICY_LEX_DOUBLE_QUOTED_STRING) {
		fprintf(stderr, "%s[%d]: Expected filename, got \"%s\"\n",
			lexer->filename, lexer->lineno,
			fr_int2str(rlm_policy_tokens, token, "?"));
		return 0;
	}

	/*
	 *	See if we're including all of the files in a subdirectory.
	 */
	strlcpy(buffer, lexer->filename, sizeof(buffer));
	p = strrchr(buffer, '/');
	if (p) {
		strlcpy(p + 1, filename, sizeof(buffer) - 1 - (p - buffer));

#ifdef HAVE_DIRENT_H
		p = strrchr(p + 1, '/');
		if (p && !p[1]) {
			DIR		*dir;
			struct dirent	*dp;

			p++;

			dir = opendir(buffer);
			if (!dir) {
				fprintf(stderr, "%s[%d]: Error opening %s:%s\n",
					lexer->filename, lexer->lineno,
					buffer, strerror(errno));
				return 0;
			}

			/*
			 *	Read the directory, ignoring "." files.
			 */
			while ((dp = readdir(dir)) != NULL) {
				struct stat buf;

				if (cf_exclude_file(dp->d_name)) continue;

				strlcpy(p, dp->d_name,
					sizeof(buffer) - (p - buffer));

				if ((stat(buffer, &buf) != 0) ||
				    S_ISDIR(buf.st_mode)) continue;

				debug_tokens("\nincluding file %s\n", buffer);
				if (!rlm_policy_parse(lexer->policies, buffer)) {
					closedir(dir);
					return 0;
				}
			}
			closedir(dir);
			return 1;
		} /* else it must have been a normalx file */
#endif
	} else {
		snprintf(buffer, sizeof(buffer), "%s/%s",
			 radius_dir, filename);
	}

	/*
	 *	Handle one include file.
	 */
	debug_tokens("\nincluding file %s\n", buffer);
	if (!rlm_policy_parse(lexer->policies, buffer)) {
		return 0;
	}

	return 1;
}
Пример #17
0
static int scan_loop(void)
{
	unsigned char req_data[MAX_PACKET_LEN];
	int len;
	DIR *wimax_dir;
	FILE *wimax_file;

	while (1)
	{
		if((wimax_dir = opendir("/tmp/wimax")) == NULL)
			mkdir("/tmp/wimax", 0777);
		else
			closedir(wimax_dir);

		if (wd_status.link_status == 0) {
			len = fill_find_network_req(req_data, 1);
			set_data(req_data, len);

			process_events_by_mask(5000, WDS_LINK_STATUS);

			if((wimax_file = fopen("/tmp/wimax/link_status", "w+")) != NULL){
				fprintf(wimax_file, "%d", wd_status.link_status);
				fclose(wimax_file);
			}

			wmlog_msg(2, "Network not found.");
		} else {
			len = fill_connection_params_req(req_data);
			set_data(req_data, len);

			process_events_by_mask(500, WDS_RSSI | WDS_CINR | WDS_TXPWR | WDS_FREQ | WDS_BSID);

			wmlog_msg(0, "RSSI: %d   CINR: %f   TX Power: %d   Frequency: %d", wd_status.rssi, wd_status.cinr, wd_status.txpwr, wd_status.freq);
			wmlog_msg(0, "BSID: %02x:%02x:%02x:%02x:%02x:%02x", wd_status.bsid[0], wd_status.bsid[1], wd_status.bsid[2], wd_status.bsid[3], wd_status.bsid[4], wd_status.bsid[5]);

			if((wimax_file = fopen("/tmp/wimax/link_status", "w+")) != NULL){
				fprintf(wimax_file, "%d", wd_status.link_status);
				fclose(wimax_file);
			}

			if((wimax_file = fopen("/tmp/wimax/mac", "w+")) != NULL){
				fprintf(wimax_file, "%02x:%02x:%02x:%02x:%02x:%02x", wd_status.mac[0], wd_status.mac[1], wd_status.mac[2], wd_status.mac[3], wd_status.mac[4], wd_status.mac[5]);
				fclose(wimax_file);
			}

			if((wimax_file = fopen("/tmp/wimax/rssi", "w+")) != NULL){
				fprintf(wimax_file, "%hd", wd_status.rssi);
				fclose(wimax_file);
			}

			if((wimax_file = fopen("/tmp/wimax/cinr", "w+")) != NULL){
				fprintf(wimax_file, "%f", wd_status.cinr);
				fclose(wimax_file);
			}

			if((wimax_file = fopen("/tmp/wimax/bsid", "w+")) != NULL){
				fprintf(wimax_file, "%02x:%02x:%02x:%02x:%02x:%02x", wd_status.bsid[0], wd_status.bsid[1], wd_status.bsid[2], wd_status.bsid[3], wd_status.bsid[4], wd_status.bsid[5]);
				fclose(wimax_file);
			}

			if((wimax_file = fopen("/tmp/wimax/txpwr", "w+")) != NULL){
				fprintf(wimax_file, "%hu", wd_status.txpwr);
				fclose(wimax_file);
			}

			if((wimax_file = fopen("/tmp/wimax/freq", "w+")) != NULL){
				fprintf(wimax_file, "%u", wd_status.freq);
				fclose(wimax_file);
			}

			if((wimax_file = fopen("/tmp/wimax/state", "w+")) != NULL){
				fprintf(wimax_file, "%d", wd_status.state);
				fclose(wimax_file);
			}

			len = fill_state_req(req_data);
			set_data(req_data, len);

			process_events_by_mask(500, WDS_STATE);

			wmlog_msg(2, "State: %s   Number: %d   Response: %d", wimax_states[wd_status.state], wd_status.state, wd_status.link_status);

			if (first_nego_flag) {
				first_nego_flag = 0;
				len = fill_find_network_req(req_data, 2);
				set_data(req_data, len);
			}

			process_events_by_mask(5000, WDS_LINK_STATUS);
		}
		
		sleep(SCAN_INTERVAL);
	}

	return 0;
}
Пример #18
0
cInstallPrimLang::cInstallPrimLang() :cInstallSubMenu(tr("Handling"))
{
    for (int k = 0; k < 256; k++)
        city_values[k] = NULL;

    // Language
    osdLanguageIndex = I18nCurrentLanguage();

    askTimeZone = true;
#ifdef RBMINI
    cPlugin *p = cPluginManager::GetPlugin("avahi");
    if (p)
    {
        std::vector < ReelBox_t > ReelBoxes;
        p->Service("Avahi ReelBox-List", &ReelBoxes);

        if (ReelBoxes.size() > 0)
        {
            // save changes in sysconfig variable in vdr into sysconfig file
            cSysConfig_vdr::GetInstance().Save();

            std::string cmd;
            // get the timezone from an AVG
            if (strlen(Setup.NetServerIP))
            {                   // there was already one configured, let's take this one...
                // TB: but only if it's available
                bool serverAvailable = false;
                for (unsigned int i = 0; i < ReelBoxes.size(); i++)
                    if (strcmp(Setup.NetServerIP, ReelBoxes.at(i).Ip.c_str()) == 0)
                        serverAvailable = true;
                if (serverAvailable)
                    cmd = std::string("getConfigsFromAVGServer.sh ") + Setup.NetServerIP + std::string(" sysconfig ; ");
                else
                    cmd = std::string("getConfigsFromAVGServer.sh ") + ReelBoxes.at(0).Ip + std::string(" sysconfig ; ");
            }
            else
                cmd = std::string("getConfigsFromAVGServer.sh ") + ReelBoxes.at(0).Ip + std::string(" sysconfig ; ");
            SystemExec(cmd.c_str());    // changes /etc/default/sysconfig

            cSysConfig_vdr::GetInstance().Load(SYSCONFIGFNAME); // load the changes in file into vdr
            dsyslog("(%s:%d) ... done loading sysconfig.", __FILE__, __LINE__);
        }

        // one or more reelbox avantgarde donot ask for TimeZone
        // it is got from the first avantgarde in the list
        askTimeZone = (ReelBoxes.size() == 0);
    }
#endif
    if (askTimeZone)
    {
        // Timezone
        currentCity = 0;
        nr_city_values = 1;
        DIR *zoneDir = NULL;
        struct dirent *entry = NULL;
        struct stat buf;
        std::string path = "/usr/share/zoneinfo";
        for (int k = 0; k < 256; k++)
        {
            city_values[k] = (char *)malloc(32);
            city_values[k][0] = '\0';
        }

        if ((zoneDir = opendir(path.c_str())) != NULL)
        {
            while ((entry = readdir(zoneDir)) != NULL)
            {
                if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
                {
                    std::string tmp = path + "/" + entry->d_name;
                    stat(tmp.c_str(), &buf);
                }
            }
            closedir(zoneDir);
        }
        else
            d(printf("Can not read directory \"%s\" because of error \"%s\"\n", path.c_str(), strerror(errno)))

        cSysConfig_vdr & sysconfig = cSysConfig_vdr::GetInstance();
        char *zoneInfo = strdup((char *)sysconfig.GetVariable("ZONEINFO"));

        char *buf2;
        char *continent = NULL;
        char *city = NULL;

        continent = strdup(strtok_r(zoneInfo, "/", &buf2)); /* go to first '/' */
        city = strdup(strtok_r(NULL, "/", &buf2));  /* get the rest */

        free(zoneInfo);

        if (city != NULL)
        {
            nr_city_values = 0;
            DIR *conDir = NULL;
            struct dirent *entry = NULL;
            struct stat buf;
            std::string path = "/usr/share/zoneinfo/Europe";

            if ((conDir = opendir(path.c_str())) != NULL)
            {
                while ((entry = readdir(conDir)) != NULL)
                {
                    std::string tmp = path + "/" + entry->d_name;
                    stat(tmp.c_str(), &buf);
                    if (S_ISREG(buf.st_mode))
                    {
                        city_values[nr_city_values] = strcpy(city_values[nr_city_values], entry->d_name);
                        nr_city_values++;
                    }
                }
                closedir(conDir);
            }
            else
                d(printf("Can not read directory \"%s\" because of error \"%s\"\n", path.c_str(), strerror(errno)))

            for (int i = 0; i < nr_city_values; i++)
                if (!strcmp(city_values[i], city))
                    currentCity = i;
        }
        free(city);
        free(continent);
    }                           // ask timezone
Пример #19
0
int qgrep_main(int argc, char **argv)
{
	int i;
	char *p;
	bool do_eclass;
	bool do_installed;
	DIR *eclass_dir = NULL;
	struct dirent *dentry = NULL;
	int reflags = 0;
	unsigned long int context_optarg;
	char status = 1;
	size_t n;
	char *overlay;

	struct qgrep_grepargs args = {
		.do_count = 0,
		.do_regex = 0,
		.do_list = 0,
		.show_filename = 0,
		.show_name = 0,
		.skip_comments = 0,
		.invert_list = 0,
		.invert_match = 0,
		.skip_pattern = NULL,
		.num_lines_before = 0,
		.num_lines_after = 0,
		.buf_list = NULL,
		.query = NULL,
		.strfunc = strstr,
		.include_atoms = NULL,
		.portdir = NULL,
	};

	do_eclass = do_installed = 0;

	while ((i = GETOPT_LONG(QGREP, qgrep, "")) != -1) {
		switch (i) {
		case 'I': args.invert_match = true;               break;
		case 'i':
			args.strfunc = strcasestr;
			reflags |= REG_ICASE;
			break;
		case 'c': args.do_count = true;                   break;
		case 'l': args.do_list = true;                    break;
		case 'L': args.do_list = args.invert_list = true; break;
		case 'e': args.do_regex = true;                   break;
		case 'x':
			args.do_regex = true;
			reflags |= REG_EXTENDED;
			break;
		case 'J': do_installed = true;                    break;
		case 'E': do_eclass = true;                       break;
		case 'H': args.show_filename = true;              break;
		case 'N': args.show_name = true;                  break;
		case 's': args.skip_comments = true;              break;
		case 'R': args.show_repo = args.show_name = true; break;
		case 'S': args.skip_pattern = optarg;             break;
		case 'B':
		case 'A':
			errno = 0;
			context_optarg = strtol(optarg, &p, 10);
			if (errno != 0)
				errp("%s: not a valid integer", optarg);
			else if (p == optarg || *p != '\0')
				err("%s: not a valid integer", optarg);
			if (context_optarg > 254)
				err("%s: silly value!", optarg);
			if (i == 'B')
				args.num_lines_before = context_optarg;
			else
				args.num_lines_after = context_optarg;
			break;
		COMMON_GETOPTS_CASES(qgrep)
		}
	}
	if (argc == optind)
		qgrep_usage(EXIT_FAILURE);

	if (args.do_list && args.do_count) {
		warn("%s and --count are incompatible options. The former wins.",
				(args.invert_list ? "--invert-list" : "--list"));
		args.do_count = false;
	}

	if (args.show_name && args.show_filename) {
		warn("--with-name and --with-filename are incompatible options. "
				"The former wins.");
		args.show_filename = false;
	}

	if (args.do_list && args.num_lines_before) {
		warn("%s and --before are incompatible options. The former wins.",
				(args.invert_list ? "--invert-list" : "--list"));
		args.num_lines_before = 0;
	}

	if (args.do_list && args.num_lines_after) {
		warn("%s and --after are incompatible options. The former wins.",
				(args.invert_list ? "--invert-list" : "--list"));
		args.num_lines_after = 0;
	}

	if (args.do_count && args.num_lines_before) {
		warn("--count and --before are incompatible options. The former wins.");
		args.num_lines_before = 0;
	}

	if (args.do_count && args.num_lines_after) {
		warn("--count and --after are incompatible options. The former wins.");
		args.num_lines_after = 0;
	}

	if (do_installed && do_eclass) {
		warn("--installed and --eclass are incompatible options. "
				"The former wins.");
		do_eclass = false;
	}

	if (argc > (optind + 1)) {
		depend_atom **d = args.include_atoms =
			xcalloc(sizeof(depend_atom *), (argc - optind - 1) + 1);
		for (i = (optind + 1); i < argc; i++) {
			*d = atom_explode(argv[i]);
			if (*d == NULL) {
				warn("%s: invalid atom, will be ignored", argv[i]);
			} else {
				d++;
			}
		}
		*d = NULL;
	}

	/* make it easier to see what needs to be printed */
	if (!args.show_name && (verbose || args.do_list))
		args.show_filename = true;

	/* pre-compile regexps once for all */
	if (args.do_regex) {
		if (args.invert_match || *RED == '\0')
			reflags |= REG_NOSUB;
		xregcomp(&args.preg, argv[optind], reflags);
		reflags |= REG_NOSUB;
		if (args.skip_pattern)
			xregcomp(&args.skip_preg, args.skip_pattern, reflags);
	}
	args.query = argv[optind];

	/* allocate a circular buffers list for --before */
	args.buf_list = qgrep_buf_list_alloc(args.num_lines_before + 1);

	array_for_each(overlays, n, overlay) {
		args.portdir = overlay;
		if (do_eclass) {
			char buf[_Q_PATH_MAX];
			char name[_Q_PATH_MAX];
			char *label;
			int efd;

			snprintf(buf, sizeof(buf), "%s/%s/eclass", portroot, overlay);
			efd = open(buf, O_RDONLY|O_CLOEXEC);
			if (efd == -1 || (eclass_dir = fdopendir(efd)) == NULL) {
				if (errno != ENOENT)
					warnp("opendir(\"%s/eclass\") failed", overlay);
				continue;
			}
			while ((dentry = readdir(eclass_dir)) != NULL) {
				if (strstr(dentry->d_name, ".eclass") == NULL)
					continue;
				/* filter the files we grep when there are extra args */
				if (args.include_atoms != NULL) {
					depend_atom **d;
					for (d = args.include_atoms; *d != NULL; d++) {
						if ((*d)->PN != NULL && strncmp(dentry->d_name,
									(*d)->PN, strlen((*d)->PN)) == 0)
							break;
					}
					if (*d == NULL)
						continue;
				}

				label = NULL;
				if (args.show_name) {
					snprintf(name, sizeof(name), "%s%.*s%s", BLUE,
							(int)(strlen(dentry->d_name) - 7), dentry->d_name,
							NORM);
					label = name;
				} else if (args.show_filename) {
					snprintf(name, sizeof(name), "eclass/%s", dentry->d_name);
					label = name;
				}
				status = qgrep_grepat(efd, dentry->d_name, label, &args);
			}
			closedir(eclass_dir);
		} else if (do_installed) {
			status = q_vdb_foreach_pkg(portroot, portvdb,
					qgrep_vdb_cb, &args, NULL);
		} else { /* do_ebuild */
			status = cache_foreach_pkg(portroot, overlay,
					qgrep_cache_cb, &args, NULL);
		}
	}

	if (args.do_regex)
		regfree(&args.preg);
	if (args.do_regex && args.skip_pattern)
		regfree(&args.skip_preg);
	if (args.include_atoms != NULL) {
		for (i = 0; i < (argc - optind - 1); i++)
			if (args.include_atoms[i] != NULL)
				atom_implode(args.include_atoms[i]);
		free(args.include_atoms);
	}
	qgrep_buf_list_free(args.buf_list);

	return status;
}
Пример #20
0
PHPAPI int php_scandir(const char *dirname, struct dirent **namelist[], int (*selector) (const struct dirent *entry), int (*compare) (const struct dirent **a, const struct dirent **b))
{
	DIR *dirp = NULL;
	struct dirent **vector = NULL;
	int vector_size = 0;
	int nfiles = 0;
	char entry[sizeof(struct dirent)+MAXPATHLEN];
	struct dirent *dp = (struct dirent *)&entry;

	if (namelist == NULL) {
		return -1;
	}

	if (!(dirp = opendir(dirname))) {
		return -1;
	}

	while (!php_readdir_r(dirp, (struct dirent *)entry, &dp) && dp) {
		int dsize = 0;
		struct dirent *newdp = NULL;

		if (selector && (*selector)(dp) == 0) {
			continue;
		}

		if (nfiles == vector_size) {
			struct dirent **newv;
			if (vector_size == 0) {
				vector_size = 10;
			} else { 
				vector_size *= 2;
			}

			newv = (struct dirent **) realloc (vector, vector_size * sizeof (struct dirent *));
			if (!newv) {
				return -1;
			}
			vector = newv;
		}

		dsize = sizeof (struct dirent) + ((strlen(dp->d_name) + 1) * sizeof(char));
		newdp = (struct dirent *) malloc(dsize);

		if (newdp == NULL) {
			goto fail;
		}

		vector[nfiles++] = (struct dirent *) memcpy(newdp, dp, dsize);
	}

	closedir(dirp);

	*namelist = vector;

	if (compare) {
		qsort (*namelist, nfiles, sizeof(struct dirent *), compare);
	}

	return nfiles;

fail:
	while (nfiles-- > 0) {
		free(vector[nfiles]);
	}
	free(vector);
	return -1;	
}
Пример #21
0
void DirClose(Dir *dir)
{
    closedir((DIR *) dir->dirh);
    free(dir->entrybuf);
    free(dir);
}
Пример #22
0
Файл: main.c Проект: borcun/free
int main(int argc, char **argv)
{
	struct dir_stat dStat1;
	struct dir_stat dStat2;
	char option[2];
	int i;
	
	// if argc equals 2 and second parameter is --help, call help
	if(argc == 2 && !strcmp("--help",argv[1])) {
		help();
		return 1;
	}
	
	// if argc doesn't equals 4, call usage and terminate program
	if(argc != 4) {
		usage();
		return 1;
	}
	
	// if argc equals 4 but optional parameter doesn't equal -s or -d
	// call usage and terminate program
	if(strcmp(argv[3],"-s") != 0 && strcmp(argv[3],"-d") != 0) {
		usage();
		return 1;
	}
	
	// take option parameter
	strcpy(option, argv[3]);
	
	// open directories
	dStat1.directory = opendir(argv[1]);
	dStat2.directory = opendir(argv[2]);
	
	// check if directories are opened or not
	if(dStat1.directory == NULL || dStat2.directory == NULL) {
		if(errno == EACCES) {
			fprintf(stderr,"%s\n","SEARCH or READ permission is denied.");
			return 1;
		}
		else if(errno == ENOTDIR) {
			fprintf(stderr,"%s\n","Path is not dir path.");
			return 1;
		}
		else {
			fprintf(stderr,"%s\n","Directory not opened.");
			return 1;		
		}
	}
	
	// copy directory names
	strcpy(dStat1.dirName, argv[1]);
	strcpy(dStat2.dirName, argv[2]);
	
	// count files number of directories
	countFileNumber(&dStat1);
	countFileNumber(&dStat2);
	
	// take files attributes of directories
	takeFileAttributes(&dStat1);
	takeFileAttributes(&dStat2);
	
	// sync directories
	syncDirectory(&dStat1, &dStat2, option);
	
	// close directories
	closedir(dStat1.directory);
	closedir(dStat2.directory);
	
	return 0;
};
Пример #23
0
void
addfdsns_to_list (TDSNCHOOSER *dsnchoose_t, char *path, Boolean b_reset)
{
  DataBrowserItemID item = DBITEM_ID + 1;
  DataBrowserCallbacks dbCallbacks;
  ThemeDrawingState outState = NULL;
  UInt16 colSize[3] = { 400, 100, 150 };
  SInt16 outBaseline;
  Point ioBound;
  int i;
  DIR *dir;
  char *path_buf;
  struct dirent *dir_entry;
  struct stat fstat;
  int b_added;
  ControlRef widget;
  WindowRef dlg;

  if (!dsnchoose_t || !path)
    return; 

  widget = dsnchoose_t->fdsnlist;
  dlg = dsnchoose_t->mainwnd;

  GetThemeDrawingState (&outState);

  /* Install an event handler on the component databrowser */
  dbCallbacks.version = kDataBrowserLatestCallbacks;
  InitDataBrowserCallbacks (&dbCallbacks);
  dbCallbacks.u.v1.itemNotificationCallback =
      NewDataBrowserItemNotificationUPP (fdsn_notification_item);
  /* On Mac OS X 10.0.x : clientDataCallback */
  dbCallbacks.u.v1.itemDataCallback =
      NewDataBrowserItemDataUPP (fdsn_getset_item);
  SetDataBrowserCallbacks (widget, &dbCallbacks);
  /* Begin the draw of the data browser */
  SetDataBrowserTarget (widget, DBITEM_ID);

  /* Make the clean up */
  for (i = 0; i < FDSN_nrows; i++, item++)
    {
      CFRelease (FDSN_array[i]);
      FDSN_array[i] = NULL;
      FDSN_type[i] = 0;
      RemoveDataBrowserItems (widget, DBITEM_ID, 1, &item, DBNAME_ID);
    }

  ActivateControl (widget);
  DrawOneControl (widget);

  /* Global Initialization */
  FDSN_nrows = 0;
  item = DBITEM_ID + 1;

  if ((dir = opendir (path)))
    {
      while ((dir_entry = readdir (dir)) && FDSN_nrows < MAX_ROWS)
	{
	  asprintf (&path_buf, "%s/%s", path, dir_entry->d_name);
	  b_added = 0;

	  if (stat ((LPCSTR) path_buf, &fstat) >= 0 && S_ISDIR (fstat.st_mode))
	    {
	      if (dir_entry->d_name && dir_entry->d_name[0] != '.') 
	        {
                  FDSN_array[FDSN_nrows] = CFStringCreateWithCString(NULL, dir_entry->d_name, kCFStringEncodingUTF8);
                  FDSN_type[FDSN_nrows] = 0;
                  b_added = 1;
	        }
	    }
	  else if (stat ((LPCSTR) path_buf, &fstat) >= 0 && !S_ISDIR (fstat.st_mode)
	           && strstr (dir_entry->d_name, ".dsn"))
	    {
              FDSN_array[FDSN_nrows] = CFStringCreateWithCString(NULL, dir_entry->d_name, kCFStringEncodingUTF8);
              FDSN_type[FDSN_nrows] = 1;
              b_added = 1;
	    }

	  if (path_buf)
	    free (path_buf);

	  if (b_added)
	    {
              GetThemeTextDimensions (FDSN_array[FDSN_nrows], kThemeSystemFont,
                kThemeStateActive, false, &ioBound, &outBaseline);
              if(colSize[0] < ioBound.h) colSize[0] = ioBound.h;

              AddDataBrowserItems (widget, DBITEM_ID, 1, &item, DBNAME_ID);
              item++;
              FDSN_nrows++;
            }
	}

      /* Close the directory entry */
      closedir (dir);
    }
  else
    create_error (NULL, NULL, "Error during accessing directory information",
	strerror (errno));

  ActivateControl (widget);
  /* Resize the columns to have a good look */
  SetDataBrowserTableViewNamedColumnWidth (widget, DBNAME_ID, colSize[0] + 20);
  DrawOneControl (widget);
  /* Remove the DataBrowser callback */
  SetDataBrowserCallbacks (NULL, &dbCallbacks);
  if(outState) DisposeThemeDrawingState (outState);

  if (b_reset)
    SetDataBrowserScrollPosition(widget, 0, 0);

  fill_dir_menu(dsnchoose_t, path);
}
Пример #24
0
int __getcwd(char *path, size_t size)
{
    struct stat above, current, tmp;
    struct dirent *entry;
    DIR *d;
    char *p, *up, *dotdot;
    int cycle;

    if (path == NULL || size <= 1) {
        errno= EINVAL;
        return -1;
    }

    p= path + size;
    *--p = 0;

    if (stat(".", &current) < 0) return -1;

    while (1) {
        dotdot= "..";
        if (stat(dotdot, &above) < 0) {
            recover(p);
            return -1;
        }

        if (above.st_dev == current.st_dev
                && above.st_ino == current.st_ino)
            break;	/* Root dir found */

        if ((d= opendir(dotdot)) == NULL) {
            recover(p);
            return -1;
        }

        /* Cycle is 0 for a simple inode nr search, or 1 for a search
         * for inode *and* device nr.
         */
        cycle= above.st_dev == current.st_dev ? 0 : 1;

        do {
            char name[3 + NAME_MAX + 1];

            tmp.st_ino= 0;
            if ((entry= readdir(d)) == NULL) {
                switch (++cycle) {
                case 1:
                    rewinddir(d);
                    continue;
                case 2:
                    closedir(d);
                    errno= ENOENT;
                    recover(p);
                    return -1;
                }
            }
            if (strcmp(entry->d_name, ".") == 0) continue;
            if (strcmp(entry->d_name, "..") == 0) continue;

            switch (cycle) {
            case 0:
                /* Simple test on inode nr. */
                if (entry->d_ino != current.st_ino) continue;
            /*FALL THROUGH*/

            case 1:
                /* Current is mounted. */
                strcpy(name, "../");
                strcpy(name+3, entry->d_name);
                if (stat(name, &tmp) < 0) continue;
                break;
            }
        } while (tmp.st_ino != current.st_ino
                 || tmp.st_dev != current.st_dev);

        up= p;
        if (addpath(path, &up, entry->d_name) < 0) {
            closedir(d);
            errno = ERANGE;
            recover(p);
            return -1;
        }
        closedir(d);

        if (chdir(dotdot) < 0) {
            recover(p);
            return -1;
        }
        p= up;

        current= above;
    }
    if (recover(p) < 0) return -1;	/* Undo all those chdir("..")'s. */
    if (*p == 0) *--p = '/';	/* Cwd is "/" if nothing added */
    if (p > path) strcpy(path, p);	/* Move string to start of path. */
    return 0;
}
Пример #25
0
std::vector<std::string> SerialInterface::enumerate_ports()
{
        std::vector<std::string> SerialDeviceList = std::vector<std::string>();
        
        #ifdef __unix__
        
        DIR *dp;
        struct dirent *dirp;
        std::string f, d;
        std::vector<std::string>::iterator it;
        char buf[PATH_MAX];
        
        struct serial_struct serinfo;
        int fd;
        
        if ((dp = opendir("/dev/")) == NULL)
        {
                std::cerr << "Error (" << errno << ") opening /dev/" << std::endl;
        }
        else
        {
                while ((dirp = readdir(dp)) != NULL)
                {
                        f = dirp->d_name;
                        d = "/dev/" + f;
                        if (f.find("ttyS") == 0)
                        {
                                if ((fd = ::open(d.c_str(), O_RDWR|O_NONBLOCK)) < 0)
                                {
                                        std::cerr << "Cannot open port " << d << std::endl;
                                        continue;
                                }
                                
                                serinfo.reserved_char[0] = 0;
                                
                                if (::ioctl(fd, TIOCGSERIAL, &serinfo) < 0)
                                {
                                        std::cerr << "Cannot get serial info for " << d << std::endl;
                                        ::close(fd);
                                        continue;
                                }
                                
                                if (serinfo.port != 0)
                                        SerialDeviceList.push_back(d);
                                
                                ::close(fd);
                                
                                continue;
                        }
                        if (f.find("ttyUSB") == 0)
                        {
                                SerialDeviceList.push_back(d);
                        }
                }
                
                closedir(dp);
        }
        
        if ((dp = opendir("/dev/serial/by-id/")) != NULL)
        {
                while ((dirp = readdir(dp)) != NULL)
                {
                        f = dirp->d_name;
                        if (f == "." || f == "..")
                                continue;
                        f = "/dev/serial/by-id/" + f;
                        if (realpath(f.c_str(), buf));
                        {
                                f = buf;
                                SerialDeviceList.push_back(f);
                        }
                }
                
                closedir(dp);
        }
        
        #elif defined _WIN32
        
        TCHAR szDevices[65535];
        unsigned long dwChars = QueryDosDevice(NULL, szDevices, 65535);
        TCHAR *ptr = szDevices;
        TCHAR *temp_ptr;
        std::string c;
        
        while (dwChars)
        {
                int port;
                
                if (sscanf(ptr, "COM%d", &port) == 1)
                {
                        c = ptr;
                        SerialDeviceList.push_back(c);
                }
                
                temp_ptr = strchr(ptr, 0);
                dwChars -= (DWORD)((temp_ptr - ptr) / sizeof(TCHAR) + 1);
                ptr = temp_ptr + 1;
        }
        
        #endif
        
        // sort it
        sort(SerialDeviceList.begin(), SerialDeviceList.end(), doj::alphanum_less<std::string>());
        
        // remove duplicates
        SerialDeviceList.erase(std::unique(SerialDeviceList.begin(), SerialDeviceList.end()), SerialDeviceList.end());
        
        return SerialDeviceList;
}
Пример #26
0
/*
 * return first found file name starting by the ``text'' or NULL if no
 * such file can be found
 * value of ``state'' is ignored
 *
 * it's the caller's responsibility to free the returned string
 */
char *
fn_filename_completion_function(const char *text, int state)
{
	static DIR *dir = NULL;
	static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
	static size_t filename_len = 0;
	struct dirent *entry;
	char *temp;
	size_t len;

	if (state == 0 || dir == NULL) {
		temp = strrchr(text, '/');
		if (temp) {
			char *nptr;
			temp++;
			nptr = el_realloc(filename, (strlen(temp) + 1) *
			    sizeof(*nptr));
			if (nptr == NULL) {
				el_free(filename);
				filename = NULL;
				return NULL;
			}
			filename = nptr;
			(void)strcpy(filename, temp);
			len = (size_t)(temp - text);	/* including last slash */

			nptr = el_realloc(dirname, (len + 1) *
			    sizeof(*nptr));
			if (nptr == NULL) {
				el_free(dirname);
				dirname = NULL;
				return NULL;
			}
			dirname = nptr;
			(void)strncpy(dirname, text, len);
			dirname[len] = '\0';
		} else {
			el_free(filename);
			if (*text == 0)
				filename = NULL;
			else {
				filename = strdup(text);
				if (filename == NULL)
					return NULL;
			}
			el_free(dirname);
			dirname = NULL;
		}

		if (dir != NULL) {
			(void)closedir(dir);
			dir = NULL;
		}

		/* support for ``~user'' syntax */

		el_free(dirpath);
		dirpath = NULL;
		if (dirname == NULL) {
			if ((dirname = strdup("")) == NULL)
				return NULL;
			dirpath = strdup("./");
		} else if (*dirname == '~')
			dirpath = fn_tilde_expand(dirname);
		else
			dirpath = strdup(dirname);

		if (dirpath == NULL)
			return NULL;

		dir = opendir(dirpath);
		if (!dir)
			return NULL;	/* cannot open the directory */

		/* will be used in cycle */
		filename_len = filename ? strlen(filename) : 0;
	}

	/* find the match */
	while ((entry = readdir(dir)) != NULL) {
		/* skip . and .. */
		if (entry->d_name[0] == '.' && (!entry->d_name[1]
		    || (entry->d_name[1] == '.' && !entry->d_name[2])))
			continue;
		if (filename_len == 0)
			break;
		/* otherwise, get first entry where first */
		/* filename_len characters are equal	  */
		if (entry->d_name[0] == filename[0]
          /* Some dirents have d_namlen, but it is not portable. */
		    && strlen(entry->d_name) >= filename_len
		    && strncmp(entry->d_name, filename,
			filename_len) == 0)
			break;
	}

	if (entry) {		/* match found */

       /* Some dirents have d_namlen, but it is not portable. */
		len = strlen(entry->d_name);

		len = strlen(dirname) + len + 1;
		temp = el_malloc(len * sizeof(*temp));
		if (temp == NULL)
			return NULL;
		(void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
	} else {
		(void)closedir(dir);
		dir = NULL;
		temp = NULL;
	}

	return temp;
}
Пример #27
0
char * findVideoDevice(const char *name)
{
    if(name == NULL) return NULL;
    DIR * d;
    char * video_pattern = "video";
    size_t video_pattern_len = strlen(video_pattern);
    size_t name_len = strlen(name);
    char * dir_name = "/dev/";
    char * result = NULL;

    printf("[UVC Cam ] Start finding video device\n");

    d = opendir (dir_name);
    if (! d) {
        fprintf (stderr, "Cannot open directory '%s': %s\n",
                 dir_name, strerror (errno));
        exit (EXIT_FAILURE);
    }
    while (1) {
        try{
            struct dirent * entry;
            entry = readdir (d);
            if (! entry) {
                break;
            }
            // if it is not a video device continue
            if(strncmp(video_pattern,entry->d_name,video_pattern_len)!=0) {
                continue;
            }
            // if video device name is not correct, coninue
            char * device = (char*) malloc(strlen(dir_name)+strlen(entry->d_name)+1);
            strcpy(device,dir_name);
            strcat(device, entry->d_name);
            printf("device=%s\n",device);
            printf("entry->d_name=%s\n",entry->d_name);
            int fd = open(device, O_RDWR|O_NONBLOCK);
            printf("FIND VIDEO DEVIC, FD is %d\n",fcntl(fd, F_GETFD));
            if (fd < 0) {
                printf("fd = -1\n");
                free(device);
                continue;
            }
            struct v4l2_capability info;
            memset(&info, 0x0, sizeof(info));
            int res = ioctl(fd, VIDIOC_QUERYCAP, &info);
            close(fd);
            if (res < 0 || strncmp(name,(char*)info.card,name_len)!=0)
            {
                printf("name=%s\n",name);
                printf("info.card=%s",(char*)info.card);
                printf("Error res is %d",res);
                free(device);
                continue;
            }
            result = device;
        }catch(...){
            continue;
        }
    }
    if (closedir (d)) {
        fprintf (stderr, "Could not close '%s': %s\n",
                 dir_name, strerror (errno));
        exit (EXIT_FAILURE);
    }
    printf("[UVC Cam] find video device OK result is %s\n", result);
    return result;
}
Пример #28
0
/*
 * Scan the [zcp] zedlet_dir for files to exec based on the event class.
 * Files must be executable by user, but not writable by group or other.
 * Dotfiles are ignored.
 *
 * Return 0 on success with an updated set of zedlets,
 * or -1 on error with errno set.
 *
 * FIXME: Check if zedlet_dir and all parent dirs are secure.
 */
int
zed_conf_scan_dir(struct zed_conf *zcp)
{
	zed_strings_t *zedlets;
	DIR *dirp;
	struct dirent *direntp;
	char pathname[PATH_MAX];
	struct stat st;
	int n;

	if (!zcp) {
		errno = EINVAL;
		zed_log_msg(LOG_ERR, "Failed to scan zedlet dir: %s",
		    strerror(errno));
		return (-1);
	}
	zedlets = zed_strings_create();
	if (!zedlets) {
		errno = ENOMEM;
		zed_log_msg(LOG_WARNING, "Failed to scan dir \"%s\": %s",
		    zcp->zedlet_dir, strerror(errno));
		return (-1);
	}
	dirp = opendir(zcp->zedlet_dir);
	if (!dirp) {
		int errno_bak = errno;
		zed_log_msg(LOG_WARNING, "Failed to open dir \"%s\": %s",
		    zcp->zedlet_dir, strerror(errno));
		zed_strings_destroy(zedlets);
		errno = errno_bak;
		return (-1);
	}
	while ((direntp = readdir(dirp))) {
		if (direntp->d_name[0] == '.')
			continue;

		n = snprintf(pathname, sizeof (pathname),
		    "%s/%s", zcp->zedlet_dir, direntp->d_name);
		if ((n < 0) || (n >= sizeof (pathname))) {
			zed_log_msg(LOG_WARNING, "Failed to stat \"%s\": %s",
			    direntp->d_name, strerror(ENAMETOOLONG));
			continue;
		}
		if (stat(pathname, &st) < 0) {
			zed_log_msg(LOG_WARNING, "Failed to stat \"%s\": %s",
			    pathname, strerror(errno));
			continue;
		}
		if (!S_ISREG(st.st_mode)) {
			zed_log_msg(LOG_INFO,
			    "Ignoring \"%s\": not a regular file",
			    direntp->d_name);
			continue;
		}
		if ((st.st_uid != 0) && !zcp->do_force) {
			zed_log_msg(LOG_NOTICE,
			    "Ignoring \"%s\": not owned by root",
			    direntp->d_name);
			continue;
		}
		if (!(st.st_mode & S_IXUSR)) {
			zed_log_msg(LOG_INFO,
			    "Ignoring \"%s\": not executable by user",
			    direntp->d_name);
			continue;
		}
		if ((st.st_mode & S_IWGRP) && !zcp->do_force) {
			zed_log_msg(LOG_NOTICE,
			    "Ignoring \"%s\": writable by group",
			    direntp->d_name);
			continue;
		}
		if ((st.st_mode & S_IWOTH) && !zcp->do_force) {
			zed_log_msg(LOG_NOTICE,
			    "Ignoring \"%s\": writable by other",
			    direntp->d_name);
			continue;
		}
		if (zed_strings_add(zedlets, NULL, direntp->d_name) < 0) {
			zed_log_msg(LOG_WARNING,
			    "Failed to register \"%s\": %s",
			    direntp->d_name, strerror(errno));
			continue;
		}
		if (zcp->do_verbose)
			zed_log_msg(LOG_INFO,
			    "Registered zedlet \"%s\"", direntp->d_name);
	}
	if (closedir(dirp) < 0) {
		int errno_bak = errno;
		zed_log_msg(LOG_WARNING, "Failed to close dir \"%s\": %s",
		    zcp->zedlet_dir, strerror(errno));
		zed_strings_destroy(zedlets);
		errno = errno_bak;
		return (-1);
	}
	if (zcp->zedlets)
		zed_strings_destroy(zcp->zedlets);

	zcp->zedlets = zedlets;
	return (0);
}
Пример #29
0
//Solaris and AIX should have this
DWORD
CTGetPidOfCmdLine(
    PCSTR programName,
    PCSTR programFilename,
    PCSTR cmdLine,
    uid_t owner,
    pid_t *pid,
    size_t *count
    )
{
    DWORD ceError = ERROR_NOT_SUPPORTED;
    size_t fillCount = 0;
    size_t foundCount = 0;
    struct stat findStat;
    DIR *dir = NULL;
    struct dirent *dirEntry = NULL;
    PSTR filePath = NULL;
    struct psinfo infoStruct;
    FILE *infoFile = NULL;
    struct stat compareStat;
    BOOLEAN bFileExists;
#if defined(__LWI_SOLARIS__)
    int (*getzoneid)() = NULL;
    int zoneid = -1;
#endif

    if(count)
    {
        fillCount = *count;
        *count = 0;
    }
    else if(pid != NULL)
        fillCount = 1;

    if(programFilename != NULL)
    {
        while(stat(programFilename, &findStat) < 0)
        {
            if(errno == EINTR)
                continue;
            GCE(ceError = LwMapErrnoToLwError(errno));
        }
    }

    if ((dir = opendir("/proc")) == NULL) {
        GCE(ceError = LwMapErrnoToLwError(errno));
    }

#if defined(__LWI_SOLARIS__)
    getzoneid = dlsym(RTLD_DEFAULT, "getzoneid");
    if (getzoneid)
    {
        zoneid = getzoneid();
    }
#endif

    while(1)
    {
        errno = 0;
        dirEntry = readdir(dir);
        if(dirEntry == NULL)
        {
            if(errno != 0)
                GCE(ceError = LwMapErrnoToLwError(errno));
            else
            {
                //No error here. We simply read the last entry
                break;
            }
        }
        if(dirEntry->d_name[0] == '.')
            continue;
        // On AIX, there is a /proc/sys which does not contain a psinfo
        if(!isdigit((int)dirEntry->d_name[0]))
            continue;
        CT_SAFE_FREE_STRING(filePath);
        GCE(ceError = CTAllocateStringPrintf(&filePath, "/proc/%s/psinfo",
                    dirEntry->d_name));
        GCE(ceError = CTCheckFileOrLinkExists(filePath, &bFileExists));
        if(!bFileExists)
        {
            // On AIX 6.1, a defunct process can lack a psinfo file.
            continue;
        }
        GCE(ceError = CTSafeCloseFile(&infoFile));
        GCE(ceError = CTOpenFile(filePath, "r", &infoFile));
        if(fread(&infoStruct, sizeof(infoStruct), 1, infoFile) != 1)
        {
            GCE(ceError = LwMapErrnoToLwError(errno));
        }

#if defined(__LWI_SOLARIS__)
        if (zoneid != -1)
        {
            int processzoneid = -1;

#ifdef HAVE_STRUCT_PSINFO_PR_ZONEID
            processzoneid = (int) infoStruct.pr_zoneid;
#else
            processzoneid = (int)
                *(infoStruct.pr_filler +
                sizeof(infoStruct.pr_filler)/sizeof(infoStruct.pr_filler[0]) -
                3);
#endif
            if (zoneid != processzoneid)
            {
                continue;
            }
        }
#endif

        if (owner != (uid_t)-1 && owner != infoStruct.pr_euid)
        {
            continue;
        }
        if (programName != NULL && strcmp(infoStruct.pr_fname, programName))
        {
            continue;
        }
        if (cmdLine != NULL && strcmp(infoStruct.pr_psargs, cmdLine))
        {
            continue;
        }
        if(programFilename != NULL)
        {
            CT_SAFE_FREE_STRING(filePath);
            GCE(ceError = CTAllocateStringPrintf(&filePath,
                        "/proc/%s/object/a.out",
                        dirEntry->d_name));

            while(stat(filePath, &compareStat) < 0)
            {
                if(errno == EINTR)
                    continue;
                if(errno == ENOENT || errno == ENOTDIR)
                {
                    //This process wasn't executed from a file?
                    goto not_match;
                }
                GCE(ceError = LwMapErrnoToLwError(errno));
            }
            if(findStat.st_ino != compareStat.st_ino)
                continue;
            if(findStat.st_dev != compareStat.st_dev)
                continue;
            if(findStat.st_rdev != compareStat.st_rdev)
                continue;
        }
 
        //This is a match
        if(foundCount < fillCount)
            pid[foundCount] = infoStruct.pr_pid;
        foundCount++;
not_match:
        ;
    }

    if(count)
        *count = foundCount;
    else if(!ceError && foundCount == 0)
        ceError = ERROR_PROC_NOT_FOUND;

cleanup:
    if(dir != NULL)
        closedir(dir);
    CT_SAFE_FREE_STRING(filePath);
    CTSafeCloseFile(&infoFile);

    return ceError;
}
Пример #30
0
int ScanFiles( char *base
             , char *mask
             , void **pInfo
             , void Process( char *name, int flags )
             , int flags
             )
{
    int sendflags;
    struct stat st;
    if( !*pInfo )
    {
        char findmask[256];
        sprintf( findmask, "%s/*", base );
        *pInfo = malloc( sizeof( MFD ) );
        findhandle(pInfo) = opendir( base );
        if( findhandle(pInfo) == NULL )
        {
            free( *pInfo );
            *pInfo = NULL;
            return 0;
        }
    }
    else
    {
    getnext:
        if( ( finddata( pInfo ) = readdir( findhandle(pInfo) ) ) == NULL )
        {
            closedir( findhandle(pInfo) );
            free( *pInfo );
            *pInfo = NULL;
            return 0;
        }
    }
    if( !strcmp( ".", finddata(pInfo)->d_name ) ||
         !strcmp( "..", finddata(pInfo)->d_name ) )
        goto getnext;
    if( flags & SFF_NAMEONLY )
        strncpy( findbuffer( pInfo ), finddata(pInfo)->d_name, MAX_PATH_NAME );
    else
        snprintf( findbuffer( pInfo ), MAX_PATH_NAME, "%s/%s", base, finddata(pInfo)->d_name );
    findbuffer( pInfo )[MAX_PATH_NAME-1] = 0; // force nul termination...
    stat( findbuffer( pInfo ), &st );
    if( ( flags & (SFF_DIRECTORIES|SFF_SUBCURSE) )
         && S_ISDIR(st.st_mode) )
    {
        if( flags & SFF_SUBCURSE  )
        {
            void *data = NULL;
            if( flags & SFF_DIRECTORIES )
                if( Process )
                    Process( findbuffer( pInfo ), SFF_DIRECTORY );
            if( flags & SFF_NAMEONLY ) // if nameonly - have to rebuild the correct name.
                snprintf( findbuffer( pInfo ), MAX_PATH_NAME, "%s/%s", base, finddata(pInfo)->d_name );
            while( ScanFiles( findbuffer(pInfo), mask, &data, Process, flags ) );
        }
        goto getnext;
    }

    if( ( sendflags = SFF_DIRECTORY, ( ( flags & SFF_DIRECTORIES )
            && ( S_ISDIR( st.st_mode ) ) ) )
         || ( sendflags = 0, CompareMask( mask, finddata(pInfo)->d_name, 0 ) ) )
    {
        if( Process )
            Process( findbuffer( pInfo ), sendflags );
        return 1;
    }
    return 1;
}