aboutsummaryrefslogblamecommitdiff
path: root/src/libnpass/util.c
blob: 3b5e052e835565560637ca706042910cde8bcfde (plain) (tree)
1
2
3
4
5
6
7
8
9
                     

                  
                  
                   
                         
                   
                   
 
                          



                                          
                               

                   
                
 


                                                                 
 

                                        


                                  


                                                                       




                                 




                                                       
 
 
                                                         
 
                                
              
 

                                 


                                                                                
                                                   
                                                                 

                            

                                                           
 
                                                            

 







                                 

                               
 
#include <sys/stat.h>

#include <ctype.h>
#include <errno.h>
#include <libgen.h>
#include <linux/limits.h>
#include <string.h>
#include <unistd.h>

#include "libnpass/util.h"
#include "util.h"

int r_mkdir(const char *path, mode_t mode)
{
	char path_cp[PATH_MAX];
	size_t len;
	char *p;
	int ret;

	len = strlen(path);
	if (len >= PATH_MAX)
		err_ret(-EINVAL, "%s", "Path exceeded PATH_MAX");

	strcpy(path_cp, path);
	for (p = path_cp + 1; *p; ++p) {
		if (*p == '/') {
			*p = '\0';

			ret = mkdir(path_cp, mode);
			if (ret < 0 && !(errno & EEXIST))
				err_ret(-errno, "%s", strerror(errno));

			*p = '/';
		}
	}

	ret = mkdir(path, mode);
	if (ret < 0 && !(errno & EEXIST))
		err_ret(-errno, "%s", strerror(errno));

	return 0;
}

int r_rmdir_empty(const char *prefix_path, char *rm_path)
{
	char abs_path[PATH_MAX];
	int r;

	r = strcmp(rm_path, ".");
	if (r == 0)
		return 0;

	r = snprintf(abs_path, sizeof(abs_path), "%s/%s", prefix_path, rm_path);
	if (r < 0 || (size_t)r >= sizeof(abs_path))
		err_ret(-EINVAL, "%s", "Path exceeded PATH_MAX");

	r = rmdir(abs_path);
	if (r < 0 && errno != EEXIST && errno != ENOTEMPTY)
		err_ret(-errno, "%s", strerror(errno));

	return r_rmdir_empty(prefix_path, dirname(rm_path));
}

void util_strtrim(char *s)
{
	char *rend;

	for (rend = s; *s; ++s)
		if (!isspace(*s))
			rend = s;

	if (*rend)
		rend[1] = '\0';
}