Пример #1
0
/* recursively create directory and parents */
int rmkdir(char *dir, mode_t mode)
{
        char *parent;
        int i;
        int r = 0;

        if (mkdir(dir, mode) != 0) {
                if (errno == ENOENT) {
                        parent = strdup(dir);
                        for (i=strlen(parent);i>0;--i) {
                                if (parent[i] == '/') {
                                        parent[i] = '\0';
                                        if ((r=rmkdir(parent,mode))!= 1) break;
                                }
                        }
                        free(parent);
                        if (r == 0) return 0;
                        rmkdir(dir, mode);
                }
                else if (errno != EEXIST) {
                        syslog(LOG_ERR, "Error creating directory '%s': %s",
                                dir, strerror(errno));
                        return 0;
                }
                else {
                        return -1;
                }
        }
        else {
                syslog(LOG_DEBUG, "Directory '%s' created", dir);
                return 1;
        }
        return -1;
}
Пример #2
0
static bool extract_entry(chm_file* h, chm_entry* e, const char* base_path) {
    int64_t path_len;
    char buf[32768];
    char* i;

    if (e->path[0] != '/')
        return true;

    /* quick hack for security hole mentioned by Sven Tantau */
    if (strstr(e->path, "/../") != NULL) {
        /* fprintf(stderr, "Not extracting %s (dangerous path)\n", ui->path); */
        return true;
    }

    if (snprintf(buf, sizeof(buf), "%s%s", base_path, e->path) > 1024) {
        return false;
    }

    /* Get the length of the path */
    path_len = strlen(e->path) - 1;

    if (e->path[path_len] == '/') {
        /* this is directory */
        return rmkdir(buf) != -1;
    }

    /* this is file */
    FILE* fout;
    int64_t len, remain = (int64_t)e->length;
    int64_t offset = 0;

    printf("--> %s\n", e->path);
    if ((fout = fopen(buf, "wb")) == NULL) {
        /* make sure that it isn't just a missing directory before we abort */
        char newbuf[32768];
        strcpy(newbuf, buf);
        i = strrchr(newbuf, '/');
        *i = '\0';
        rmkdir(newbuf);
        if ((fout = fopen(buf, "wb")) == NULL)
            return false;
    }

    while (remain != 0) {
        len = chm_retrieve_entry(h, e, (uint8_t*)buf, offset, sizeof(buf));
        if (len > 0) {
            fwrite(buf, 1, (size_t)len, fout);
            offset += (int64_t)len;
            remain -= len;
        } else {
            fprintf(stderr, "incomplete file: %s\n", e->path);
            break;
        }
    }

    fclose(fout);
    return true;
}
Пример #3
0
static int rmkdir(char *path)
{
    /*
     * strip off trailing components unless we can stat the directory, or we
     * have run out of components
     */

    char *i = strrchr(path, '/');

    if(path[0] == '\0'  ||  dir_exists(path))
        return 0;

    if (i != NULL)
    {
        *i = '\0';
        rmkdir(path);
        *i = '/';
        mkdir(path, 0777);
    }

#ifdef WIN32
        return 0;
#else
    if (dir_exists(path))
        return 0;
    else
        return -1;
#endif
}
Пример #4
0
static void
init_ns(void) {
	struct stat st;
	char *s;

	if(address && strncmp(address, "unix!", 5) == 0) {
		ns_path = estrdup(&address[5]);
		s = strrchr(ns_path, '/');
		if(s != nil)
			*s = '\0';
	}
	else if((s = getenv("NAMESPACE")))
		ns_path = s;
	else
		ns_path = ns_display();

	if((ns_path[0] != '/') || (strlen(ns_path) == 0))
		fatal("Bad ns_path");

	rmkdir(ns_path, 0700);

	if(stat(ns_path, &st))
		fatal("Can't stat ns_path '%s': %r", ns_path);
	if(getuid() != st.st_uid)
		fatal("ns_path '%s' exists but is not owned by you", ns_path);
	if(st.st_mode & 077)
		fatal("ns_path '%s' exists, but has group or world permissions", ns_path);
}
Пример #5
0
int affix_init(int argc, char *argv[], int facility)
{
	int		fd, err;
	static int	affix_running = 0;
	
	if (affix_running)
		return 0;

	affix_logmask = 0xffff;

	fd = socket(PF_AFFIX, SOCK_RAW, BTPROTO_HCI);
	if (fd < 0 && errno == EAFNOSUPPORT) {
		// try to load module
		system("/sbin/modprobe affix");
		fd = socket(PF_AFFIX, SOCK_RAW, BTPROTO_HCI);
		if (fd < 0)
			return fd;
	}
	close(fd);
	affix_running = 1;

	/* set environment */
	__argc = argc;
	__argv = argv;
	progname = argv[0];

	openlog(argv[0], LOG_PERROR, facility);
	
	if (getuid() == 0) {
		/* root -> put the stuff to /var/spool/affix */
		sprintf(affix_userpref, "/var/spool/affix");
	} else
		sprintf(affix_userpref, "%s/.bluetooth", getenv("HOME"));
	err = rmkdir(affix_userpref, 0700);
	if (err < 0) {
		perror("Unable to create dir\n");
		return err;
	}
	sprintf(affix_cachefile, "%s/devcache", affix_userpref);
	btdev_cache_init();
	atexit(do_exit);
	return 0;
}
Пример #6
0
static int rmkdir(char *path)
{
        char *i = strrchr(path, '/');

        if(path[0] == '\0'  ||  file_exists(path))
                return 0;

        if (i != NULL) {
                *i = '\0';
                rmkdir(path);
                *i = '/';
                mkdir(path, 0777);
        }

        if (file_exists(path))
                return 0;
        else
                return -1;
}
Пример #7
0
int main(int argc, char **argv)
{
    char word[MAXWORD+1];
    int cmd;
    int wrdlen;
    if(argc >= 2) {
        handle = clnt_create(argv[1], DIRPROG, DIRVERS, "tcp");
    } else{
        handle = clnt_create(RMACHINE, DIRPROG, DIRVERS, "tcp");
    }

    if (handle == NULL) {
        printf("cound not contact remote program.\n");
        exit(1);
    }

    while (1) {
        scanf("%d",&cmd);
        if(cmd == 10)
            exit(0);
        scanf("%s",word);
        switch(cmd) {
        case 1:
            rmkdir(word);
            printf("mkdir dir %s\n",word);
            break;
        case 2:
            rrmdir(word);
            printf("rmdir dir %s\n",word);
            break;
        case 10:
            printf("program quits.\n");
            exit(0);
        default:
            printf("command %d invalid.\n", cmd);
            break;
        }
    }
    return 0;
}
Пример #8
0
static int
rmkdir(char *path)
{
  /*
   * strip off trailing components unless we can stat the directory, or we
   * have run out of components
   */

  char *i = rindex(path, '/');

  if (path[0] == '\0'  ||  dir_exists(path))
    return 0;

  if (i != NULL) {
    *i = '\0';
    rmkdir(path);
    *i = '/';
    mkdir(path, 0777);
  }

  return dir_exists(path) ? 0 : -1;
}
Пример #9
0
/*
 * callback function for enumerate API
 */
int _extract_callback(struct chmFile *h,
              struct chmUnitInfo *ui,
              void *context)
{
    LONGUINT64 ui_path_len;
    char buffer[32768];
    struct extract_context *ctx = (struct extract_context *)context;
    char *i;

    if (ui->path[0] != '/')
        return CHM_ENUMERATOR_CONTINUE;

    /* quick hack for security hole mentioned by Sven Tantau */
    if (strstr(ui->path, "/../") != NULL)
    {
        /* fprintf(stderr, "Not extracting %s (dangerous path)\n", ui->path); */
        return CHM_ENUMERATOR_CONTINUE;
    }

    if (snprintf(buffer, sizeof(buffer), "%s%s", ctx->base_path, ui->path) > 1024)
        return CHM_ENUMERATOR_FAILURE;

    /* Get the length of the path */
    ui_path_len = strlen(ui->path)-1;

    /* Distinguish between files and dirs */
    if (ui->path[ui_path_len] != '/' )
    {
        FILE *fout;
        LONGINT64 len, remain=ui->length;
        LONGUINT64 offset = 0;

        printf("--> %s\n", ui->path);
        if ((fout = fopen(buffer, "wb")) == NULL)
	{
	    /* make sure that it isn't just a missing directory before we abort */ 
	    char newbuf[32768];
	    strcpy(newbuf, buffer);
	    i = strrchr(newbuf, '/');
	    *i = '\0';
	    rmkdir(newbuf);
	    if ((fout = fopen(buffer, "wb")) == NULL)
              return CHM_ENUMERATOR_FAILURE;
	}

        while (remain != 0)
        {
            len = chm_retrieve_object(h, ui, (unsigned char *)buffer, offset, 32768);
            if (len > 0)
            {
                fwrite(buffer, 1, (size_t)len, fout);
                offset += len;
                remain -= len;
            }
            else
            {
                fprintf(stderr, "incomplete file: %s\n", ui->path);
                break;
            }
        }

        fclose(fout);
    }
    else
    {
        if (rmkdir(buffer) == -1)
            return CHM_ENUMERATOR_FAILURE;
    }

    return CHM_ENUMERATOR_CONTINUE;
}
Пример #10
0
/**
 * Download a file.
 *
 * @param url URL.
 * @param cache_key Cache key.
 *
 * If the file is present in the cache, the cached version
 * will be retrieved. Otherwise, the file will be downloaded.
 *
 * If the file was not found on the server, or it was not found
 * the last time it was requested, an empty string will be
 * returned, and a zero-byte file will be stored in the cache.
 *
 * @return Absolute path to the cached file.
 */
string CacheManager::download(
	const string &url,
	const string &cache_key)
{
	// Check the main cache key.
	string cache_filename = getCacheFilename(cache_key);
	if (cache_filename.empty()) {
		// Error obtaining the cache key filename.
		return string();
	}

	// Lock the semaphore to make sure we don't
	// download too many files at once.
	SemaphoreLocker locker(m_dlsem);

	// Check if the file already exists.
	if (!access(cache_filename, R_OK)) {
		// File exists.
		// Is it larger than 0 bytes?
		int64_t sz = filesize(cache_filename);
		if (sz == 0) {
			// File is 0 bytes, which indicates it didn't exist
			// on the server. If the file is older than a week,
			// try to redownload it.
			// TODO: Configurable time.
			// TODO: How should we handle errors?
			time_t filetime;
			if (get_mtime(cache_filename, &filetime) != 0)
				return string();

			struct timeval systime;
			if (gettimeofday(&systime, nullptr) != 0)
				return string();
			if ((systime.tv_sec - filetime) < (86400*7)) {
				// Less than a week old.
				return string();
			}

			// More than a week old.
			// Delete the cache file and redownload it.
			if (delete_file(cache_filename) != 0)
				return string();
		} else if (sz > 0) {
			// File is larger than 0 bytes, which indicates
			// it was cached successfully.
			return cache_filename;
		}
	}

	// Check if the URL is blank.
	// This is allowed for some databases that are only available offline.
	if (url.empty()) {
		// Blank URL. Don't try to download anything.
		// Don't mark the file as unavailable by creating a
		// 0-byte dummy file, either.
		return string();
	}

	// Make sure the subdirectories exist.
	// NOTE: The filename portion MUST be kept in cache_filename,
	// since the last component is ignored by rmkdir().
	if (rmkdir(cache_filename) != 0) {
		// Error creating subdirectories.
		return string();
	}

	// TODO: Keep-alive cURL connections (one per server)?
	m_downloader->setUrl(url);
	m_downloader->setProxyUrl(m_proxyUrl);
	int ret = m_downloader->download();

	// Write the file to the cache.
	unique_ptr<IRpFile> file(new RpFile(cache_filename, RpFile::FM_CREATE_WRITE));

	if (ret != 0 || !file || !file->isOpen()) {
		// Error downloading the file, or error opening
		// the file in the local cache.

		// TODO: Only keep a negative cache if it's a 404.
		// Keep the cached file as a 0-byte file to indicate
		// a "negative" hit, but return an empty filename.
		return string();
	}

	// Write the file.
	file->write((void*)m_downloader->data(), m_downloader->dataSize());
	file->close();

	// Set the file's mtime if it was obtained by the downloader.
	// TODO: IRpFile::set_mtime()?
	time_t mtime = m_downloader->mtime();
	if (mtime >= 0) {
		set_mtime(cache_filename, mtime);
	}

	// Return the cache filename.
	return cache_filename;
}
Пример #11
0
/*
 * callback function for enumerate API
 */
static int
_extract_callback(struct chmFile *h, struct chmUnitInfo *ui, void *context)
{
  gchar* fname = NULL;
  char buffer[32768];
  struct extract_context *ctx = (struct extract_context *)context;
  char *i;

  if (ui->path[0] != '/') {
    return CHM_ENUMERATOR_CONTINUE;
  }

  g_debug("ui->path = %s", ui->path);

  fname = g_build_filename(ctx->base_path, ui->path+1, NULL);

  if (ui->length != 0) {
    FILE *fout;
    LONGINT64 len, remain = ui->length;
    LONGUINT64 offset = 0;

    gchar *file_ext;

    file_ext = g_strrstr(g_path_get_basename(ui->path), ".");
    g_debug("file_ext = %s", file_ext);

    if ((fout = fopen(fname, "wb")) == NULL) {
      /* make sure that it isn't just a missing directory before we abort */
      char newbuf[32768];
      strcpy(newbuf, fname);
      i = rindex(newbuf, '/');
      *i = '\0';
      rmkdir(newbuf);

      if ((fout = fopen(fname, "wb")) == NULL) {
        g_message("CHM_ENUMERATOR_FAILURE fopen");
        return CHM_ENUMERATOR_FAILURE;
      }
    }

    while (remain != 0) {
      len = chm_retrieve_object(h, ui, (unsigned char *)buffer, offset, 32768);
      if (len > 0) {
        if(fwrite(buffer, 1, (size_t)len, fout) != len) {
          g_message("CHM_ENUMERATOR_FAILURE fwrite");
          return CHM_ENUMERATOR_FAILURE;
        }
        offset += len;
        remain -= len;
      } else {
        break;
      }
    }

    fclose(fout);
    extract_post_file_write(fname);
  } else {
    if (rmkdir(fname) == -1) {
      g_message("CHM_ENUMERATOR_FAILURE rmkdir");
      return CHM_ENUMERATOR_FAILURE;
    }
  }
  g_free(fname);
  return CHM_ENUMERATOR_CONTINUE;
}
Пример #12
0
void recursiveDir (char lotpath[],char lotinternpath[],unsigned int lotNr,char subname[], char server[]) {

	DIR *DIRH;
	struct dirent *dp;
	char nextdirname[512];
	char filname[512];
	char dirname[512];
	char lotinternfilname[512];

	struct stat inode;

	sprintf(dirname,"%s%s",lotpath,lotinternpath);

	if (stat(dirname,&inode) != 0) {
		perror(dirname);
		return;
	}

	if (S_ISREG(inode.st_mode)) {
		printf("sending file \"%s\" as \"%s\"\n",dirname,lotinternpath);
		if (server != NULL) {
			if (!rSendFileToHostname(dirname,lotinternpath,lotNr, "w", subname, server)) {
                                printf("can't send file %s\n",filname);
				exit(-1);
        		}			
		}
		else {
			rSendFile(dirname,lotinternpath,lotNr, "w",subname);
		}
	}
	else if (S_ISDIR(inode.st_mode)) {

	if ((DIRH = opendir(dirname)) == NULL) {
		perror(dirname);
		return;
	}	

	while ((dp = readdir(DIRH)) != NULL) {

		if ((dp->d_type == DT_DIR) && ((strcmp(dp->d_name,".") == 0) || (strcmp(dp->d_name,"..") == 0))) {
			#ifdef DEBUG
				printf(". domain\n");
			#endif
		}
		else if (dp->d_type == DT_DIR) {
			//if (lotinternpath[0] == '\0') {
				sprintf(nextdirname,"%s%s/",lotinternpath,dp->d_name);
			//}
			//else {
			//	strcpy(nextdirname,dp->d_name);
			//}
			printf("dir (nextdirname %s)\n",nextdirname);
			rmkdir(nextdirname,lotNr,subname);

			//kaller seg selv rekurift
			recursiveDir(lotpath,nextdirname,lotNr,subname,server);
		}
		else if (dp->d_type == DT_REG) {
			printf("file - ");
			sprintf(filname,"%s%s",dirname,dp->d_name);
			sprintf(lotinternfilname,"%s%s",lotinternpath,dp->d_name);
			printf("file %s, %u %s\n",filname,lotNr,lotinternfilname);	

			if (server != NULL) {
				if (!rSendFileToHostname(filname,lotinternfilname,lotNr, "w",subname, server)) {
                	                printf("can't send file %s\n",filname);
        	                }			
			}
			else {
				rSendFile(filname,lotinternfilname,lotNr, "w",subname);
			}
		}
		else {
			printf("unknown type %i\n",dp->d_type);
		}
		//printf("%s %i\n",dp->d_name,dp->d_type);

	}

	closedir(DIRH);

	}
	else {
		fprintf(stderr,"File \"%s\" is neader directory, nor normal file!\n",dirname);
		exit(1);
	}
}
Пример #13
0
main (int argc, char *argv[]) {

	char lotpath[512];
	int lotNr;
	char file[512];

	char *optHost = NULL;

        extern char *optarg;
        extern int optind, opterr, optopt;
        char c;
        while ((c=getopt(argc,argv,"h:"))!=-1) {
                switch (c) {
                        case 'h':
                                optHost = optarg;
                                fprintf(stderr, "Will send to host %s\n",optHost);

                                break;
                        default:
                                exit(1);
                }

        }
        --optind;



	if (argc -optind < 3) {
               	printf("Dette programet kopierer en lot til en annen server\n\n\t./lotcp lotnr subname [file]\n\n");
		printf("Options:\n\t-h host\n\n");
               	exit(0);
        }


	lotNr = atol(argv[1 +optind]);
	char *subname = argv[2 +optind];
	
	//int rmkdir(char dest[], int LotNr,char subname[]);
	rmkdir("",lotNr,subname);


	//void GetFilPathForLot(char *FilePath,int LotNr,char subname[]);		
	GetFilPathForLot(lotpath,lotNr,argv[2 +optind]);
	
	#ifdef DEBUG
	printf("lotpath %s\n",lotpath);
	#endif

	if ((argc -optind) == 3) {
		recursiveDir(lotpath,"",lotNr,subname,optHost);
	}
	else if ((argc -optind) == 4) {
		strcpy(file,argv[3 +optind]);
		//hvis vi er en mappe må vi slutte på /. Hvis vi ikke her det legger vi til en /
		if((strchr(file,'/') != NULL) && (file[strlen(file) -1] != '/')) {
			printf("adding a / to \"%s\"\n",file);
			strcat(file,"/");
		}
		recursiveDir(lotpath,file,lotNr,subname,optHost);
	}
	else {
		fprintf(stderr,"wrong argc count.\n");
	}
}