Ejemplo n.º 1
0
int		is_dir(char *name, char *path)
{
  char		*full_path;
  struct stat	stats;

  if ((full_path = malloc(strlen(name) + strlen(path) + 2)) == NULL)
    return (-1);
  if (path[strlen(path) - 1] == '/')
    {
      if (sprintf(full_path, "%s%s", path, name) < 0)
	return (-1);
    }
  else
    if (sprintf(full_path, "%s/%s", path, name) < 0)
      return (-1);
#ifdef DEBUG
  printf("Path = \"%s\"\nName = \"%s\"\n", path, name);
  printf("Full Path = %s\n", full_path);
#endif
  if (stat(full_path, &stats) < 0)
    return (free_dir(-1, full_path));
  if (S_ISREG(stats.st_mode))
    return (free_dir(0, full_path));
  else if (S_ISDIR(stats.st_mode))
    return (free_dir(1, full_path));
  return (free_dir(2, full_path));
}
Ejemplo n.º 2
0
void listdir(char *d, FILE *fp)
{
	char path[512], rpath[512];
#if 0
	long pathsize = 0;
#endif
	struct _info **dir, **sav;
	int n, i;
	char *s;
	static char *igdir[] = {
		"/nfs", "/dev", "/proc", "/opt", "/tmp", "/etc",
		 "nfs",  "dev",  "proc",  "opt",  "tmp",  "etc",
		NULL
	};

	sav = dir = read_dir(d, &n);
	if (!dir && n) Err("Dir read");
	if (!n) {
		free_dir(sav);
		return;
	}

	qsort(dir, n, sizeof(struct _info *), cmpfunc);

	for(i = 0;i < n;++i) {
#if 0
		if (sizeof(char) * (strlen(d)+strlen(dir[i]->name) + 2) > pathsize)
			path = xrealloc(path,pathsize=(sizeof(char) * (strlen(d)+strlen(dir[i]->name) + 1024)));
#endif
		if (!strncmp(d, "/", 1)) s = d + 1;
		else if (!strncmp(d, "./", 2)) s = d + 2;
		else s = d;
		sprintf(path,"%s/%s", s, dir[i]->name);

		sprintf(rpath,"%s/%s", d, dir[i]->name);

		if (dir[i]->isdir) {
			int j;
			int flg = 1;

			for(j = 0;igdir[j] != NULL;++j) {
				if (!strcmp(path, igdir[j])) {
					flg = 0;
					break;
				}
			}
//			if (flg) listdir(rpath, fp);
		}
		else {
			if (dir[i]->lnk == NULL) {
//				printf("delete %s\n", rpath);
				crstrip(rpath);
			}
		}
	}
//	free(path);
	free_dir(sav);

}
Ejemplo n.º 3
0
static void
free_dir (struct dir *root)
{
  if (!root)
    return;
  free_dir (root->next);
  free_dir (root->child);
  grub_free (root->name);
  grub_free (root);
}
Ejemplo n.º 4
0
grub_err_t
grub_initrd_load (struct grub_linux_initrd_context *initrd_ctx,
		  char *argv[], void *target)
{
  grub_uint8_t *ptr = target;
  int i;
  int newc = 0;
  struct dir *root = 0;
  grub_ssize_t cursize = 0;

  for (i = 0; i < initrd_ctx->nfiles; i++)
    {
      grub_memset (ptr, 0, ALIGN_UP_OVERHEAD (cursize, 4));
      ptr += ALIGN_UP_OVERHEAD (cursize, 4);

      if (initrd_ctx->components[i].newc_name)
	{
	  ptr += insert_dir (initrd_ctx->components[i].newc_name,
			     &root, ptr);
	  ptr = make_header (ptr, initrd_ctx->components[i].newc_name,
			     grub_strlen (initrd_ctx->components[i].newc_name),
			     0100777,
			     initrd_ctx->components[i].size);
	  newc = 1;
	}
      else if (newc)
	{
	  ptr = make_header (ptr, "TRAILER!!!", sizeof ("TRAILER!!!") - 1,
			     0, 0);
	  free_dir (root);
	  root = 0;
	  newc = 0;
	}

      cursize = initrd_ctx->components[i].size;
      if (grub_file_read (initrd_ctx->components[i].file, ptr, cursize)
	  != cursize)
	{
	  if (!grub_errno)
	    grub_error (GRUB_ERR_FILE_READ_ERROR, N_("premature end of file %s"),
			argv[i]);
	  grub_initrd_close (initrd_ctx);
	  return grub_errno;
	}
      ptr += cursize;
    }
  if (newc)
    ptr = make_header (ptr, "TRAILER!!!", sizeof ("TRAILER!!!") - 1, 0, 0);
  free_dir (root);
  root = 0;
  return GRUB_ERR_NONE;
}
Ejemplo n.º 5
0
Archivo: pgtz.c Proyecto: colinet/sqlix
void
pg_tzenumerate_end(pg_tzenum *dir)
{
	while (dir->depth >= 0) {
		free_dir(dir->dirdesc[dir->depth]);
		pfree(dir->dirname[dir->depth]);
		dir->depth--;
	}

	pfree(dir);
}
Ejemplo n.º 6
0
int
fts_close (FTS *sp)
{
	register FTSENT *freep, *p;
	int saved_errno = 0;

	/*
	 * This still works if we haven't read anything -- the dummy structure
	 * points to the root list, so we step through to the end of the root
	 * list which has a valid parent pointer.
	 */
	if (sp->fts_cur) {
		for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
			freep = p;
			p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
			free(freep);
		}
		free(p);
	}

	/* Free up child linked list, sort array, file name buffer. */
	if (sp->fts_child)
		fts_lfree(sp->fts_child);
	free(sp->fts_array);
	free(sp->fts_path);

	if (ISSET(FTS_CWDFD))
	  {
	    if (0 <= sp->fts_cwd_fd)
	      close (sp->fts_cwd_fd);
	  }
	else if (!ISSET(FTS_NOCHDIR))
	  {
	    /* Return to original directory, save errno if necessary. */
	    if (fchdir(sp->fts_rfd))
	      saved_errno = errno;
	    close(sp->fts_rfd);
	  }

	fd_ring_clear (&sp->fts_fd_ring);
	free_dir (sp);

	/* Free up the stream pointer. */
	free(sp);

	/* Set errno and return. */
	if (saved_errno) {
		__set_errno (saved_errno);
		return (-1);
	}

	return (0);
}
Ejemplo n.º 7
0
/*
 * calculate size of database in all tablespaces
 */
static int64 calculate_database_size(oid_t dbOid)
{
	int64 totalsize;
	DIR *dirdesc;
	struct dirent *direntry;
	char dirpath[MAX_PG_PATH];
	char pathname[MAX_PG_PATH];
	acl_result_e aclresult;

	/* User must have connect privilege for target database */
	aclresult = db_acl_check(dbOid, get_uid(), ACL_CONNECT);
	if (aclresult != ACLCHECK_OK)
		aclcheck_error(aclresult, ACL_KIND_DATABASE, get_db_name(dbOid));

	/* Shared storage in pg_global is not counted */

	/* Include pg_default storage */
	snprintf(pathname, MAX_PG_PATH, "base/%u", dbOid);
	totalsize = db_dir_size(pathname);

	/* scan_pl the non-default tablespaces */
	snprintf(dirpath, MAX_PG_PATH, "pg_tblspc");
	dirdesc = alloc_dir(dirpath);
	if (!dirdesc)
		ereport(ERROR, (errcode_file_access(),
		errmsg("could not open tablespace directory \"%s\": %m", dirpath)));

	while ((direntry = read_dir(dirdesc, dirpath)) != NULL) {
		CHECK_FOR_INTERRUPTS();

		if (strcmp(direntry->d_name, ".") == 0
			|| strcmp(direntry->d_name, "..") == 0)
			continue;

		snprintf(pathname, MAX_PG_PATH, "pg_tblspc/%s/%s/%u", direntry->d_name,
			 TBS_VERSION_DIR, dbOid);
		totalsize += db_dir_size(pathname);
	}

	free_dir(dirdesc);

	/* Complain if we found no trace of the DB at all */
	if (!totalsize)
		ereport(ERROR,
			(E_UNDEFINED_DATABASE,
			 errmsg("database with OID %u does not exist", dbOid)));

	return totalsize;
}
Ejemplo n.º 8
0
Archivo: pgtz.c Proyecto: colinet/sqlix
/*
 * scan_pl specified directory for a case-insensitive match to fname
 * (of length fnamelen --- fname may not be null terminated!).	If found,
 * copy the actual filename into canonname and return true.
 */
static bool
scan_directory_ci(
	const char *dirname,
	const char *fname,
	int fnamelen,
	char *canonname,
	int canonnamelen)
{
	bool found = false;
	DIR* dirdesc;
	struct dirent *direntry;

	dirdesc = alloc_dir(dirname);
	if (!dirdesc) {
		ereport(LOG, (
		errcode_file_access(),
		errmsg("could not open directory \"%s\": %m", dirname)));

		return false;
	}

	while ((direntry = read_dir(dirdesc, dirname)) != NULL) {
		/*
		 * Ignore . and .., plus any other "hidden" files.	This is a security
		 * measure to prevent access to files outside the timezone directory.
		 */
		if (direntry->d_name[0] == '.')
			continue;

		if (strlen(direntry->d_name) == fnamelen
			&& pg_strncasecmp(direntry->d_name, fname, fnamelen) == 0) {
			/* Found our match */
			strlcpy(canonname, direntry->d_name, canonnamelen);
			found = true;
			break;
		}
	}

	free_dir(dirdesc);

	return found;
}
Ejemplo n.º 9
0
/*
 * Cancel monitoring.
 */
int FAMCancelMonitor(FAMConnection *fc, FAMRequest *requestp)
{
    DirInfo *dir;
    unsigned request;
    kevent_t *kev;

    request = requestp->reqnum;
    if(request >= fc->dir_count || fc->dirs[request] == 0) {
        FAMErrno = FAM_BAD_REQUEST_NUMBER;
        return -1;
    }
    dir = fc->dirs[request];
    kev = dir->kevent;
    kev->flags = EV_DELETE;
    if (kevent(fc->id, kev, 1, NULL, 0, &gTime0) < 0)
        perror("FAMCancelMonitor");
    free_dir(dir);
    fc->dirs[request] = 0;
    return 0;
}
Ejemplo n.º 10
0
/*
	Generates a dummy fs using a *real* directory as a *model*
*/
int generate_dummy_fs(char* model_root_dir, char * destiny_file )
{
	buffer * buf = malloc(sizeof(buffer));
	buffer * content = malloc(sizeof(content));
	if(buf == NULL)
	{
		return GEN_FS_MEM;
	}
	
	dummy_dir * fs = malloc(sizeof(dummy_dir)); // fs is the root dir

	init( &fs->name );
	write( &fs->name, "", 1); // Empty string {'\0'}
	fs->parent = NULL;

	// Walk through dirs, build dir and file structure
	work_directory( model_root_dir , fs, model_root_dir );

	// TODO: Walk through all files in fs, read content and output to buffer
	init(content);
	// TODO: walk ...

	// Write header to buf
	init(buf);
	write_dummy_dir( fs , buf);
	
	// TODO: Write buffers to destiny file ...	
	// TODO: * Open file (create, overwrite)
	// TODO: * Write buffers (buf and content)
	// TODO: * Close file

	// Free memory
	destroy( &fs->name );
	free_dir(fs); (fs);
	destroy(content); free(content);
	destroy(buf); free(buf);

	return GEN_FS_SUCCESS ;
}
Ejemplo n.º 11
0
/*
 * Close the fc.
 */
int FAMClose(FAMConnection *fc)
{
    FAMEvent *event, *next;
    unsigned i;

    /* Free all the directories */
    for(i = 0; i != fc->dir_count; i++)
        if(fc->dirs[i])
            free_dir(fc->dirs[i]);

    /* Free all the events */
    event = fc->event;
    while(event) {
        next = event->next;
        free_fevent(event);
        event = next;
    }

    /* Reset the fc */
    close(fc->id);
    memset(fc, 0, sizeof(*fc));
    return 0;
}
Ejemplo n.º 12
0
/* Return physical size of directory contents, or 0 if dir doesn't exist */
static int64 db_dir_size(const char *path)
{
	int64 dirsize = 0;
	struct dirent *direntry;
	DIR *dirdesc;
	char filename[MAX_PG_PATH];

	dirdesc = alloc_dir(path);
	if (!dirdesc)
		return 0;

	while ((direntry = read_dir(dirdesc, path)) != NULL) {
		struct stat fst;

		CHECK_FOR_INTERRUPTS();

		if (strcmp(direntry->d_name, ".") == 0
			|| strcmp(direntry->d_name, "..") == 0)
			continue;

		snprintf(filename, MAX_PG_PATH, "%s/%s", path, direntry->d_name);
		if (stat(filename, &fst) < 0) {
			if (errno == ENOENT) {
				continue;
			} else {
				ereport(ERROR, (
				errcode_file_access(),
				errmsg("could not stat file \"%s\": %m", filename)));
			}
		}

		dirsize += fst.st_size;
	}

	free_dir(dirdesc);
	return dirsize;
}
Ejemplo n.º 13
0
void monitor()
{
    char *name = "/private/tmp/Books";
    DIR_NODE *old_dir = get_a_new_dir_node(name, 0, 0);
    DIR_NODE *new_dir;
    read_all_dirent(old_dir);

    while (1)
    {
        sleep(CHECK_INTERVAL);
        if (task_cnt != 0)
        {
            PRINT("ERR %s %d\n", __FILE__, __LINE__);
            return;
        }

        new_dir = get_a_new_dir_node(name, 0, 0);
        read_all_dirent(new_dir);
        dir_changes(old_dir, new_dir);
        free_dir(old_dir);
        old_dir = new_dir;

    }
}
Ejemplo n.º 14
0
Archivo: main.c Proyecto: huangxw/gx
static void *mainloop(void *thread_arg)
{
    struct REQUEST *conns = NULL;
    int curr_conn = 0;
    struct REQUEST      *req, *prev, *tmp;
    struct timeval      tv;
    int                 max;
    socklen_t           length;
    fd_set              rd, wr;

    for (; !termsig;) {
        if (got_sighup) {
            got_sighup = 0;
        }

        FD_ZERO(&rd);
        FD_ZERO(&wr);
        max = 0;

        /* add listening socket */
        if (curr_conn < max_conn) {
            FD_SET(slisten, &rd);
            max = slisten;
        }

        /* add connection sockets */
        for (req = conns; req != NULL; req = req->next) {
            switch (req->state) {
                case STATE_KEEPALIVE:
                case STATE_READ_HEADER:
                    FD_SET(req->fd, &rd);

                    if (req->fd > max) {
                        max = req->fd;
                    }

                    break;
                case STATE_WRITE_HEADER:
                case STATE_WRITE_BODY:
                case STATE_WRITE_FILE:
                case STATE_WRITE_RANGES:
                    FD_SET(req->fd, &wr);

                    if (req->fd > max) {
                        max = req->fd;
                    }

                    break;
            }
        }

        /* go! */
        tv.tv_sec  = keepalive_time;
        tv.tv_usec = 0;

        if (-1 == select(max + 1, &rd, &wr, NULL, (curr_conn > 0) ? &tv : NULL)) {
            perror("select");
            continue;
        }

        now = time(NULL);

        /* new connection ? */
        if (FD_ISSET(slisten, &rd)) {
            req = malloc(sizeof(struct REQUEST));

            if (NULL != req) {
                memset(req, 0, sizeof(struct REQUEST));

                if (-1 == (req->fd = accept(slisten, NULL, NULL))) {
                    if (EAGAIN != errno) {
                        free(req);
                    }
                } else {
                    close_on_exec(req->fd);
                    fcntl(req->fd, F_SETFL, O_NONBLOCK);
                    req->bfd = -1;
                    req->state = STATE_READ_HEADER;
                    req->ping = now;
                    req->next = conns;
                    conns = req;
                    curr_conn++;

                    /* Make sure the request has not been cancelled!
                     * Otherwise just ignore it. */
                    if (req) {
                        length = sizeof(req->peer);

                        if (-1 == getpeername(req->fd, (struct sockaddr *) & (req->peer), &length)) {
                            req->state = STATE_CLOSE;
                        }

                        getnameinfo((struct sockaddr *)&req->peer, length,
                                    req->peerhost, MAX_HOST,
                                    req->peerserv, MAX_MISC,
                                    NI_NUMERICHOST | NI_NUMERICSERV);
                        printf("%s:\tfd: %03d; connect from %s\n", get_time(), req->fd , req->peerhost);
                    }
                }
            }
        }

        /* check active connections */
        for (req = conns, prev = NULL; req != NULL;) {
            /* handle I/O */
            switch (req->state) {
                case STATE_KEEPALIVE:
                case STATE_READ_HEADER:

                    if (FD_ISSET(req->fd, &rd)) {
                        req->state = STATE_READ_HEADER;
                        read_request(req, 0);
                        req->ping = now;
                    }

                    break;
                case STATE_WRITE_HEADER:
                case STATE_WRITE_BODY:
                case STATE_WRITE_FILE:
                case STATE_WRITE_RANGES:

                    if (FD_ISSET(req->fd, &wr)) {
                        write_request(req);
                        req->ping = now;
                    }

                    break;
            }

            /* check timeouts */
            if (req->state == STATE_KEEPALIVE) {
                if (now > req->ping + keepalive_time || curr_conn > max_conn * 9 / 10) {
                    req->state = STATE_CLOSE;
                }
            } else if (req->state > 0) {
                if (now > req->ping + timeout) {
                    if (req->state == STATE_READ_HEADER) {
                        mkerror(req, 408, 0);
                    } else {
                        req->state = STATE_CLOSE;
                    }
                }
            }

            /* header parsing */
header_parsing:

            if (req->state == STATE_PARSE_HEADER) {
                parse_request(req);

                if (req->state == STATE_WRITE_HEADER) {
                    write_request(req);
                }
            }

            /* handle finished requests */
            if (req->state == STATE_FINISHED && !req->keep_alive) {
                req->state = STATE_CLOSE;
            }

            if (req->state == STATE_FINISHED) {
                req->auth[0]       = 0;
                req->if_modified   = NULL;
                req->if_unmodified = NULL;
                req->if_range      = NULL;
                req->range_hdr     = NULL;
                req->ranges        = 0;

                if (req->r_start) {
                    free(req->r_start);
                    req->r_start = NULL;
                }

                if (req->r_end) {
                    free(req->r_end);
                    req->r_end   = NULL;
                }

                if (req->r_head) {
                    free(req->r_head);
                    req->r_head  = NULL;
                }

                if (req->r_hlen) {
                    free(req->r_hlen);
                    req->r_hlen  = NULL;
                }

                list_free(&req->header);
                memset(req->mtime,   0, sizeof(req->mtime));

                if (req->bfd != -1) {
                    close(req->bfd);
                    req->bfd  = -1;
                }

                req->body      = NULL;
                req->written   = 0;
                req->head_only = 0;
                req->rh        = 0;
                req->rb        = 0;

                if (req->dir) {
                    free_dir(req->dir);
                    req->dir = NULL;
                }

                req->hostname[0] = 0;
                req->path[0]     = 0;
                req->query[0]    = 0;

                if (req->hdata == req->lreq) {
                    /* ok, wait for the next one ... */
                    req->state = STATE_KEEPALIVE;
                    req->hdata = 0;
                    req->lreq  = 0;
                } else {
                    /* there is a pipelined request in the queue ... */
                    req->state = STATE_READ_HEADER;
                    memmove(req->hreq, req->hreq + req->lreq,
                            req->hdata - req->lreq);
                    req->hdata -= req->lreq;
                    req->lreq  =  0;
                    read_request(req, 1);
                    goto header_parsing;
                }
            }

            /* connections to close */
            if (req->state == STATE_CLOSE) {
                close(req->fd);

                if (req->bfd != -1) {
                    close(req->bfd);
                }

                if (req->dir) {
                    free_dir(req->dir);
                }

                curr_conn--;
                printf("%s:\tfd: %03d; current connections: %d\n", get_time(), req->fd, curr_conn);
                /* unlink from list */
                tmp = req;

                if (prev == NULL) {
                    conns = req->next;
                    req = conns;
                } else {
                    prev->next = req->next;
                    req = req->next;
                }

                /* free memory  */
                if (tmp->r_start) {
                    free(tmp->r_start);
                }

                if (tmp->r_end) {
                    free(tmp->r_end);
                }

                if (tmp->r_head) {
                    free(tmp->r_head);
                }

                if (tmp->r_hlen) {
                    free(tmp->r_hlen);
                }

                list_free(&tmp->header);
                free(tmp);
            } else {
                prev = req;
                req = req->next;
            }
        }
    }

    return NULL;
}
Ejemplo n.º 15
0
int main(void)
{
    /* enable interrupts (on the CPU) */
    init_interrupts();

    /* Initialize audio and video */
    audio_init(44100,2);
    console_init();

    /* Initialize key detection */
    controller_init();

    MikMod_RegisterAllDrivers();
    MikMod_RegisterAllLoaders();

    md_mode |= DMODE_16BITS;
    md_mode |= DMODE_SOFT_MUSIC;
    md_mode |= DMODE_SOFT_SNDFX;
    //md_mode |= DMODE_STEREO;
                                            
    md_mixfreq = audio_get_frequency();

    MikMod_Init("");

    if(dfs_init( DFS_DEFAULT_LOCATION ) != DFS_ESUCCESS)
    {
        printf("Filesystem failed to start!\n");
    }
    else
    {
        direntry_t *list;
        int count = 0;
        int page = 0;
        int cursor = 0; 

        console_set_render_mode(RENDER_MANUAL);
        console_clear();

        list = populate_dir(&count);

        while(1)
        {
            console_clear();
            display_dir(list, cursor, page, MAX_LIST, count);
            console_render();

            controller_scan();
            struct controller_data keys = get_keys_down();

            if(keys.c[0].up)
            {
                cursor--;
                new_scroll_pos(&cursor, &page, MAX_LIST, count);
            }

            if(keys.c[0].down)
            {
                cursor++;
                new_scroll_pos(&cursor, &page, MAX_LIST, count);
            }

            if(keys.c[0].C_right && list[cursor].type == DT_REG)
            {
                /* Module playing loop */
                MODULE *module = NULL;

                /* Concatenate to make file */
                char path[512];

                strcpy( path, dir );
                strcat( path, list[cursor].filename );

                module = Player_Load(path, 256, 0);
                
                /* Ensure that first part of module doesn't get cut off */
                audio_write_silence();
                audio_write_silence();

                if(module)
                {
                    char c = '-';
                    int sw = 0;

                    Player_Start(module);

                    while(1)
                    {
                        if(sw == 5)
                        {
                            console_clear();
                            display_dir(list, cursor, page, MAX_LIST, count);

                            sw = 0;
                            switch(c)
                            {
                                case '-':
                                    c = '\\';
                                    break;
                                case '\\':
                                    c = '|';
                                    break;
                                case '|':
                                    c = '/';
                                    break;
                                case '/':
                                    c = '-';
                                    break;
                            }
    
                            printf("\n\n\n%c Playing module", c);                        
                            console_render();
                        }
                        else
                        {
                            sw++;
                        }

                        MikMod_Update();

                        controller_scan();
                        struct controller_data keys = get_keys_down();

                        if(keys.c[0].C_left || !Player_Active())
                        {
                            /* End playback */
                            audio_write_silence();
                            audio_write_silence();
                            audio_write_silence();
                            audio_write_silence();

                            break;
                        }
                    }
                
                    Player_Stop();
                    Player_Free(module);
                }
            }

            if(keys.c[0].L)
            {
                /* Open the SD card */
                strcpy( dir, "sd://" );

                /* Populate new directory */
                free_dir(list);
                list = populate_dir(&count);

                page = 0;
                cursor = 0;
            }

            if(keys.c[0].R)
            {
                /* Open the ROM FS card */
                strcpy( dir, "rom://" );

                /* Populate new directory */
                free_dir(list);
                list = populate_dir(&count);

                page = 0;
                cursor = 0;
            }

            if(keys.c[0].A && list[cursor].type == DT_DIR)
            {
                /* Change directories */
                chdir(list[cursor].filename);
       
                /* Populate new directory */
                free_dir(list);
                list = populate_dir(&count);

                page = 0;
                cursor = 0;
            }

            if(keys.c[0].B)
            {
                /* Up! */
                chdir("..");
       
                /* Populate new directory */
                free_dir(list);
                list = populate_dir(&count);

                page = 0;
                cursor = 0;
            }
        }
    }

    while(1);

    return 0;
}
Ejemplo n.º 16
0
Archivo: misc.c Proyecto: colinet/sqlix
datum_t pg_tablespace_databases(PG_FUNC_ARGS)
{
	struct fcall_ctx* funcctx;
	struct dirent* de;
	ts_db_fctx* fctx;

	if (SRF_IS_FIRSTCALL()) {
		struct mctx* oldcontext;
		oid_t tablespaceOid = ARG_OID(0);

		funcctx = SRF_FIRSTCALL_INIT();
		oldcontext = mctx_switch(funcctx->multi_call_memory_ctx);

		fctx = palloc(sizeof(ts_db_fctx));

		/*
		 * size = tablespace dirname length + dir sep char + oid + terminator
		 */
		fctx->location = (char *)palloc(9 + 1 + OIDCHARS + 1 + strlen(TBS_VERSION_DIR) + 1);
		if (tablespaceOid == GLOBAL_TBS_OID) {
			fctx->dirdesc = NULL;
			ereport(WARNING, (
			errmsg("global tablespace never has databases")));
		} else {
			if (tablespaceOid == DEFAULT_TBS_OID)
				sprintf(fctx->location, "base");
			else
				sprintf(fctx->location,
					"pg_tblspc/%u/%s",
					tablespaceOid,
					TBS_VERSION_DIR);

			fctx->dirdesc = alloc_dir(fctx->location);
			if (!fctx->dirdesc) {
				/* the only expected error is ENOENT */
				if (errno != ENOENT)
					ereport(ERROR, (
					errcode_file_access(),
					errmsg("could not open directory \"%s\": %m",
						fctx->location)));

				ereport(WARNING, (
				errmsg("%u is not a tablespace OID",
					tablespaceOid)));
			}
		}

		funcctx->user_fctx = fctx;
		mctx_switch(oldcontext);
	}

	funcctx = SRF_PERCALL_SETUP();
	fctx = (ts_db_fctx *) funcctx->user_fctx;
	if (!fctx->dirdesc)			/* not a tablespace */
		SRF_RETURN_DONE(funcctx);

	while ((de = read_dir(fctx->dirdesc, fctx->location)) != NULL) {
		char *subdir;
		DIR *dirdesc;
		oid_t datOid = atooid(de->d_name);

		/* this test skips . and .., but is awfully weak */
		if (!datOid)
			continue;

		/* if database subdir is empty, don't report tablespace as used */

		/* size = path length + dir sep char + file name + terminator */
		subdir = palloc(strlen(fctx->location) + 1 + strlen(de->d_name) + 1);
		sprintf(subdir, "%s/%s", fctx->location, de->d_name);
		dirdesc = alloc_dir(subdir);
		while ((de = read_dir(dirdesc, subdir)) != NULL) {
			if (strcmp(de->d_name, ".") != 0
				&& strcmp(de->d_name, "..") != 0)
				break;
		}

		free_dir(dirdesc);
		pfree(subdir);

		if (!de)
			continue;	/* indeed, nothing in it */

		SRF_RETURN_NEXT(funcctx, OID_TO_D(datOid));
	}

	free_dir(fctx->dirdesc);
	SRF_RETURN_DONE(funcctx);
}
Ejemplo n.º 17
0
grub_err_t
grub_initrd_init (int argc, char *argv[],
		  struct grub_linux_initrd_context *initrd_ctx)
{
  int i;
  int newc = 0;
  struct dir *root = 0;

  initrd_ctx->nfiles = 0;
  initrd_ctx->components = 0;

  initrd_ctx->components = grub_zalloc (argc
					* sizeof (initrd_ctx->components[0]));
  if (!initrd_ctx->components)
    return grub_errno;

  initrd_ctx->size = 0;

  for (i = 0; i < argc; i++)
    {
      const char *fname = argv[i];

      initrd_ctx->size = ALIGN_UP (initrd_ctx->size, 4);

      if (grub_memcmp (argv[i], "newc:", 5) == 0)
	{
	  const char *ptr, *eptr;
	  ptr = argv[i] + 5;
	  while (*ptr == '/')
	    ptr++;
	  eptr = grub_strchr (ptr, ':');
	  if (eptr)
	    {
	      grub_file_filter_disable_compression ();
	      initrd_ctx->components[i].newc_name = grub_strndup (ptr, eptr - ptr);
	      if (!initrd_ctx->components[i].newc_name)
		{
		  grub_initrd_close (initrd_ctx);
		  return grub_errno;
		}
	      initrd_ctx->size
		+= ALIGN_UP (sizeof (struct newc_head)
			    + grub_strlen (initrd_ctx->components[i].newc_name),
			     4);
	      initrd_ctx->size += insert_dir (initrd_ctx->components[i].newc_name,
					      &root, 0);
	      newc = 1;
	      fname = eptr + 1;
	    }
	}
      else if (newc)
	{
	  initrd_ctx->size += ALIGN_UP (sizeof (struct newc_head)
					+ sizeof ("TRAILER!!!") - 1, 4);
	  free_dir (root);
	  root = 0;
	  newc = 0;
	}
      grub_file_filter_disable_compression ();
      initrd_ctx->components[i].file = grub_file_open (fname);
      if (!initrd_ctx->components[i].file)
	{
	  grub_initrd_close (initrd_ctx);
	  return grub_errno;
	}
      initrd_ctx->nfiles++;
      initrd_ctx->components[i].size
	= grub_file_size (initrd_ctx->components[i].file);
      initrd_ctx->size += initrd_ctx->components[i].size;
    }

  if (newc)
    {
      initrd_ctx->size += ALIGN_UP (sizeof (struct newc_head)
				    + sizeof ("TRAILER!!!") - 1, 4);
      free_dir (root);
      root = 0;
    }
  
  return GRUB_ERR_NONE;
}
Ejemplo n.º 18
0
/*
 * copy_dir: copy a directory
 *
 * If recurse is false, subdirectories are ignored.  Anything that's not
 * a directory or a regular file is ignored.
 */
void copy_dir(char *fromdir, char *todir, bool recurse)
{
	DIR *xldir;
	struct dirent *xlde;
	char fromfile[MAX_PG_PATH];
	char tofile[MAX_PG_PATH];

	if (mkdir(todir, S_IRWXU) != 0)
		ereport(ERROR, (errcode_file_access(),
		errmsg("could not create directory \"%s\": %m", todir)));

	xldir = alloc_dir(fromdir);
	if (xldir == NULL)
		ereport(ERROR, (errcode_file_access(),
		errmsg("could not open directory \"%s\": %m", fromdir)));

	while ((xlde = read_dir(xldir, fromdir)) != NULL) {
		struct stat fst;

		/* If we got a cancel signal during the copy of the directory,
		 * quit */
		CHECK_FOR_INTERRUPTS();

		if (strcmp(xlde->d_name, ".") == 0 || strcmp(xlde->d_name, "..") == 0)
			continue;

		snprintf(fromfile, MAX_PG_PATH, "%s/%s", fromdir, xlde->d_name);
		snprintf(tofile, MAX_PG_PATH, "%s/%s", todir, xlde->d_name);

		if (lstat(fromfile, &fst) < 0)
			ereport(ERROR, (errcode_file_access(),
			errmsg("could not stat file \"%s\": %m", fromfile)));

		if (S_ISDIR(fst.st_mode)) {
			/* recurse to handle subdirectories */
			if (recurse)
				copy_dir(fromfile, tofile, true);
		} else if (S_ISREG(fst.st_mode))
			copy_file(fromfile, tofile);
	}
	free_dir(xldir);

	/*
	 * Be paranoid here and fsync all files to ensure the copy is really 
	 * done.
	 */
	xldir = alloc_dir(todir);
	if (xldir == NULL)
		ereport(ERROR, (errcode_file_access(),
		errmsg("could not open directory \"%s\": %m", todir)));

	while ((xlde = read_dir(xldir, todir)) != NULL) {
		struct stat fst;

		if (strcmp(xlde->d_name, ".") == 0  || strcmp(xlde->d_name, "..") == 0)
			continue;

		snprintf(tofile, MAX_PG_PATH, "%s/%s", todir, xlde->d_name);

		/*
		 * We don't need to sync subdirectories here since the recursive
		 * copy_dir will do it before it returns
		 */
		if (lstat(tofile, &fst) < 0)
			ereport(ERROR, (errcode_file_access(),
			errmsg("could not stat file \"%s\": %m", tofile)));

		if (S_ISREG(fst.st_mode))
			fsync_fname(tofile, false);
	}
	free_dir(xldir);

	/*
	 * It's important to fsync the destination directory itself as 
	 * individual file fsyncs don't guarantee that the directory entry for
	 * the file is synced. Recent versions of ext4 have made the window much
	 * wider but it's been true for ext3 and other filesystems in the past.
	 */
	fsync_fname(todir, true);
}
Ejemplo n.º 19
0
Archivo: xml.c Proyecto: execjosh/tree
off_t xml_listdir(char *d, int *dt, int *ft, u_long lev, dev_t dev)
{
  char *path;
  bool nlf = FALSE;
  long pathsize = 0;
  struct _info **dir, **sav;
  struct stat sb;
  int t, n, mt;

  if ((Level >= 0) && (lev > Level)) {
    if (!noindent) fputc('\n',outfile);
    return 0;
  }

  if (xdev && lev == 0) {
    stat(d,&sb);
    dev = sb.st_dev;
  }

  sav = dir = read_dir(d,&n);
  if (!dir && n) {
    fprintf(outfile,"<error>opening dir</error>\n");
    return 0;
  }
  if (!n) {
    if (!noindent) fputc('\n', outfile);
    free_dir(sav);
    return 0;
  }
  if (flimit > 0 && n > flimit) {
    fprintf(outfile,"<error>%d entries exceeds filelimit, not opening dir</error>%s",n,noindent?"":"\n");
    free_dir(sav);
    return 0;
  }

  if (cmpfunc) qsort(dir,n,sizeof(struct _info *), cmpfunc);
  if (lev >= maxdirs-1) {
    dirs = xrealloc(dirs,sizeof(int) * (maxdirs += 1024));
    memset(dirs+(maxdirs-1024), 0, sizeof(int) * 1024);
  }
  dirs[lev] = 1;
  if (!*(dir+1)) dirs[lev] = 2;
  if (!noindent) fprintf(outfile,"\n");

  path = malloc(pathsize=4096);

  while(*dir) {
    if (!noindent) xml_indent(lev);

    if ((*dir)->lnk) mt = (*dir)->mode & S_IFMT;
    else mt = (*dir)->mode & S_IFMT;
    for(t=0;ifmt[t];t++)
      if (ifmt[t] == mt) break;
    fprintf(outfile,"<%s", ftype[t]);

    if (fflag) {
      if (sizeof(char) * (strlen(d)+strlen((*dir)->name)+2) > pathsize)
	path=xrealloc(path,pathsize=(sizeof(char) * (strlen(d)+strlen((*dir)->name)+1024)));
      if (!strcmp(d,"/")) sprintf(path,"%s%s",d,(*dir)->name);
      else sprintf(path,"%s/%s",d,(*dir)->name);
    } else {
      if (sizeof(char) * (strlen((*dir)->name)+1) > pathsize)
	path=xrealloc(path,pathsize=(sizeof(char) * (strlen((*dir)->name)+1024)));
      sprintf(path,"%s",(*dir)->name);
    }

    fprintf(outfile, " name=\"");
    html_encode(outfile,path);
    fputc('"',outfile);

    if ((*dir)->lnk) {
      fprintf(outfile, " target=\"");
      html_encode(outfile,(*dir)->lnk);
      fputc('"',outfile);
    }
    xml_fillinfo(*dir);
    fputc('>',outfile);

    if ((*dir)->isdir) {
      if ((*dir)->lnk) {
	if (lflag && !(xdev && dev != (*dir)->dev)) {
	  if (findino((*dir)->inode,(*dir)->dev)) {
	    fprintf(outfile,"<error>recursive, not followed</error>");
	  } else {
	    saveino((*dir)->inode, (*dir)->dev);
	    if (*(*dir)->lnk == '/')
	      listdir((*dir)->lnk,dt,ft,lev+1,dev);
	    else {
	      if (strlen(d)+strlen((*dir)->lnk)+2 > pathsize) path=xrealloc(path,pathsize=(strlen(d)+strlen((*dir)->name)+1024));
	      if (fflag && !strcmp(d,"/")) sprintf(path,"%s%s",d,(*dir)->lnk);
	      else sprintf(path,"%s/%s",d,(*dir)->lnk);
	      listdir(path,dt,ft,lev+1,dev);
	    }
	    nlf = TRUE;
	  }
	}
      } else if (!(xdev && dev != (*dir)->dev)) {
	if (strlen(d)+strlen((*dir)->name)+2 > pathsize) path=xrealloc(path,pathsize=(strlen(d)+strlen((*dir)->name)+1024));
	if (fflag && !strcmp(d,"/")) sprintf(path,"%s%s",d,(*dir)->name);
	else sprintf(path,"%s/%s",d,(*dir)->name);
	saveino((*dir)->inode, (*dir)->dev);
	listdir(path,dt,ft,lev+1,dev);
	nlf = TRUE;
      }
      *dt += 1;
    } else *ft += 1;
    if (*(dir+1) && !*(dir+2)) dirs[lev] = 2;
    if (nlf) {
      nlf = FALSE;
      if (!noindent) xml_indent(lev);
    }
    fprintf(outfile,"</%s>%s",ftype[t],noindent?"":"\n");
    dir++;
  }
  dirs[lev] = 0;
  free(path);
  free_dir(sav);
  return 0;
}
Ejemplo n.º 20
0
Archivo: pgtz.c Proyecto: colinet/sqlix
pg_tz*
pg_tzenumerate_next(pg_tzenum *dir)
{
	while (dir->depth >= 0) {
		struct dirent *direntry;
		char fullname[MAX_PG_PATH];
		struct stat statbuf;

		direntry = read_dir(dir->dirdesc[dir->depth], dir->dirname[dir->depth]);
		if (!direntry) {
			/* End of this directory */
			free_dir(dir->dirdesc[dir->depth]);
			pfree(dir->dirname[dir->depth]);
			dir->depth--;
			continue;
		}

		if (direntry->d_name[0] == '.')
			continue;

		snprintf(fullname, MAX_PG_PATH, "%s/%s", dir->dirname[dir->depth], direntry->d_name);
		if (stat(fullname, &statbuf) != 0)
			ereport(ERROR, (
			errcode_file_access(),
			errmsg("could not stat \"%s\": %m", fullname)));

		if (S_ISDIR(statbuf.st_mode)) {
			/* Step into the subdirectory */
			if (dir->depth >= MAX_TZDIR_DEPTH - 1)
				ereport(ERROR, (
				errmsg_internal("timezone directory stack overflow")));

			dir->depth++;
			dir->dirname[dir->depth] = pstrdup(fullname);
			dir->dirdesc[dir->depth] = alloc_dir(fullname);
			if (!dir->dirdesc[dir->depth])
				ereport(ERROR, (
				errcode_file_access(),
				errmsg("could not open directory \"%s\": %m",
					fullname)));

			/* Start over reading in the new directory */
			continue;
		}

		/*
		 * Load this timezone using tzload() not pg_tzset(), so we don't fill
		 * the cache
		 */
		if (tzload(fullname + dir->baselen, dir->tz.TZname, &dir->tz.state, TRUE) != 0) {
			/* Zone could not be loaded, ignore it */
			continue;
		}

		if (!tz_acceptable(&dir->tz)) {
			/* Ignore leap-second zones */
			continue;
		}

		/* Timezone loaded OK. */
		return &dir->tz;
	}

	/* Nothing more found */
	return NULL;
}
Ejemplo n.º 21
0
/*
 * calculate total size of tablespace
 */
static int64 calculate_tablespace_size(oid_t tblspcOid)
{
	char tblspcPath[MAX_PG_PATH];
	char pathname[MAX_PG_PATH];
	int64 totalsize = 0;
	DIR *dirdesc;
	struct dirent *direntry;
	acl_result_e aclresult;

	/*
	 * User must have CREATE privilege for target tablespace, either
	 * explicitly granted or implicitly because it is default for current
	 * database.
	 */
	if (tblspcOid != current_tbs_id) {
		aclresult =
		    tbs_acl_check(tblspcOid, get_uid(), ACL_CREATE);
		if (aclresult != ACLCHECK_OK)
			aclcheck_error(aclresult, ACL_KIND_TABLESPACE, get_tbs_name(tblspcOid));
	}

	if (tblspcOid == DEFAULT_TBS_OID)
		snprintf(tblspcPath, MAX_PG_PATH, "base");
	else if (tblspcOid == GLOBAL_TBS_OID)
		snprintf(tblspcPath, MAX_PG_PATH, "global");
	else
		snprintf(tblspcPath, MAX_PG_PATH, "pg_tblspc/%u/%s", tblspcOid, TBS_VERSION_DIR);

	dirdesc = alloc_dir(tblspcPath);
	if (!dirdesc)
		ereport(ERROR, (errcode_file_access(),
		errmsg("could not open tablespace directory \"%s\": %m", tblspcPath)));

	while ((direntry = read_dir(dirdesc, tblspcPath)) != NULL) {
		struct stat fst;

		CHECK_FOR_INTERRUPTS();

		if (strcmp(direntry->d_name, ".") == 0
			|| strcmp(direntry->d_name, "..") == 0)
			continue;

		snprintf(pathname, MAX_PG_PATH, "%s/%s", tblspcPath, direntry->d_name);
		if (stat(pathname, &fst) < 0) {
			if (errno == ENOENT)
				continue;
			else
				ereport(ERROR, (
				errcode_file_access(),
				errmsg("could not stat file \"%s\": %m", pathname)));
		}

		if (S_ISDIR(fst.st_mode))
			totalsize += db_dir_size(pathname);

		totalsize += fst.st_size;
	}

	free_dir(dirdesc);

	return totalsize;
}
Ejemplo n.º 22
0
Archivo: pgtz.c Proyecto: colinet/sqlix
/*
 * Recursively scan the timezone database looking for the best match to
 * the system timezone behavior.
 *
 * tzdir points to a buffer of size MAX_PG_PATH.	On entry, it holds the
 * pathname of a directory containing TZ files.  We internally modify it
 * to hold pathnames of sub-directories and files, but must restore it
 * to its original contents before exit.
 *
 * tzdirsub points to the part of tzdir that represents the subfile name
 * (ie, tzdir + the original directory name length, plus one for the
 * first added '/').
 *
 * tt tells about the system timezone behavior we need to match.
 *
 * *bestscore and *bestzonename on entry hold the best score found so far
 * and the name of the best zone.  We overwrite them if we find a better
 * score.  bestzonename must be a buffer of length TZ_STRLEN_MAX + 1.
 */
static void
scan_available_timezones(
	char *tzdir,
	char *tzdirsub,
	struct tztry* tt,
	int *bestscore,
	char *bestzonename)
{
	int tzdir_orig_len = strlen(tzdir);
	DIR* dirdesc;
	struct dirent *direntry;

	dirdesc = alloc_dir(tzdir);
	if (!dirdesc) {
		ereport(LOG, (
		errcode_file_access(),
		errmsg("could not open directory \"%s\": %m", tzdir)));

		return;
	}

	while ((direntry = read_dir(dirdesc, tzdir)) != NULL) {
		struct stat statbuf;

		/* Ignore . and .., plus any other "hidden" files */
		if (direntry->d_name[0] == '.')
			continue;

		snprintf(tzdir + tzdir_orig_len, MAX_PG_PATH - tzdir_orig_len, "/%s", direntry->d_name);
		if (stat(tzdir, &statbuf) != 0) {
			ereport(LOG, (
			errcode_file_access(),
			errmsg("could not stat \"%s\": %m", tzdir)));

			tzdir[tzdir_orig_len] = '\0';
			continue;
		}

		if (S_ISDIR(statbuf.st_mode)) {
			/* Recurse into subdirectory */
			scan_available_timezones(tzdir, tzdirsub, tt, bestscore, bestzonename);
		} else {
			/* Load and test this file */
			int score = score_timezone(tzdirsub, tt);

			if (score > *bestscore) {
				*bestscore = score;
				strlcpy(bestzonename, tzdirsub, TZ_STRLEN_MAX + 1);
			} else if (score == *bestscore) {
				/* Consider how to break a tie */
				if (strlen(tzdirsub) < strlen(bestzonename)
					|| (strlen(tzdirsub) == strlen(bestzonename)
						&& strcmp(tzdirsub, bestzonename) < 0))
					strlcpy(bestzonename, tzdirsub, TZ_STRLEN_MAX + 1);
			}
		}

		/* Restore tzdir */
		tzdir[tzdir_orig_len] = '\0';
	}

	free_dir(dirdesc);
}
Ejemplo n.º 23
0
Archivo: xml.c Proyecto: execjosh/tree
void xmlr_listdir(struct _info **dir, char *d, int *dt, int *ft, u_long lev)
{
  char *path;
  long pathsize = 0;
  struct _info **sav = dir;
  bool nlf = FALSE;
  int mt, t;
  
  if (dir == NULL) return;
  
  dirs[lev] = 1;
  if (!*(dir+1)) dirs[lev] = 2;
  fprintf(outfile,"\n");
  
  path = malloc(pathsize=4096);
  
  while(*dir) {
    if (!noindent) xml_indent(lev);

    if ((*dir)->lnk) mt = (*dir)->mode & S_IFMT;
    else mt = (*dir)->mode & S_IFMT;
    for(t=0;ifmt[t];t++)
      if (ifmt[t] == mt) break;
    fprintf(outfile,"<%s", ftype[t]);

    if (fflag) {
      if (sizeof(char) * (strlen(d)+strlen((*dir)->name)+2) > pathsize)
	path=xrealloc(path,pathsize=(sizeof(char) * (strlen(d)+strlen((*dir)->name)+1024)));
      if (!strcmp(d,"/")) sprintf(path,"%s%s",d,(*dir)->name);
      else sprintf(path,"%s/%s",d,(*dir)->name);
    } else {
      if (sizeof(char) * (strlen((*dir)->name)+1) > pathsize)
	path=xrealloc(path,pathsize=(sizeof(char) * (strlen((*dir)->name)+1024)));
      sprintf(path,"%s",(*dir)->name);
    }

    fprintf(outfile, " name=\"");
    html_encode(outfile,path);
    fputc('"',outfile);

    if ((*dir)->lnk) {
      fprintf(outfile, " target=\"");
      html_encode(outfile,(*dir)->lnk);
      fputc('"',outfile);
    }

    xml_fillinfo(*dir);
    if (mt != S_IFDIR && mt != S_IFLNK && (*dir)->err == NULL) fprintf(outfile,"/>");
    else fputc('>',outfile);

    if ((*dir)->err) {
      fprintf(outfile,"<error>%s</error>", (*dir)->err);
      free((*dir)->err);
      (*dir)->err = NULL;
    }
    if ((*dir)->child) {
      if (fflag) {
	if (strlen(d)+strlen((*dir)->name)+2 > pathsize) path=xrealloc(path,pathsize=(strlen(d)+strlen((*dir)->name)+1024));
	if (!strcmp(d,"/")) sprintf(path,"%s%s",d,(*dir)->name);
	else sprintf(path,"%s/%s",d,(*dir)->name);
      }
      xmlr_listdir((*dir)->child, fflag? path : NULL, dt, ft, lev+1);
      nlf = TRUE;
      *dt += 1;
    } else {
      if ((*dir)->isdir) *dt += 1;
      else *ft += 1;
    }
    
    if (*(dir+1) && !*(dir+2)) dirs[lev] = 2;
    if (nlf) {
      nlf = FALSE;
      if (!noindent) xml_indent(lev);
    }
    if (mt == S_IFDIR || mt == S_IFLNK || (*dir)->err != NULL) fprintf(outfile,"</%s>\n",ftype[t]);
    else putc('\n',outfile);
    dir++;
  }
  dirs[lev] = 0;
  free(path);
  free_dir(sav);
}