Esempio n. 1
0
void
cfg_init(void)
{
	cfg.history_len = 15;

	cfg.auto_execute = 0;
	cfg.time_format = strdup("%m/%d %H:%M");
	cfg.wrap_quick_view = 1;
	cfg.undo_levels = 100;
	cfg.sort_numbers = 0;
	cfg.follow_links = 1;
	cfg.fast_run = 0;
	cfg.confirm = CONFIRM_DELETE | CONFIRM_PERM_DELETE;
	cfg.vi_command = strdup("vim");
	cfg.vi_cmd_bg = 0;
	cfg.vi_x_command = strdup("");
	cfg.vi_x_cmd_bg = 0;
	cfg.use_trash = 1;
	cfg.use_term_multiplexer = 0;
	cfg.use_vim_help = 0;
	cfg.wild_menu = 0;
	cfg.wild_popup = 0;

	cfg.sug.flags = 0;
	cfg.sug.maxregfiles = 5;
	cfg.sug.delay = 500;

	cfg.ignore_case = 0;
	cfg.smart_case = 0;
	cfg.hl_search = 1;
	cfg.vifm_info = VINFO_MARKS | VINFO_BOOKMARKS;
	cfg.scroll_off = 0;
	cfg.gdefault = 0;
	cfg.scroll_bind = 0;
	cfg.wrap_scan = 1;
	cfg.inc_search = 0;
	cfg.selection_is_primary = 1;
	cfg.tab_switches_pane = 1;
	cfg.use_system_calls = 0;
	cfg.tab_stop = 8;
	cfg.ruler_format = strdup("%l/%S ");
	cfg.status_line = strdup("");

	cfg.lines = INT_MIN;
	cfg.columns = INT_MIN;

	cfg.dot_dirs = DD_NONROOT_PARENT;

	cfg.filter_inverted_by_default = 1;

	cfg.apropos_prg = strdup("apropos %a");
	cfg.find_prg = strdup("find %s %a -print , "
			"-type d \\( ! -readable -o ! -executable \\) -prune");
	cfg.grep_prg = strdup("grep -n -H -I -r %i %a %s");
	cfg.locate_prg = strdup("locate %a");
	cfg.delete_prg = strdup("");
	cfg.media_prg = format_str("%s/vifm-media", get_installed_data_dir());

	cfg.tail_tab_line_paths = 0;
	cfg.trunc_normal_sb_msgs = 0;
	cfg.shorten_title_paths = 1;
	cfg.short_term_mux_titles = 0;

	cfg.slow_fs_list = strdup("");

	cfg.cd_path = strdup(env_get_def("CDPATH", DEFAULT_CD_PATH));
	replace_char(cfg.cd_path, ':', ',');

	cfg.extra_padding = 1;
	cfg.side_borders_visible = 1;
	cfg.use_unicode_characters = 0;
	cfg.display_statusline = 1;

	cfg.border_filler = strdup(" ");

	cfg.set_title = term_title_restorable();

	cfg.chase_links = 0;

	cfg.timeout_len = 1000;
	cfg.min_timeout_len = 150;

	/* Fill cfg.word_chars as if it was initialized from isspace() function. */
	memset(&cfg.word_chars, 1, sizeof(cfg.word_chars));
	cfg.word_chars['\x00'] = 0; cfg.word_chars['\x09'] = 0;
	cfg.word_chars['\x0a'] = 0; cfg.word_chars['\x0b'] = 0;
	cfg.word_chars['\x0c'] = 0; cfg.word_chars['\x0d'] = 0;
	cfg.word_chars['\x20'] = 0;

	cfg.view_dir_size = VDS_SIZE;

	cfg.log_file[0] = '\0';

	cfg_set_shell(env_get_def("SHELL", DEFAULT_SHELL_CMD));
	cfg.shell_cmd_flag = strdup((curr_stats.shell_type == ST_CMD) ? "/C" : "-c");

	memset(&cfg.type_decs, '\0', sizeof(cfg.type_decs));
	cfg.type_decs[FT_DIR][DECORATION_SUFFIX][0] = '/';

	cfg.name_decs = NULL;
	cfg.name_dec_count = 0;

	cfg.fast_file_cloning = 0;
	cfg.cvoptions = 0;

	cfg.case_override = 0;
	cfg.case_ignore = 0;

	//add by sim1 ********
	cfg.prefer_vsplit = 0;
	//add by sim1 ********

	cfg.sizefmt.base = 1024;
	cfg.sizefmt.precision = 0;
	cfg.sizefmt.ieci_prefixes = 0;

	cfg.pane_tabs = 0;
	cfg.show_tab_line = STL_MULTIPLE;

	cfg.auto_ch_pos = 1;
	cfg.ch_pos_on = CHPOS_STARTUP | CHPOS_DIRMARK | CHPOS_ENTER;
}
Esempio n. 2
0
/*
 * Level name conversions
 */
string file_name_to_level_name(string file) {
	return replace_char(explode(file,'.')[0], '_', ' ');
}
Esempio n. 3
0
int main(int argn, char** args){
	if(argn!=5){
		print("use this format: ./Client name server_ip router_ip router_port\n");
		return 0;
	}
	char* client_name = args[1];
	char* client_ip=NULL;
	char* server_ip= args[2];
	char* router_port= args[4];
	char server_data [MAX_STR_SIZE];
	clear_buff(server_data,MAX_STR_SIZE);
	int ip_input_tokens_num;
	char ip_input_tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE];
	char ip_input_buffer[MAX_STR_SIZE];
	clear_buff(ip_input_buffer, MAX_STR_SIZE);
	while( read(STDINFD, ip_input_buffer, MAX_STR_SIZE) > 0 ){	
		tokenizer(ip_input_buffer, " ", &ip_input_tokens_num, ip_input_tokens);
		if(mystrcmp(ip_input_tokens[0], "Set") == 0 && mystrcmp(ip_input_tokens[1], "IP") == 0 && ip_input_tokens_num == 3){
			client_ip=ip_input_tokens[2];
			replace_char(client_ip,'\n','\0');
			break;
		}else{
			print("You should set your IP first : Set IP 115.2.2.18\n");
		}
	}
	int fd = connect_to_port(atoi(router_port));
	char input_buffer[MAX_STR_SIZE];
	clear_buff(input_buffer, MAX_STR_SIZE);
	while(read(STDINFD, input_buffer, MAX_STR_SIZE) > 0)
	{	
		int input_tokens_num;
		char input_tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE];
		replace_char(input_buffer,'\n','\0');
		char iden_buff[MAX_STR_SIZE];
		clear_buff(iden_buff, MAX_STR_SIZE);
		strcat(iden_buff, "00");//00 is for client
		//parsing input_buffer
		tokenizer(input_buffer," ", &input_tokens_num, input_tokens);
		
		char frame[MAX_STR_SIZE];
		clear_buff(frame, MAX_STR_SIZE);
		char data[MAX_STR_SIZE];
		clear_buff(data, MAX_STR_SIZE);
		
		//send command for server
		if( (mystrcmp(input_tokens[0], "DC") < 0) && (mystrcmp(input_tokens[0], "Logout") < 0) )
		{
			if( strcmp(input_tokens[0],"Send")==0 && strcmp(input_tokens[1],"message")==0  && input_tokens_num==3){
				strcat(data,"Sent message: ");
				strcat(data,input_tokens[2]);
			} else if(strcmp(input_tokens[0],"Send")==0 && strcmp(input_tokens[1],"file")==0 && input_tokens_num==3){
				if(!file_exist(input_tokens[2])){
					printf("file %s doesn't exist! You should create this file near ./Client 's directory\n", input_tokens[2]);
					continue;
				}
				char file_content[MAX_STR_SIZE];
				clear_buff(file_content,MAX_STR_SIZE);
				read_entire_file(input_tokens[2],file_content);
				replace_char(file_content,'\n','^');
				strcat(data,"Sent file ");
				strcat(data,input_tokens[2]);
				strcat(data," contain:\n");
				strcat(data,file_content);
			}
			else
				strcat(data,input_buffer);

			framing(iden_buff,"0",client_ip,client_name,data,"cccc","cc",frame);
			printf("sent frame is: %s\n",frame );
			int bytes_written = write(fd, frame, strlength(frame));
			if(bytes_written < 0)
				write(STDOUTFD,"Error on writing\n", sizeof("Error on writing\n"));

			//get response from server
			char res_status[MAX_STR_SIZE];
			clear_buff(res_status, MAX_STR_SIZE);
			int read_status = read(fd, res_status, MAX_STR_SIZE);
			//show the response to client
			printf("status of result of first reading ...\n");
			write(STDOUTFD, res_status, strlength(res_status));
			printf("\n");

			char res_buff[MAX_STR_SIZE];
			clear_buff(res_buff, MAX_STR_SIZE);
			read_status = read(fd, res_buff, MAX_STR_SIZE);
			process_client_command(res_buff,server_data );
			printf("result is:\n%s\n",res_buff );
			int input_tokens_num;
			char input_tokens[MAX_ARRAY_SIZE][MAX_STR_SIZE];
			tokenizer(res_buff, "&", &input_tokens_num, input_tokens);
			//show the response to client
			write(STDOUTFD, input_tokens[5], strlength(input_tokens[5]));
			printf("\n");
		}
		else if(mystrcmp(input_tokens[0], "DC") == 0)
		{
			int bytes_written = write(fd, "DC", strlength("DC"));
			if(bytes_written < 0)
				write(STDOUTFD,"Error on writing\n", sizeof("Error on writing\n"));
			break;
		}
		else if(mystrcmp(input_tokens[0], "Logout") == 0)
		{
			int bytes_written = write(fd,"DC", strlength("DC"));
			if(bytes_written < 0)
				write(STDOUTFD,"Error on writing\n", sizeof("Error on writing\n"));
			close(fd);
			return 0;
		}
	}
	close(fd);
	return 0;
}
Esempio n. 4
0
char* replace_spaces(char* s)
{
    return replace_char(s, ' ', "%20");
}
Esempio n. 5
0
/* Remove the task's controller directory after moving out the
   shepherd and killing anything left.  */
bool
remove_shepherd_cpuset(u_long32 job, u_long32 task, pid_t pid)
{
   char dir[SGE_PATH_MAX], taskfile[SGE_PATH_MAX], spid[PID_BSIZE];
   FILE *fp;
   bool rogue = false;

   DENTER(TOP_LAYER, "remove_shepherd_cpuset");
   snprintf(dir, sizeof dir, "%s/"sge_u32"."sge_u32"/"pid_t_fmt,
            cgroup_dir(cg_cpuset), job, task, pid);
   build_path(taskfile, dir, "tasks");
   /* We should have an empty task list.  If we can't remove it, kill
      anything there.  Arguably this should be repeated in case of a
      race against things spawning if we don't have the freezer cgroup.  */
   errno = 0;
   if (rmdir(dir) == 0) DRETURN(true);
   /* EBUSY means it still has tasks.  */
   if (errno != EBUSY) {
      ERROR((SGE_EVENT, MSG_FILE_RMDIRFAILED_SS, dir, strerror(errno)));
      DRETURN(false);
   }
   if (!(fp = fopen(taskfile, "r"))) {
      WARNING((SGE_EVENT, MSG_FILE_NOOPEN_SS, taskfile, strerror(errno)));
      DRETURN(false);
   }
   while (fgets(spid, sizeof spid, fp)) {
      char buf[MAX_STRING_SIZE], file[SGE_PATH_MAX], *v, *cmd;
      pid_t tgid;
      size_t l;

      replace_char(spid, strlen(spid), '\n', '\0');

      /* Move the task away to avoid waiting for it to die.  */
      /* Fixme:  Keep the cpusetdir tasks open and just write to that.  */
      reparent_proc(spid, cgroup_dir(cg_cpuset));

      /* Kill rogue processes, avoiding the shepherd.  (Shepherd needs
         to be killed exactly once, otherwise sge_reap_children_execd
         is called multiple times.)  Only consider entries in the task
         list that are processes (Tgid == Pid), not threads; this
         copes with old-style cpusets, lacking cgroup.procs.  */
      snprintf(file, sizeof file, "/proc/%s/status", spid);
      v = file_getvalue(buf, MAX_STRING_SIZE, file, "Tgid:");
      if (! v) continue;
      tgid = atoi(v);
      if (strcmp(v, spid)       /* process */
          && (tgid != pid)) {   /* not shepherd */
          if (!rogue)
             WARNING((SGE_EVENT, "rogue process(es) found for task "
    		  sge_u32"."sge_u32, job, task));
          rogue = true;

          /* Extract and log process name */
          snprintf(file, sizeof file, "/proc/%s/cmdline", spid);
          errno = 0;
          l = sizeof buf;
          cmd = dev_file2string(file, buf, &l);
          if (l)
             INFO((SGE_EVENT, "rogue: "SFN2, replace_char(cmd, l, '\0', ' ')));

          sge_switch2start_user();
          kill(tgid, SIGKILL);
          sge_switch2admin_user();
      }
   }
   fclose(fp);
   errno = 0;
   if (rmdir(dir) == 0) DRETURN(true);
   ERROR((SGE_EVENT, MSG_FILE_RMDIRFAILED_SS, dir, strerror(errno)));
   DRETURN(false);
}
Esempio n. 6
0
void servicing_index_t::ensure_redirections()
{
    if (m_parsed)
    {
        return;
    }

    pal::ifstream_t fstream(m_index_file);
    if (!fstream.good())
    {
        return;
    }

    pal::stringstream_t sstream;
    std::string line;
    while (std::getline(fstream, line))
    {
        pal::string_t str;
        pal::to_palstring(line.c_str(), &str);

        // Can interpret line as "package"?
        pal::string_t prefix = _X("package|");
        if (str.find(prefix) != 0)
        {
            continue;
        }

        pal::string_t name, version, relative;
        pal::string_t* tokens[] = { &name, &version, &relative };
        pal::string_t delim[] = { pal::string_t(_X("|")), pal::string_t(_X("|")), pal::string_t(_X("=")) };

        bool bad_line = false;

        size_t from = prefix.length();
        for (size_t cur = 0; cur < (sizeof(delim) / sizeof(delim[0])); ++cur)
        {
            size_t pos = str.find(delim[cur], from);
            if (pos == pal::string_t::npos)
            {
                bad_line = true;
                break;
            }

            tokens[cur]->assign(str.substr(from, pos - from));
            from = pos + 1;
        }

        if (bad_line)
        {
            trace::error(_X("Invalid line in servicing index. Skipping..."));
            continue;
        }

        // Save redirection for this package.
        sstream.str(_X(""));
        sstream << name << _X("|") << version << _X("|") << relative;

        if (trace::is_enabled())
        {
            auto stream_str = sstream.str();
            trace::verbose(_X("Adding servicing entry %s => %s"), stream_str.c_str(), str.substr(from).c_str());
        }

        // Store just the filename.
        pal::string_t redir = str.substr(from);
        if (_X('/') != DIR_SEPARATOR)
        {
            replace_char(&redir, _X('/'), DIR_SEPARATOR);
        }
        m_redirections.emplace(sstream.str(), redir);
    }

    m_parsed = true;
}
Esempio n. 7
0
// Checking and replacing in cache 
int check_cache(char *proxy[], char *entry, int sock, struct addrinfo *servinfo) {
    int i,j,n,sock_req;
    char *temp,*upd,*host,*path,buf[MAXDATASIZE],hbuf[MAXDATASIZE];
    char *e = "Expires: ";
    char *l = "Last-Modified: ";
    //Obtaining Current directory
    if (getcwd(cwd, sizeof(cwd)) == NULL) {
	perror("server: getcwd() error\n");
	return 0;
    }
    struct tm exp, up, *now_gm;
    time_t now;
    FILE *fp;
    for(i=0; i<CACHE_SIZE; i++) {
	if(proxy[i] != NULL) {
		//Finding in the list, and replacing in LRU fashion if found
		if(!strcmp(proxy[i],entry)) {
			sprintf(cwd,"%s/%s",cwd,entry);
                        fp=fopen(cwd,"r");
			n = fread(buf, sizeof(char), sizeof(buf), fp);
			// Checking Expires time
			if((temp = strstr(buf,e)) != NULL) {
				exp=strToTm(temp+strlen(e));
				printf("server: Expires: %s", asctime(&exp));
				now = time(NULL);				
				now_gm = gmtime(&now);
				printf("server: Current: %s", asctime(now_gm));
			}
			// If not expired, then send from proxy cache
			if(difftime(timegm(&exp),now)>0 && (temp != NULL)) {
				send_cache:
					rewind(fp);
				        while(!feof(fp)) {
				                n = fread(buf, sizeof(char), sizeof(buf), fp);
				                if(!(n<=0))
				                        send(sock,buf,n,0);
				        }
				        fclose(fp);
					for(j=i; j>0; j--) {
						strcpy(proxy[j],proxy[j-1]);
					}	
					strcpy(proxy[0],entry);
					printf("server: Obtained from proxy cache \n\n");
					return 1;
			}
			// If expired in proxy cache, check if modified
			else {
				// Checking Last Updated time
				strcpy(hbuf,entry);
				replace_char(hbuf,'_','/');
				host = strtok((char*)hbuf,"/");
				path = strtok(NULL,"\n");
				// implementing a HEAD request
				sprintf(buf,"HEAD /%s HTTP/1.0\r\nHost: %s\r\n\r\n",path,host);
				sock_req = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
				connect(sock_req, servinfo->ai_addr, servinfo->ai_addrlen);
				
				n = send(sock_req,buf,sizeof(buf),0);
				if(n<0)
					perror("server: Error sending to the socket\n");
				
				n=recv(sock_req,buf,sizeof(buf),0);
				if((upd = strstr(buf,l)) != NULL) {
					up=strToTm(upd+strlen(l));
					printf("server: Last-Modified: %s", asctime(&up));
				}
				close(sock_req);
				//Checking if modified after expiry
				if(difftime(timegm(&exp),timegm(&up))>0 && temp!=NULL && upd!=NULL) 
					goto send_cache;
				
				// Expired and modified after that, so re-obtain from server
				remove(cwd);
				fclose(fp);
				for(j=i; j<CACHE_SIZE-1; j++) {
					if(proxy[j+1] != NULL) 
						strcpy(proxy[j],proxy[j+1]);
					else
						break;
				}
				proxy[j]=NULL;
				return 0;
			}
		}
	}
    }
    return 0;
}
Esempio n. 8
0
File: path.c Progetto: jubalh/vifm
void
to_back_slash(char path[])
{
	replace_char(path, '/', '\\');
}
Esempio n. 9
0
void deps_json_t::reconcile_libraries_with_targets(
    const json_value& json,
    const std::function<bool(const pal::string_t&)>& library_exists_fn,
    const std::function<const std::vector<pal::string_t>&(const pal::string_t&, int, bool*)>& get_rel_paths_by_asset_type_fn)
{
    const auto& libraries = json.at(_X("libraries")).as_object();
    for (const auto& library : libraries)
    {
        trace::info(_X("Reconciling library %s"), library.first.c_str());

        if (pal::to_lower(library.second.at(_X("type")).as_string()) != _X("package"))
        {
            trace::info(_X("Library %s is not a package"), library.first.c_str());
            continue;
        }
        if (!library_exists_fn(library.first))
        {
            trace::info(_X("Library %s does not exist"), library.first.c_str());
            continue;
        }

        const auto& properties = library.second.as_object();

        const pal::string_t& hash = properties.at(_X("sha512")).as_string();
        bool serviceable = properties.at(_X("serviceable")).as_bool();

        for (int i = 0; i < deps_entry_t::s_known_asset_types.size(); ++i)
        {
            bool rid_specific = false;
            for (const auto& rel_path : get_rel_paths_by_asset_type_fn(library.first, i, &rid_specific))
            {
                bool ni_dll = false;
                auto asset_name = get_filename_without_ext(rel_path);
                if (ends_with(asset_name, _X(".ni"), false))
                {
                    ni_dll = true;
                    asset_name = strip_file_ext(asset_name);
                }

                deps_entry_t entry;
                size_t pos = library.first.find(_X("/"));
                entry.library_name = library.first.substr(0, pos);
                entry.library_version = library.first.substr(pos + 1);
                entry.library_type = _X("package");
                entry.library_hash = hash;
                entry.asset_name = asset_name;
                entry.asset_type = (deps_entry_t::asset_types) i;
                entry.relative_path = rel_path;
                entry.is_serviceable = serviceable;
                entry.is_rid_specific = rid_specific;

                // TODO: Deps file does not follow spec. It uses '\\', should use '/'
                replace_char(&entry.relative_path, _X('\\'), _X('/'));

                m_deps_entries[i].push_back(entry);

                if (ni_dll)
                {
                    m_ni_entries[entry.asset_name] = m_deps_entries
                        [deps_entry_t::asset_types::runtime].size() - 1;
                }

                trace::info(_X("Added %s %s deps entry [%d] [%s, %s, %s]"), deps_entry_t::s_known_asset_types[i], entry.asset_name.c_str(), m_deps_entries[i].size() - 1, entry.library_name.c_str(), entry.library_version.c_str(), entry.relative_path.c_str());
                
            }
        }
    }
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
    int sockfd, sockmax, sock_req, new_fd;  // listen on sock_fd, new connection on new_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    FILE *fp;
    int yes=1;
    char s[INET6_ADDRSTRLEN];
    int rv,i,n,numbytes;
    char buf[MAXDATASIZE], url[MAXDATASIZE], tmp[MAXDATASIZE], prot[10], http[MAXDATASIZE],path[MAXDATASIZE];
    char *proxy_cache[CACHE_SIZE]; // Store entries in LRU fashion

    for(i=0; i<CACHE_SIZE; i++) {
	proxy_cache[i]=NULL;
    }
    //Checking specification of command line options
    if (argc != 3) {
        fprintf(stderr,"usage: server server_ip server_port \n");
        exit(1);
    }

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }

        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
                sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    if (p == NULL)  {
        fprintf(stderr, "server: failed to bind\n");
        return 2;
    }

    freeaddrinfo(servinfo); // all done with this structure

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    // FD_SET variables for select() 
    fd_set master,read_fds;

    // clear the master and temp sets
    FD_ZERO(&master);    
    FD_ZERO(&read_fds);

    // add the socket descriptor to the master set
    FD_SET(sockfd, &master);

    // keep track of the largest socket descriptor to use with select()
    sockmax = sockfd; // so far, it's this one

    printf("server: waiting for connections...\n");

    while(1) 
    {  // main accept() loop
	read_fds = master;
	if(select(sockmax+1,&read_fds,NULL,NULL,NULL) == -1) {
	        printf("Error with select \n");
        	perror("select");
	        exit(1);
    	}

	//Looping through all incoming socket connections 
	for(i=0; i<=sockmax; i++) {
		if(FD_ISSET(i, &read_fds)) {
			if(i == sockfd) {
				//Accept the new connection
				sin_size = sizeof their_addr;
				new_fd =accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
				if(new_fd == -1) {
					perror("accept");
					continue;
				}
				else {
					printf("server: Adding to master %d\n",new_fd);
					FD_SET(new_fd, &master); //Adding to master set
					if(new_fd > sockmax) {
						sockmax = new_fd;
					}

				inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s);
				printf("server: %d got connection from %s\n", sockfd,s);	
				}
           		}
			
			else {
		            	// handle data from a client
		            	if ((numbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
		                        // got error or connection closed by client
		                	if (numbytes == 0) {
					        // connection closed
				        	printf("server: socket %d hung up! Nothing received\n", i);
		                	} 
					else {
						printf("server: some error receiving \n");
				            	perror("recv");
		                	}

		                	close(i); // bye!
		                	FD_CLR(i, &master); // remove from master set
		            	} 
				else {
				        // we got some data from a client
					buf[numbytes] = '\0';
					sscanf(buf,"%s %s %s\r\nHost: %s\r\n\r\n",http,path,prot,url);			
					printf("server: %s %s %s %s\n",http,path,prot,url);
					if(((strncmp(http,"GET",3)==0))&&(strncmp(prot,HTTP,8)==0)) {
							
											
						if ((getaddrinfo(url, "http", &hints, &servinfo)) != 0) {	
							goto badurl;
						}					
		
						printf("server: HostPath = %s%s\n",url,path);
						   
						sock_req = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
						new_fd=connect(sock_req, servinfo->ai_addr, servinfo->ai_addrlen);
						inet_ntop(servinfo->ai_family, get_in_addr(servinfo->ai_addr), s, sizeof s);
						printf("server: Connected to %s IP - %s\n",url,s);
						if(new_fd<0)
							perror("server: Error in connecting to remote server");
											
						strcpy(tmp,url);
						replace_char(strcat(tmp,path),'/','_');
						
						//Checking the cache in the directory
						if(check_cache(proxy_cache,tmp,i,servinfo)) {
							close(i); // bye!
		                                        FD_CLR(i, &master); // remove from master set
							continue;
						}

						//Obtaining Current directory
						if (getcwd(cwd, sizeof(cwd)) == NULL) {
	               			        	perror("server: getcwd() error\n");
							continue;
						}

						//Appending the filename to the path
                                                replace_char(strcat(url,path),'/','_');
						
                                                sprintf(cwd,"%s/%s",cwd,url);

						n=send(sock_req,buf,strlen(buf),0);
						if(n<0)
							perror("Error writing to socket");
						else{
							do
							{
								fp = fopen (cwd, "a+");
								if (fp == NULL) {
									printf ("server: file not found (%s)\n", cwd);
								}

								bzero((char*)buf,sizeof(buf));
								n=recv(sock_req,buf,sizeof(buf),0);
								fwrite(buf, n, sizeof(char), fp);
								fclose(fp);
								if(!(n<=0))
									send(i,buf,n,0);

							}while(n>0);
						}
						add_entry(proxy_cache,url);
						printf("\n");
					}
					else
					{
						badurl:
						printf("server: bad url\n");
						send(i,"HTTP/1.0 400 bad request\nOnly HTTP requests allowed \r\n\r\n",100,0);
					}
					close(i); // bye!
                                        FD_CLR(i, &master); // remove from master set
				}
			}
		}
	}
    }	
    return 0;
}
Esempio n. 11
0
// Read from filename all information available
void filename_to_field( const char *pFileName, char *szTitle, char *szArtist, char *szAlbum, char *szYear ){

	int i, len, last = strlen(pFileNameFormat) - 1;
	char Buffer[256];
	bool stop = FALSE;
	char *lastC;										// end field pointer, point to the last char of the string to copy
	char *firstC = Buffer;								// start field pointer, point to the first char of the string to copy
	
	strcpy( Buffer, pFileName );						// copy the filename into an internal buffer
	replace_char( Buffer );								// replace all provided characters with space
	
	for( i = 0; i < last && !stop; i++ ){

		// pFileNameFormat[last] is the field separator
		if( (lastC = index( firstC, pFileNameFormat[last] )) == NULL ) {
		
			lastC = &firstC[strlen(firstC)-4];			// get the end field pointer
			stop = TRUE;									// force to be the last loop
		}
		
		len = (lastC - firstC) / sizeof(char);			// get the length of the field found
		while( firstC[0] == 0x20 ){						// delete all spaces at the beginning of the string
			
			firstC ++;
			len--;
		}

		// Una volta che ho controllato il tutto posso fare la copia
		switch( pFileNameFormat[i] ){
				
				case 'A':
					strncpy( szArtist, firstC, len>=31?30:len );
					if( szArtist[len-1] == 0x20 )					// remove, if present, a space at the end of the string
						szArtist[len-1] = '\0';
					else
						szArtist[len] = '\0';
					break;
				case 'M':
					strncpy( szAlbum,  firstC, len>=31?30:len );
					if( szAlbum[len-1] == 0x20 )					// remove, if present, a space at the end of the string
						szAlbum[len-1] = '\0';
					else
						szAlbum[len] = '\0';
					break;
				case 'T':
					strncpy( szTitle,  firstC, len>=31?30:len );
					if( szTitle[len-1] == 0x20 )					// remove, if present, a space at the end of the string
						szTitle[len-1] = '\0';
					else
						szTitle[len] = '\0';
					break;
				case 'Y':
					strncpy( szYear,   firstC, len>=5?4:len );
					szYear[5] = '\0';
					break;
				default:
					CloseDBConnection();
					print_error( BAD_FORMAT );
		}
		
		// set the pointer to first position to actual last + 1
		firstC = lastC + 1;
	}
}
Esempio n. 12
0
gchar *iconv_convert(const gchar *icode, const gchar *ocode, const gchar *orig){
	iconv_t cd;
	int r = 0;
	int buflen;
	size_t isize;
	size_t osize;
	guchar *outbuf;
	guchar *result;
	guchar *inbuf;
	size_t origsize;

	g_assert(icode != NULL);
	g_assert(ocode != NULL);
	g_assert(orig != NULL);

	//LOG(LOG_DEBUG, "IN : iconv_convert(%s, %s, %s)", icode, ocode, orig);

	if(strlen(orig) == 0){
		result = malloc(1);
		result[0] = '\0';
		LOG(LOG_DEBUG, "OUT : iconv_convert() OUT1");
		return(result);
	}

	if(strcasecmp(icode, ocode) == 0){
		LOG(LOG_DEBUG, "OUT : iconv_convert() OUT2");
		return(g_strdup(orig));
	}

	cd = iconv_open( ocode, icode );
	if( (int)cd == -1 ) {
		LOG(LOG_DEBUG, "OUT : iconv_convert() OUT3");
		return(NULL);
	}

	//hex_dump(inbuf);

	inbuf = (gchar *)orig;
		
	origsize = isize = strlen(inbuf);
	osize = buflen = isize * 2;
	result = outbuf = malloc(osize);
	memset(result, 0x00, osize);


	while(1){
#ifdef __FreeBSD__
		r = iconv(cd, (const char **)&inbuf, &isize, &outbuf, &osize);
#else
		r = iconv(cd, (char **)&inbuf, &isize, (char **)&outbuf, &osize);
#endif

#ifdef __WIN32__
		if((r == -1) && (errno == EILSEQ) && (strcasecmp(icode, "utf-8") == 0)){
			*outbuf = 0x5c;
			outbuf ++;

			osize -= 1;
			isize -= 1;
			
			inbuf += 1;
			continue;
		} 
#endif
		// Replace undefined characters
		if((r == -1) && (errno == EILSEQ)) {
			LOG(LOG_INFO, "Couldn't convert %02x %02x. Skipped.", (guchar)(*inbuf), (guchar)(*(inbuf+1)));
			replace_char(icode, ocode, &inbuf, &outbuf, &isize, &osize);
			continue;
		}
		break;
	}

	iconv_close(cd);

	if(r != 0){
		int i;

		LOG(LOG_INFO, "iconv failed at location %d (%s -> %s)", origsize - isize, icode, ocode);
		LOG(LOG_INFO, "original size %d", origsize);


		for(i=0; i < 10 ; i ++) {
			if(inbuf[i] == '\0')
				break;
			LOG(LOG_INFO, "[%02x](%c) ", (unsigned char)inbuf[i], (unsigned char)inbuf[i]);
		}
		LOG(LOG_CRITICAL, "iconv : %s", strerror(errno));
		result[0] = '\0';

		LOG(LOG_DEBUG, "OUT : iconv_convert() OUT4");
		return(result);
	}

	//LOG(LOG_DEBUG, "OUT : iconv_convert()");

	return(result);
}
Esempio n. 13
0
void test_deserialise()
{
    char *buf, *buf2, *tmp;
    const char *types = NULL, *path;
    lo_arg **argv = NULL;
    size_t len, size;
    char data[256];
    int result = 0;

    lo_blob btest = lo_blob_new(sizeof(testdata), testdata);
    uint8_t midi_data[4] = {0xff, 0xf7, 0xAA, 0x00};
    lo_timetag tt = {0x1, 0x80000000};
    lo_blob b = NULL;

    // build a message
    lo_message msg = lo_message_new();
    TEST(0 == lo_message_get_argc(msg));
    lo_message_add_float(msg, 0.12345678f);             // 0  f
    lo_message_add_int32(msg, 123);                     // 1  i
    lo_message_add_string(msg, "123");                  // 2  s
    lo_message_add_blob(msg, btest);                    // 3  b
    lo_message_add_midi(msg, midi_data);                // 4  m
    lo_message_add_int64(msg, 0x0123456789abcdefULL);   // 5  h
    lo_message_add_timetag(msg, tt);                    // 6  t
    lo_message_add_double(msg, 0.9999);                 // 7  d
    lo_message_add_symbol(msg, "sym");                  // 8  S
    lo_message_add_char(msg, 'X');                      // 9  c
    lo_message_add_char(msg, 'Y');                      // 10 c
    lo_message_add_true(msg);                           // 11 T
    lo_message_add_false(msg);                          // 12 F
    lo_message_add_nil(msg);                            // 13 N
    lo_message_add_infinitum(msg);                      // 14 I

    // test types, args
    TEST(15 == lo_message_get_argc(msg));
    types = lo_message_get_types(msg);
    TEST(NULL != types);
    argv = lo_message_get_argv(msg);
    TEST(NULL != argv);
    TEST('f' == types[0] && fabs(argv[0]->f - 0.12345678f) < FLT_EPSILON);
    TEST('i' == types[1] && 123 == argv[1]->i);
    TEST('s' == types[2] && !strcmp(&argv[2]->s, "123"));
    TEST('b' == types[3]);
    b = (lo_blob)argv[3];
    TEST(lo_blob_datasize(b) == sizeof(testdata));
    TEST(12 == lo_blobsize(b));
    TEST(!memcmp(lo_blob_dataptr(b), &testdata, sizeof(testdata)));
    TEST('m' == types[4]  && !memcmp(&argv[4]->m, midi_data, 4));
    TEST('h' == types[5]  && 0x0123456789abcdefULL == argv[5]->h);
    TEST('t' == types[6]  && 1 == argv[6]->t.sec && 0x80000000 == argv[6]->t.frac);
    TEST('d' == types[7]  && fabs(argv[7]->d - 0.9999) < FLT_EPSILON);
    TEST('S' == types[8]  && !strcmp(&argv[8]->s, "sym"));
    TEST('c' == types[9]  && 'X' == argv[9]->c);
    TEST('c' == types[10] && 'Y' == argv[10]->c);
    TEST('T' == types[11] && NULL == argv[11]);
    TEST('F' == types[12] && NULL == argv[12]);
    TEST('N' == types[13] && NULL == argv[13]);
    TEST('I' == types[14] && NULL == argv[14]);

    // serialise it
    len = lo_message_length(msg, "/foo");
    printf("serialise message_length=%d\n", (int)len);
    buf = calloc(len, sizeof(char));
    size = 0;
    tmp = lo_message_serialise(msg, "/foo", buf, &size);
    TEST(tmp == buf && size == len && 92 == len);
    lo_message_free(msg);

    // deserialise it
    printf("deserialise\n");
    path = lo_get_path(buf, len);
    TEST(NULL != path && !strcmp(path, "/foo"));
    msg = lo_message_deserialise(buf, size, NULL);
    TEST(NULL != msg);

    // repeat same test as above
    TEST(15 == lo_message_get_argc(msg));
    types = lo_message_get_types(msg);
    TEST(NULL != types);
    argv = lo_message_get_argv(msg);
    TEST(NULL != argv);
    TEST('f' == types[0] && fabs(argv[0]->f - 0.12345678f) < FLT_EPSILON);
    TEST('i' == types[1] && 123 == argv[1]->i);
    TEST('s' == types[2] && !strcmp(&argv[2]->s, "123"));
    TEST('b' == types[3]);
    b = (lo_blob)argv[3];
    TEST(lo_blob_datasize(b) == sizeof(testdata));
    TEST(12 == lo_blobsize(b));
    TEST(!memcmp(lo_blob_dataptr(b), &testdata, sizeof(testdata)));
    TEST('m' == types[4]  && !memcmp(&argv[4]->m, midi_data, 4));
    TEST('h' == types[5]  && 0x0123456789abcdefULL == argv[5]->h);
    TEST('t' == types[6]  && 1 == argv[6]->t.sec && 0x80000000 == argv[6]->t.frac);
    TEST('d' == types[7]  && fabs(argv[7]->d - 0.9999) < FLT_EPSILON);
    TEST('S' == types[8]  && !strcmp(&argv[8]->s, "sym"));
    TEST('c' == types[9]  && 'X' == argv[9]->c);
    TEST('c' == types[10] && 'Y' == argv[10]->c);
    TEST('T' == types[11] && NULL == argv[11]);
    TEST('F' == types[12] && NULL == argv[12]);
    TEST('N' == types[13] && NULL == argv[13]);
    TEST('I' == types[14] && NULL == argv[14]);

    // serialise it again, compare
    len = lo_message_length(msg, "/foo");
    printf("serialise message_length=%d\n", (int)len);
    buf2 = calloc(len, sizeof(char));
    size = 0;
    tmp = lo_message_serialise(msg, "/foo", buf2, &size);
    TEST(tmp == buf2 && size == len && 92 == len);
    TEST(!memcmp(buf, buf2, len));
    lo_message_free(msg);

    lo_blob_free(btest);
    free(buf);
    free(buf2);

    // deserialise failure tests with invalid message data

    msg = lo_message_deserialise(data, 0, &result); // 0 size
    TEST(NULL == msg && LO_ESIZE == result);

    snprintf(data, 256, "%s", "/foo"); // unterminated path string
    msg = lo_message_deserialise(data, 4, &result);
    TEST(NULL == msg && LO_EINVALIDPATH == result);

    snprintf(data, 256, "%s", "/f_o"); // non-0 in pad area
    msg = lo_message_deserialise(data, 4, &result);
    TEST(NULL == msg && LO_EINVALIDPATH == result);

    snprintf(data, 256, "%s", "/t__"); // types missing
    replace_char(data, 4, '_', '\0');
    msg = lo_message_deserialise(data, 4, &result);
    TEST(NULL == msg && LO_ENOTYPE == result);

    snprintf(data, 256, "%s%s", "/t__", "____"); // types empty
    replace_char(data, 8, '_', '\0');
    msg = lo_message_deserialise(data, 8, &result);
    TEST(NULL == msg && LO_EBADTYPE == result);

    snprintf(data, 256, "%s%s", "/t__", ",f_"); // short message
    replace_char(data, 7, '_', '\0');
    msg = lo_message_deserialise(data, 7, &result);
    TEST(NULL == msg && LO_EINVALIDTYPE == result);

    snprintf(data, 256, "%s%s", "/t__", "ifi_"); // types missing comma
    replace_char(data, 8, '_', '\0');
    msg = lo_message_deserialise(data, 8, &result);
    TEST(NULL == msg && LO_EBADTYPE == result);

    snprintf(data, 256, "%s%s", "/t__", ",ifi"); // types unterminated
    replace_char(data, 8, '_', '\0');
    msg = lo_message_deserialise(data, 8, &result);
    TEST(NULL == msg && LO_EINVALIDTYPE == result);

    snprintf(data, 256, "%s%s", "/t__", ",ii_"); // not enough arg data
    replace_char(data, 8, '_', '\0');
    msg = lo_message_deserialise(data, 12, &result);
    TEST(NULL == msg && LO_EINVALIDARG == result);

    snprintf(data, 256, "%s%s", "/t__", ",ii_"); // not enough arg data again
    replace_char(data, 8, '_', '\0');
    msg = lo_message_deserialise(data, 15, &result);
    TEST(NULL == msg && LO_EINVALIDARG == result);

    snprintf(data, 256, "%s%s", "/t__", ",f__"); // too much arg data
    replace_char(data, 8, '_', '\0');
    msg = lo_message_deserialise(data, 16, &result);
    TEST(NULL == msg && LO_ESIZE == result);

    snprintf(data, 256, "%s%s", "/t__", ",bs_"); // blob longer than msg length
    replace_char(data, 8, '_', '\0');
    *(uint32_t *)(data + 8) = lo_htoo32((uint32_t)99999);
    msg = lo_message_deserialise(data, 256, &result);
    TEST(NULL == msg && LO_EINVALIDARG == result);
}
Esempio n. 14
0
string level_name_to_file_name(string name) {
	return replace_char(to_lower(name.append(".lev")), ' ', '_');
}
Esempio n. 15
0
/**
 *	This function takes a string and its length and replaces the special characters
 *	that it contains (new line, tabulator) and replaces them by escape sequences;
 */
int replace_spec_chars(char* string, int str_len) {
	replace_char('\n',"#012",string,str_len,4);
	replace_char('\t',"#011",string,str_len,4);
	return 0;
}
Esempio n. 16
0
File: path.c Progetto: jubalh/vifm
void
to_forward_slash(char path[])
{
	replace_char(path, '\\', '/');
}
Esempio n. 17
0
/* Draws single menu item at position specified by line argument.  Non-zero
 * clear argument suppresses drawing current items in different color. */
static void
draw_menu_item(menu_state_t *ms, int pos, int line, int clear)
{
	menu_data_t *const m = ms->d;
	int i;
	int off;
	char *item_tail;
	const int width = (curr_stats.load_stage == 0) ? 100 : getmaxx(menu_win) - 2;

	/* Calculate color for the line. */
	int attrs;
	col_attr_t col = cfg.cs.color[WIN_COLOR];
	if(cfg.hl_search && ms->search_highlight &&
			ms->matches != NULL && ms->matches[pos][0] >= 0)
	{
		cs_mix_colors(&col, &cfg.cs.color[SELECTED_COLOR]);
	}
	if(!clear && pos == m->pos)
	{
		cs_mix_colors(&col, &cfg.cs.color[CURR_LINE_COLOR]);
	}
	attrs = COLOR_PAIR(colmgr_get_pair(col.fg, col.bg)) | col.attr;

	/* Calculate offset of m->hor_pos's character in item text. */
	off = 0;
	i = m->hor_pos;
	while(i-- > 0 && m->items[pos][off] != '\0')
	{
		off += utf8_chrw(m->items[pos] + off);
	}

	item_tail = strdup(m->items[pos] + off);
	replace_char(item_tail, '\t', ' ');

	wattron(menu_win, attrs);

	/* Clear the area. */
	checked_wmove(menu_win, line, 1);
	if(curr_stats.load_stage != 0)
	{
		wprintw(menu_win, "%*s", width, "");
	}

	/* Draw visible part of item. */
	checked_wmove(menu_win, line, 2);
	if(utf8_strsw(item_tail) > (size_t)(width - 2))
	{
		void *p;
		const size_t len = utf8_nstrsnlen(item_tail, width - 3 - 2 + 1);
		memset(item_tail + len, ' ', strlen(item_tail) - len);
		p = realloc(item_tail, len + 4);
		if(p != NULL)
		{
			item_tail = p;
			strcpy(item_tail + len - 1, "...");
		}
		wprint(menu_win, item_tail);
	}
	else
	{
		const size_t len = utf8_nstrsnlen(item_tail, width - 2 + 1);
		item_tail[len] = '\0';
		wprint(menu_win, item_tail);
	}

	wattroff(menu_win, attrs);

	if(ms->search_highlight && ms->matches != NULL && ms->matches[pos][0] >= 0)
	{
		draw_search_match(item_tail, ms->matches[pos][0] - m->hor_pos,
				ms->matches[pos][1] - m->hor_pos, line, width, attrs);
	}

	free(item_tail);
}
Esempio n. 18
0
/**
 * @brief Runs diff-engine.
 */
BOOL CDiffWrapper::RunFileDiff()
{
	String filepath1(m_s1File);
	String filepath2(m_s2File);
	replace_char(&*filepath1.begin(), '/', '\\');
	replace_char(&*filepath2.begin(), '/', '\\');

	BOOL bRet = TRUE;
	String strFile1Temp(filepath1);
	String strFile2Temp(filepath2);
	
	m_options.SetToDiffUtils();

	if (m_bUseDiffList)
		m_nDiffs = m_pDiffList->GetSize();

	if (m_bPluginsEnabled)
	{
		// Do the preprocessing now, overwrite the temp files
		// NOTE: FileTransform_UCS2ToUTF8() may create new temp
		// files and return new names, those created temp files
		// are deleted in end of function.
		if (m_infoPrediffer->bToBeScanned)
		{
			// this can only fail if the data can not be saved back (no more
			// place on disk ???) What to do then ??
			FileTransform_Prediffing(strFile1Temp, m_sToFindPrediffer.c_str(), m_infoPrediffer,
				m_bPathsAreTemp);
		}
		else
		{
			// This can fail if the prediffer has a problem
			if (FileTransform_Prediffing(strFile1Temp, *m_infoPrediffer,
				m_bPathsAreTemp) == FALSE)
			{
				// display a message box
				CString sError;
				LangFormatString2(sError, IDS_PREDIFFER_ERROR, strFile1Temp.c_str(),
					m_infoPrediffer->pluginName.c_str());
				AfxMessageBox(sError, MB_OK | MB_ICONSTOP);
				// don't use any more this prediffer
				m_infoPrediffer->bToBeScanned = FALSE;
				m_infoPrediffer->pluginName.erase();
			}
		}

		// We use the same plugin for both files, so it must be defined before
		// second file
		ASSERT(m_infoPrediffer->bToBeScanned == FALSE);
		if (FileTransform_Prediffing(strFile2Temp, *m_infoPrediffer,
			m_bPathsAreTemp) == FALSE)
		{
			// display a message box
			CString sError;
			LangFormatString2(sError, IDS_PREDIFFER_ERROR, strFile2Temp.c_str(),
				m_infoPrediffer->pluginName.c_str());
			AfxMessageBox(sError, MB_OK | MB_ICONSTOP);
			// don't use any more this prediffer
			m_infoPrediffer->bToBeScanned = FALSE;
			m_infoPrediffer->pluginName.erase();
		}
	}

	// Comparing UTF-8 files seems to require this conversion?
	// I'm still very confused about why, as what the functions
	// document doing is UCS2 to UTF-8 conversion, nothing else.
	// Something is wrong here. - Kimmo
	FileTransform_UCS2ToUTF8(strFile1Temp, m_bPathsAreTemp);
	FileTransform_UCS2ToUTF8(strFile2Temp, m_bPathsAreTemp);

	DiffFileData diffdata;
	diffdata.SetDisplayFilepaths(filepath1.c_str(), filepath2.c_str()); // store true names for diff utils patch file
	// This opens & fstats both files (if it succeeds)
	if (!diffdata.OpenFiles(strFile1Temp.c_str(), strFile2Temp.c_str()))
	{
		return FALSE;
	}

	// Compare the files, if no error was found.
	// Last param (bin_file) is NULL since we don't
	// (yet) need info about binary sides.
	int bin_flag = 0;
	struct change *script = NULL;
	bRet = Diff2Files(&script, &diffdata, &bin_flag, NULL);

	// We don't anymore create diff-files for every rescan.
	// User can create patch-file whenever one wants to.
	// We don't need to waste time. But lets keep this as
	// debugging aid. Sometimes it is very useful to see
	// what differences diff-engine sees!
#ifdef _DEBUG
	// throw the diff into a temp file
	String sTempPath = env_GetTempPath(); // get path to Temp folder
	String path = paths_ConcatPath(sTempPath, _T("Diff.txt"));

	outfile = _tfopen(path.c_str(), _T("w+"));
	if (outfile != NULL)
	{
		print_normal_script(script);
		fclose(outfile);
		outfile = NULL;
	}
#endif

	// First determine what happened during comparison
	// If there were errors or files were binaries, don't bother
	// creating diff-lists or patches
	
	// diff_2_files set bin_flag to -1 if different binary
	// diff_2_files set bin_flag to +1 if same binary
	if (bin_flag != 0)
	{
		m_status.bBinaries = TRUE;
		if (bin_flag == -1)
			m_status.bIdentical = FALSE;
		else
			m_status.bIdentical = TRUE;
	}
	else
	{ // text files according to diffutils, so change script exists
		m_status.bIdentical = (script == 0);
		m_status.bBinaries = FALSE;
	}
	file_data * inf = diffdata.m_inf;
	m_status.bLeftMissingNL = inf[0].missing_newline;
	m_status.bRightMissingNL = inf[1].missing_newline;


	// Create patch file
	if (!m_status.bBinaries && m_bCreatePatchFile)
	{
		WritePatchFile(script, &inf[0]);
	}
	
	// Go through diffs adding them to WinMerge's diff list
	// This is done on every WinMerge's doc rescan!
	if (!m_status.bBinaries && m_bUseDiffList)
	{
		LoadWinMergeDiffsFromDiffUtilsScript(script, diffdata.m_inf);
	}			

	FreeDiffUtilsScript(script);

	// Done with diffutils filedata
	diffdata.Close();

	if (m_bPluginsEnabled)
	{
		// Delete temp files transformation functions possibly created
		if (lstrcmpi(filepath1.c_str(), strFile1Temp.c_str()) != 0)
		{
			if (!::DeleteFile(strFile1Temp.c_str()))
			{
				LogErrorString(Fmt(_T("DeleteFile(%s) failed: %s"),
					strFile1Temp.c_str(), GetSysError(GetLastError()).c_str()));
			}
			strFile1Temp.erase();
		}
		if (lstrcmpi(filepath2.c_str(), strFile2Temp.c_str()) != 0)
		{
			if (!::DeleteFile(strFile2Temp.c_str()))
			{
				LogErrorString(Fmt(_T("DeleteFile(%s) failed: %s"),
					strFile2Temp.c_str(), GetSysError(GetLastError()).c_str()));
			}
			strFile2Temp.erase();
		}
	}
	return bRet;
}
Esempio n. 19
0
int main(int argc, char ** argv)
{
	int c;
	int flags = MS_MANDLOCK; /* no need to set legacy MS_MGC_VAL */
	char * orgoptions = NULL;
	char * share_name = NULL;
	const char * ipaddr = NULL;
	char * uuid = NULL;
	char * mountpoint = NULL;
	char * options = NULL;
	char * optionstail;
	char * resolved_path = NULL;
	char * temp;
	char * dev_name;
	int rc = 0;
	int rsize = 0;
	int wsize = 0;
	int nomtab = 0;
	int uid = 0;
	int gid = 0;
	int optlen = 0;
	int orgoptlen = 0;
	size_t options_size = 0;
	size_t current_len;
	int retry = 0; /* set when we have to retry mount with uppercase */
	struct addrinfo *addrhead = NULL, *addr;
	struct stat statbuf;
	struct utsname sysinfo;
	struct mntent mountent;
	struct sockaddr_in *addr4;
	struct sockaddr_in6 *addr6;
	FILE * pmntfile;

	/* setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE); */

	if(argc && argv) {
		thisprogram = argv[0];
	} else {
		mount_cifs_usage();
		exit(EX_USAGE);
	}

	if(thisprogram == NULL)
		thisprogram = "mount.cifs";

	uname(&sysinfo);
	/* BB add workstation name and domain and pass down */

/* #ifdef _GNU_SOURCE
	printf(" node: %s machine: %s sysname %s domain %s\n", sysinfo.nodename,sysinfo.machine,sysinfo.sysname,sysinfo.domainname);
#endif */
	if(argc > 2) {
		dev_name = argv[1];
		share_name = strndup(argv[1], MAX_UNC_LEN);
		if (share_name == NULL) {
			fprintf(stderr, "%s: %s", argv[0], strerror(ENOMEM));
			exit(EX_SYSERR);
		}
		mountpoint = argv[2];
	} else if (argc == 2) {
		if ((strcmp(argv[1], "-V") == 0) ||
		    (strcmp(argv[1], "--version") == 0))
		{
			print_cifs_mount_version();
			exit(0);
		}

		if ((strcmp(argv[1], "-h") == 0) ||
		    (strcmp(argv[1], "-?") == 0) ||
		    (strcmp(argv[1], "--help") == 0))
		{
			mount_cifs_usage();
			exit(0);
		}

		mount_cifs_usage();
		exit(EX_USAGE);
	} else {
		mount_cifs_usage();
		exit(EX_USAGE);
	}

	/* add sharename in opts string as unc= parm */

	while ((c = getopt_long (argc, argv, "afFhilL:no:O:rsSU:vVwt:",
			 longopts, NULL)) != -1) {
		switch (c) {
/* No code to do the following  options yet */
/*	case 'l':
		list_with_volumelabel = 1;
		break;
	case 'L':
		volumelabel = optarg;
		break; */
/*	case 'a':	       
		++mount_all;
		break; */

		case '?':
		case 'h':	 /* help */
			mount_cifs_usage ();
			exit(EX_USAGE);
		case 'n':
			++nomtab;
			break;
		case 'b':
#ifdef MS_BIND
			flags |= MS_BIND;
#else
			fprintf(stderr,
				"option 'b' (MS_BIND) not supported\n");
#endif
			break;
		case 'm':
#ifdef MS_MOVE		      
			flags |= MS_MOVE;
#else
			fprintf(stderr,
				"option 'm' (MS_MOVE) not supported\n");
#endif
			break;
		case 'o':
			orgoptions = strdup(optarg);
		    break;
		case 'r':  /* mount readonly */
			flags |= MS_RDONLY;
			break;
		case 'U':
			uuid = optarg;
			break;
		case 'v':
			++verboseflag;
			break;
		case 'V':
			print_cifs_mount_version();
			exit (0);
		case 'w':
			flags &= ~MS_RDONLY;
			break;
		case 'R':
			rsize = atoi(optarg) ;
			break;
		case 'W':
			wsize = atoi(optarg);
			break;
		case '1':
			if (isdigit(*optarg)) {
				char *ep;

				uid = strtoul(optarg, &ep, 10);
				if (*ep) {
					printf("bad uid value \"%s\"\n", optarg);
					exit(EX_USAGE);
				}
			} else {
				struct passwd *pw;

				if (!(pw = getpwnam(optarg))) {
					printf("bad user name \"%s\"\n", optarg);
					exit(EX_USAGE);
				}
				uid = pw->pw_uid;
				endpwent();
			}
			break;
		case '2':
			if (isdigit(*optarg)) {
				char *ep;

				gid = strtoul(optarg, &ep, 10);
				if (*ep) {
					printf("bad gid value \"%s\"\n", optarg);
					exit(EX_USAGE);
				}
			} else {
				struct group *gr;

				if (!(gr = getgrnam(optarg))) {
					printf("bad user name \"%s\"\n", optarg);
					exit(EX_USAGE);
				}
				gid = gr->gr_gid;
				endpwent();
			}
			break;
		case 'u':
			got_user = 1;
			user_name = optarg;
			break;
		case 'd':
			domain_name = optarg; /* BB fix this - currently ignored */
			got_domain = 1;
			break;
		case 'p':
			if(mountpassword == NULL)
				mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
			if(mountpassword) {
				got_password = 1;
				strlcpy(mountpassword,optarg,MOUNT_PASSWD_SIZE+1);
			}
			break;
		case 'S':
			get_password_from_file(0 /* stdin */,NULL);
			break;
		case 't':
			break;
		case 'f':
			++fakemnt;
			break;
		default:
			printf("unknown mount option %c\n",c);
			mount_cifs_usage();
			exit(EX_USAGE);
		}
	}

	if((argc < 3) || (dev_name == NULL) || (mountpoint == NULL)) {
		mount_cifs_usage();
		exit(EX_USAGE);
	}

	if (getenv("PASSWD")) {
		if(mountpassword == NULL)
			mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
		if(mountpassword) {
			strlcpy(mountpassword,getenv("PASSWD"),MOUNT_PASSWD_SIZE+1);
			got_password = 1;
		}
	} else if (getenv("PASSWD_FD")) {
		get_password_from_file(atoi(getenv("PASSWD_FD")),NULL);
	} else if (getenv("PASSWD_FILE")) {
		get_password_from_file(0, getenv("PASSWD_FILE"));
	}

        if (orgoptions && parse_options(&orgoptions, &flags)) {
                rc = EX_USAGE;
		goto mount_exit;
	}
	addrhead = addr = parse_server(&share_name);
	if((addrhead == NULL) && (got_ip == 0)) {
		printf("No ip address specified and hostname not found\n");
		rc = EX_USAGE;
		goto mount_exit;
	}
	
	/* BB save off path and pop after mount returns? */
	resolved_path = (char *)malloc(PATH_MAX+1);
	if(resolved_path) {
		/* Note that if we can not canonicalize the name, we get
		another chance to see if it is valid when we chdir to it */
		if (realpath(mountpoint, resolved_path)) {
			mountpoint = resolved_path; 
		}
	}
	if(chdir(mountpoint)) {
		printf("mount error: can not change directory into mount target %s\n",mountpoint);
		rc = EX_USAGE;
		goto mount_exit;
	}

	if(stat (".", &statbuf)) {
		printf("mount error: mount point %s does not exist\n",mountpoint);
		rc = EX_USAGE;
		goto mount_exit;
	}

	if (S_ISDIR(statbuf.st_mode) == 0) {
		printf("mount error: mount point %s is not a directory\n",mountpoint);
		rc = EX_USAGE;
		goto mount_exit;
	}

	if((getuid() != 0) && (geteuid() == 0)) {
		if((statbuf.st_uid == getuid()) && (S_IRWXU == (statbuf.st_mode & S_IRWXU))) {
#ifndef CIFS_ALLOW_USR_SUID
			/* Do not allow user mounts to control suid flag
			for mount unless explicitly built that way */
			flags |= MS_NOSUID | MS_NODEV;
#endif						
		} else {
			printf("mount error: permission denied or not superuser and mount.cifs not installed SUID\n"); 
			exit(EX_USAGE);
		}
	}

	if(got_user == 0) {
		/* Note that the password will not be retrieved from the
		   USER env variable (ie user%password form) as there is
		   already a PASSWD environment varaible */
		if (getenv("USER"))
			user_name = strdup(getenv("USER"));
		if (user_name == NULL)
			user_name = getusername();
		got_user = 1;
	}
       
	if(got_password == 0) {
		char *tmp_pass = getpass("Password: "******"Password not entered, exiting\n");
			exit(EX_USAGE);
		}
		strlcpy(mountpassword, tmp_pass, MOUNT_PASSWD_SIZE+1);
		got_password = 1;
	}
	/* FIXME launch daemon (handles dfs name resolution and credential change) 
	   remember to clear parms and overwrite password field before launching */
	if(orgoptions) {
		optlen = strlen(orgoptions);
		orgoptlen = optlen;
	} else
		optlen = 0;
	if(share_name)
		optlen += strlen(share_name) + 4;
	else {
		printf("No server share name specified\n");
		printf("\nMounting the DFS root for server not implemented yet\n");
                exit(EX_USAGE);
	}
	if(user_name)
		optlen += strlen(user_name) + 6;
	optlen += MAX_ADDRESS_LEN + 4;
	if(mountpassword)
		optlen += strlen(mountpassword) + 6;
mount_retry:
	SAFE_FREE(options);
	options_size = optlen + 10 + DOMAIN_SIZE;
	options = (char *)malloc(options_size /* space for commas in password */ + 8 /* space for domain=  , domain name itself was counted as part of the length username string above */);

	if(options == NULL) {
		printf("Could not allocate memory for mount options\n");
		exit(EX_SYSERR);
	}

	strlcpy(options, "unc=", options_size);
	strlcat(options,share_name,options_size);
	/* scan backwards and reverse direction of slash */
	temp = strrchr(options, '/');
	if(temp > options + 6)
		*temp = '\\';
	if(user_name) {
		/* check for syntax like user=domain\user */
		if(got_domain == 0)
			domain_name = check_for_domain(&user_name);
		strlcat(options,",user="******",domain=",options_size);
			strlcat(options,domain_name,options_size);
		}
	}

	strlcat(options,",ver=",options_size);
	strlcat(options,MOUNT_CIFS_VERSION_MAJOR,options_size);

	if(orgoptions) {
		strlcat(options,",",options_size);
		strlcat(options,orgoptions,options_size);
	}
	if(prefixpath) {
		strlcat(options,",prefixpath=",options_size);
		strlcat(options,prefixpath,options_size); /* no need to cat the / */
	}

	/* convert all '\\' to '/' in share portion so that /proc/mounts looks pretty */
	replace_char(dev_name, '\\', '/', strlen(share_name));

	if (!got_ip && addr) {
		strlcat(options, ",ip=", options_size);
		current_len = strnlen(options, options_size);
		optionstail = options + current_len;
		switch (addr->ai_addr->sa_family) {
		case AF_INET6:
			addr6 = (struct sockaddr_in6 *) addr->ai_addr;
			ipaddr = inet_ntop(AF_INET6, &addr6->sin6_addr, optionstail,
					   options_size - current_len);
			break;
		case AF_INET:
			addr4 = (struct sockaddr_in *) addr->ai_addr;
			ipaddr = inet_ntop(AF_INET, &addr4->sin_addr, optionstail,
					   options_size - current_len);
			break;
		}

		/* if the address looks bogus, try the next one */
		if (!ipaddr) {
			addr = addr->ai_next;
			if (addr)
				goto mount_retry;
			rc = EX_SYSERR;
			goto mount_exit;
		}
	}

	if(verboseflag)
		fprintf(stderr, "\nmount.cifs kernel mount options: %s", options);

	if (mountpassword) {
		/*
		 * Commas have to be doubled, or else they will
		 * look like the parameter separator
		 */
		if(retry == 0)
			check_for_comma(&mountpassword);
		strlcat(options,",pass="******",pass=********");
	}

	if (verboseflag)
		fprintf(stderr, "\n");

	if (!fakemnt && mount(dev_name, mountpoint, "cifs", flags, options)) {
		switch (errno) {
		case ECONNREFUSED:
		case EHOSTUNREACH:
			if (addr) {
				addr = addr->ai_next;
				if (addr)
					goto mount_retry;
			}
			break;
		case ENODEV:
			printf("mount error: cifs filesystem not supported by the system\n");
			break;
		case ENXIO:
			if(retry == 0) {
				retry = 1;
				if (uppercase_string(dev_name) &&
				    uppercase_string(share_name) &&
				    uppercase_string(prefixpath)) {
					printf("retrying with upper case share name\n");
					goto mount_retry;
				}
			}
		}
		printf("mount error(%d): %s\n", errno, strerror(errno));
		printf("Refer to the mount.cifs(8) manual page (e.g. man "
		       "mount.cifs)\n");
		rc = EX_FAIL;
		goto mount_exit;
	}

	if (nomtab)
		goto mount_exit;
	atexit(unlock_mtab);
	rc = lock_mtab();
	if (rc) {
		printf("cannot lock mtab");
		goto mount_exit;
	}
	pmntfile = setmntent(MOUNTED, "a+");
	if (!pmntfile) {
		printf("could not update mount table\n");
		unlock_mtab();
		rc = EX_FILEIO;
		goto mount_exit;
	}
	mountent.mnt_fsname = dev_name;
	mountent.mnt_dir = mountpoint;
	mountent.mnt_type = CONST_DISCARD(char *,"cifs");
	mountent.mnt_opts = (char *)malloc(220);
	if(mountent.mnt_opts) {
		char * mount_user = getusername();
		memset(mountent.mnt_opts,0,200);
		if(flags & MS_RDONLY)
			strlcat(mountent.mnt_opts,"ro",220);
		else
			strlcat(mountent.mnt_opts,"rw",220);
		if(flags & MS_MANDLOCK)
			strlcat(mountent.mnt_opts,",mand",220);
		if(flags & MS_NOEXEC)
			strlcat(mountent.mnt_opts,",noexec",220);
		if(flags & MS_NOSUID)
			strlcat(mountent.mnt_opts,",nosuid",220);
		if(flags & MS_NODEV)
			strlcat(mountent.mnt_opts,",nodev",220);
		if(flags & MS_SYNCHRONOUS)
			strlcat(mountent.mnt_opts,",sync",220);
		if(mount_user) {
			if(getuid() != 0) {
				strlcat(mountent.mnt_opts,
					",user=", 220);
				strlcat(mountent.mnt_opts,
					mount_user, 220);
			}
		}
	}
	mountent.mnt_freq = 0;
	mountent.mnt_passno = 0;
	rc = addmntent(pmntfile,&mountent);
	endmntent(pmntfile);
	unlock_mtab();
	SAFE_FREE(mountent.mnt_opts);
	if (rc)
		rc = EX_FILEIO;
mount_exit:
	if(mountpassword) {
		int len = strlen(mountpassword);
		memset(mountpassword,0,len);
		SAFE_FREE(mountpassword);
	}

	if (addrhead)
		freeaddrinfo(addrhead);
	SAFE_FREE(options);
	SAFE_FREE(orgoptions);
	SAFE_FREE(resolved_path);
	SAFE_FREE(share_name);
	exit(rc);
}
/**
 * Write the canvas to an image file and/or JSON summary.
 *
 * @param canvas Must be non-null. Canvas to be written to a file.
 * @param writePath If nonempty, write the binary image to a file within this directory.
 * @param mismatchPath If nonempty, write the binary image to a file within this directory,
 *     but only if the image does not match expectations.
 * @param inputFilename If we are writing out a binary image, use this to build its filename.
 * @param jsonSummaryPtr If not null, add image results (checksum) to this summary.
 * @param useChecksumBasedFilenames If true, use checksum-based filenames when writing to disk.
 * @param tileNumberPtr If not null, which tile number this image contains.
 *
 * @return bool True if the operation completed successfully.
 */
static bool write(SkCanvas* canvas, const SkString& writePath, const SkString& mismatchPath,
                  const SkString& inputFilename, ImageResultsAndExpectations *jsonSummaryPtr,
                  bool useChecksumBasedFilenames, const int* tileNumberPtr=NULL) {
    SkASSERT(canvas != NULL);
    if (NULL == canvas) {
        return false;
    }

    SkBitmap bitmap;
    SkISize size = canvas->getDeviceSize();
    setup_bitmap(&bitmap, size.width(), size.height());

    canvas->readPixels(&bitmap, 0, 0);
    force_all_opaque(bitmap);
    BitmapAndDigest bitmapAndDigest(bitmap);

    SkString escapedInputFilename(inputFilename);
    replace_char(&escapedInputFilename, '.', '_');

    // TODO(epoger): what about including the config type within outputFilename?  That way,
    // we could combine results of different config types without conflicting filenames.
    SkString outputFilename;
    const char *outputSubdirPtr = NULL;
    if (useChecksumBasedFilenames) {
        ImageDigest *imageDigestPtr = bitmapAndDigest.getImageDigestPtr();
        outputSubdirPtr = escapedInputFilename.c_str();
        outputFilename.set(imageDigestPtr->getHashType());
        outputFilename.append("_");
        outputFilename.appendU64(imageDigestPtr->getHashValue());
    } else {
        outputFilename.set(escapedInputFilename);
        if (tileNumberPtr) {
            outputFilename.append("-tile");
            outputFilename.appendS32(*tileNumberPtr);
        }
    }
    outputFilename.append(".png");

    if (jsonSummaryPtr) {
        ImageDigest *imageDigestPtr = bitmapAndDigest.getImageDigestPtr();
        SkString outputRelativePath;
        if (outputSubdirPtr) {
            outputRelativePath.set(outputSubdirPtr);
            outputRelativePath.append("/");  // always use "/", even on Windows
            outputRelativePath.append(outputFilename);
        } else {
            outputRelativePath.set(outputFilename);
        }

        jsonSummaryPtr->add(inputFilename.c_str(), outputRelativePath.c_str(),
                            *imageDigestPtr, tileNumberPtr);
        if (!mismatchPath.isEmpty() &&
            !jsonSummaryPtr->getExpectation(inputFilename.c_str(),
                                            tileNumberPtr).matches(*imageDigestPtr)) {
            if (!write_bitmap_to_disk(bitmap, mismatchPath, outputSubdirPtr, outputFilename)) {
                return false;
            }
        }
    }

    if (writePath.isEmpty()) {
        return true;
    } else {
        return write_bitmap_to_disk(bitmap, writePath, outputSubdirPtr, outputFilename);
    }
}
Esempio n. 21
0
File: config.c Progetto: KryDos/vifm
void
init_config(void)
{
	cfg.show_one_window = 0;
	cfg.history_len = 15;

	(void)hist_init(&cfg.cmd_hist, cfg.history_len);
	(void)hist_init(&cfg.search_hist, cfg.history_len);
	(void)hist_init(&cfg.prompt_hist, cfg.history_len);
	(void)hist_init(&cfg.filter_hist, cfg.history_len);

	cfg.auto_execute = 0;
	cfg.time_format = strdup(" %m/%d %H:%M");
	cfg.wrap_quick_view = 1;
	cfg.use_iec_prefixes = 0;
	cfg.undo_levels = 100;
	cfg.sort_numbers = 0;
	cfg.follow_links = 1;
	cfg.fast_run = 0;
	cfg.confirm = 1;
	cfg.vi_command = strdup("vim");
	cfg.vi_cmd_bg = 0;
	cfg.vi_x_command = strdup("");
	cfg.vi_x_cmd_bg = 0;
	cfg.use_trash = 1;

	{
		char fuse_home[PATH_MAX];
		int update_stat;
		snprintf(fuse_home, sizeof(fuse_home), "%s/vifm_FUSE", get_tmpdir());
		update_stat = set_fuse_home(fuse_home);
		assert(update_stat == 0);
	}

	cfg.use_term_multiplexer = 0;
	cfg.use_vim_help = 0;
	cfg.wild_menu = 0;
	cfg.ignore_case = 0;
	cfg.smart_case = 0;
	cfg.hl_search = 1;
	cfg.vifm_info = VIFMINFO_BOOKMARKS;
	cfg.auto_ch_pos = 1;
	cfg.timeout_len = 1000;
	cfg.scroll_off = 0;
	cfg.gdefault = 0;
#ifndef _WIN32
	cfg.slow_fs_list = strdup("");
#endif
	cfg.scroll_bind = 0;
	cfg.wrap_scan = 1;
	cfg.inc_search = 0;
	cfg.selection_is_primary = 1;
	cfg.tab_switches_pane = 1;
	cfg.use_system_calls = 0;
	cfg.last_status = 1;
	cfg.tab_stop = 8;
	cfg.ruler_format = strdup("%=%l/%S ");
	cfg.status_line = strdup("");

	cfg.lines = INT_MIN;
	cfg.columns = INT_MIN;

	cfg.dot_dirs = DD_NONROOT_PARENT;

	cfg.trunc_normal_sb_msgs = 0;

	cfg.filter_inverted_by_default = 1;

	cfg.apropos_prg = strdup("apropos %a");
	cfg.find_prg = strdup("find %s %a -print , "
			"-type d \\( ! -readable -o ! -executable \\) -prune");
	cfg.grep_prg = strdup("grep -n -H -I -r %i %a %s");
	cfg.locate_prg = strdup("locate %a");

	cfg.cd_path = strdup(env_get_def("CDPATH", DEFAULT_CD_PATH));
	replace_char(cfg.cd_path, ':', ',');

	cfg.filelist_col_padding = 1;
	cfg.side_borders_visible = 1;

	cfg.border_filler = strdup(" ");

#ifndef _WIN32
	copy_str(cfg.log_file, sizeof(cfg.log_file), "/var/log/vifm-startup-log");
#else
	{
		char exe_dir[PATH_MAX];
		(void)get_exe_dir(exe_dir, sizeof(exe_dir));
		snprintf(cfg.log_file, sizeof(cfg.log_file), "%s/startup-log", exe_dir);
	}
#endif

	cfg_set_shell(env_get_def("SHELL", DEFAULT_SHELL_CMD));

	memset(&cfg.decorations, '\0', sizeof(cfg.decorations));
	cfg.decorations[DIRECTORY][DECORATION_SUFFIX] = '/';
}