Esempio n. 1
0
int tcps_file(int port) {
    if ( (fdl = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
	fprintf(stderr, "socket : \n");
	exit(EXIT_FAILURE);
    }
    memset(&datas, 0, sizeof(struct sockaddr_in));
    datas.sin_family      = AF_INET;
    datas.sin_addr.s_addr = htonl(INADDR_ANY);
    datas.sin_port        = htons(port);
    
    if ( bind(fdl, (struct sockaddr *) &datas, sizeof(struct sockaddr)) < 0 ) {
	fprintf(stderr, "bind : \n");
	exit(EXIT_FAILURE);
    }
    if ( listen(fdl,MAX_LINE) < 0 ) {
	fprintf(stderr, "listen : \n");
	exit(EXIT_FAILURE);
    }
    printf("en écoute \n");
    for (;;) {
        if ((fdc = accept(fdl, NULL, 0)) < 0) {
            fprintf(stderr,"accept : \n");
        }
        int pid = fork();
        switch(pid){
            case 0 :
                    printf("connecté\n");
                    do {
                        tcps_recv(queryrecv,BLOCK);
                        printf("querry recieved! \"%s\"\n", queryrecv);
                        if (strcmp(getfilename(queryrecv),SCAN)==0) {
                            printf("Scanning for file %s\n", queryrecv+5);
                            tcps_scan(getfilename(queryrecv+5));
                        } else if (strcmp(getfilename(queryrecv),UNCONNECT)!=0) {
                            printf("ask for block number : %d of the file %s\n",getblocknumber(queryrecv),getfilename(queryrecv));
                            tcps_sendblock(getfilename(queryrecv),getblocknumber(queryrecv));
                            usleep(10);
                        } else {
                            printf("GoodBye!");
                        }
                    } while (strcmp(getfilename(queryrecv),UNCONNECT)!=0);
                if ( shutdown(fdc,SHUT_RDWR) < 0 ) {
                    fprintf(stderr, "shutdown : \n");
                    exit(EXIT_FAILURE);
                }
                if ( close(fdc) < 0 ) {
                    fprintf(stderr, "close : \n");
                    exit(EXIT_FAILURE);
                }
                    exit(0);
                    break;
            default:
                break;
        }
    }
}
Esempio n. 2
0
namespace Platform
{
	enum Type
	{
		NULLPlatform=-1, x86, ARM
	};

	static const char* Files[]={getfilename("sets/x86.txt"), getfilename("sets/arm.txt")};
	static const char* Names[]={"x86", "ARM"};
}
Esempio n. 3
0
/* Searches DIR for a file with the given NAME
   and returns true if one exists, false otherwise.
   On success, sets *INODE to an inode for the file, otherwise to
   a null pointer.  The caller must close *INODE. */
bool
dir_lookup (const struct dir *dir, const char *name,
            struct inode **inode) 
{
  struct dir_entry e;

  ASSERT (dir != NULL);
  ASSERT (name != NULL);


  //we have to stop / lookup in /
  if( strcmp(name,"/") == 0 && inode_id(dir->inode) == ROOT_DIR_SECTOR)
	*inode = inode_reopen(dir->inode);
  else {
  //lock the directory for the rest of the lookup operation
  inode_lock(dir->inode);
  name = getfilename(name);
 
  if (lookup (dir, name, &e, NULL))
    *inode = inode_open (e.inode_sector);
  else
    *inode = NULL;
 //unlock the dir again
 inode_unlock(dir->inode);
 }

  return *inode != NULL;
}
Esempio n. 4
0
ssize_t my_write(int fd, const void *buf, size_t count)
{
    //获取真实地址
    typedef ssize_t (*REALFUNC)(int fd, const void *buf, size_t count);
    REALFUNC real_write = (REALFUNC)get_real_func("write");

    //忽略标准输入/输出
    if(fd >=0 && fd <= 2) {
        return real_write(fd, buf, count);
    }
    //通过fd获取文件名并过滤
    char filename[256];
    getfilename(fd, filename, sizeof(filename));
    char *fname = "data.txt";
    //判断文件名是否为"data.txt",如果不是则调用原函数
    if(strncmp(filename, fname, strlen(fname)) != 0) {
        return real_write(fd, buf, count);
    }

    //考虑到printf实际内部会调用write函数,避免循环调用,执行printf前先detach之后再attach
    detach_func("write");
    printf("[%s] fd:%d(%s), buf:%s\n", __FUNCTION__, fd, filename, buf);
    attach_func("write", (void *)my_write);

    errno = ENOSPC;
    return -1;
}
Esempio n. 5
0
int Wordcount(char *file, char *target_dir){
	char wordset[_MAX_WORDNUMBER_][_MAX_WORDLEN_];
	int wstop=-1,count=0,ret=0;

	initWordcount(file,target_dir);
	struct timeval t_stamp = getUTimeStamp();
	char full_file_path[_MAX_FILEBUFFERLEN_];
	//open file to write into
	char* ctmpptr = strstr(file,".txt"); memset(ctmpptr,0,strlen(ctmpptr)*sizeof(char)); *ctmpptr='\0';
	ctmpptr=getfilename(file);
	snprintf(full_file_path, sizeof(full_file_path), "%s/%s.txt___%d.%d.txt", target_dir, 
                 ctmpptr, (int)(t_stamp.tv_sec),(int)(t_stamp.tv_usec));
	FILE* fout=fopen(full_file_path,"w");
	if(fout){
		for(getToken();chtype!=endoffile;getToken()){
			strcpy(wordset[++wstop],token);
			CLEARTOEK;
		}
		if(prv_chtype==character){
			strcpy(wordset[++wstop],token);	
		}
		//sort
		qsort(wordset, wstop, _MAX_WORDLEN_*(sizeof(char)), fcmp);
		//write into file
		int i=0,j=0,sum=0;
		for(i=0;i<wstop;i=j){
			for(sum=0,j=i; (strcmp(wordset[j],wordset[i])==0) && j<wstop; ++j,++sum)	;
			fprintf(fout,"%s %d\n",wordset[i],sum);
		}
		fclose(fout);
	}else{
		return -1;
	}
	return 0;
}
Esempio n. 6
0
void truncfilename(char* path)
{
	char* i = getfilename(path);
	memmove(path,i,strlen(i)+1);
	i = strrchr(path,'.');
	if (i) *i=0;
}
Esempio n. 7
0
/* check permissions and setup the upload transfer */
void upload_start(const char *nick, const char *hostname, const char *hostmask,
                  const char *filename, const char *remoteip, const char *remoteport, const char *bytes, char *token)
{
  upload *ul;
  char *uploaddir;
  char *tempstr;
  off_t len;

  updatecontext();

  len = atoull(bytes);
  if (invalid_upload(nick, hostmask, len))
    return;
  uploaddir = get_uploaddir(hostmask);
  if (uploaddir == NULL) {
    error_upload_start(nick, hostmask, "no uploaddir", "No uploaddir defined.");
    return;
  }
  if (disk_full(uploaddir) != 0) {
    error_upload_start(nick, hostmask, "disk full", "not enough free space on disk");
    return;
  }
  if (file_uploading(filename) != 0) {
    error_upload_start(nick, hostmask, "upload running", "I'm already getting this file");
    return;
  }
  if (max_uploads_reached() != 0) {
    error_upload_start(nick, hostmask, "too many uploads", "I'm already getting too many files");
    return;
  }
  ul = irlist_add(&gdata.uploads, sizeof(upload));
  l_initvalues(ul);
  ul->file = mystrdup(getfilename(filename));
  ul->con.family = (strchr(remoteip, ':')) ? AF_INET6 : AF_INET;
  ul->con.remoteaddr = mystrdup(remoteip);
  ul->con.remoteport = atoi(remoteport);
  ul->totalsize = len;
  ul->nick = mystrdup(nick);
  ul->hostname = mystrdup(hostname);
  ul->uploaddir = mystrdup(uploaddir);
  ul->net = gnetwork->net;
  qupload_started(gnetwork->net, nick);

  tempstr = getsendname(ul->file);
  ioutput(OUT_S|OUT_L|OUT_D, COLOR_YELLOW,
          "DCC Send Accepted from %s on %s: %s (%" LLPRINTFMT "dkB)",
          nick, gnetwork->name, tempstr,
          (ul->totalsize / 1024));
  mydelete(tempstr);
  if (gdata.mirc_dcc64)
    if (ul->totalsize > 0xFFFFFFFFL)
      ul->mirc_dcc64 = 1;

  if (ul->con.remoteport > 0U) {
    l_establishcon(ul);
  } else {
    /* Passive DCC */
    l_setup_passive(ul, token);
  }
}
Esempio n. 8
0
branch()
{
	register char	c;
	register int	i;
	extern char	getch();

#	ifdef xMTR2
	if (tTf(16, -1))
		printf(">>branch: ");
#	endif

	/* see if conditional */
	while ((c = getch()) > 0)
		if (c != ' ' && c != '\t')
			break;
	if (c == '?')
	{
		/* got a conditional; evaluate it */
		Oneline = TRUE;
		macinit(&getch, 0, 0);
		i = expr();

		if (i <= 0)
		{
			/* no branch */
#			ifdef xMTR2
			if (tTf(16, 0))
				printf("no branch\n");
#			endif
			getfilename();
			return;
		}
	}
	else
	{
		Peekch = c;
	}

	/* get the target label */
	if (branchto(getfilename()) == 0)
		if (branchto(macro("{default}")) == 0)
		{
			Peekch = -1;
			printf("Cannot branch\n");
		}
	return;
}
Esempio n. 9
0
FILE *fileopen(char *deflt, char *extension, char *mode, char *prompt)
{
    FILE *fp = NULL;            /* file corresponding to filename */
    if (getfilename(deflt, extension, mode, prompt)) {
        fp = fopen(fileopen_name, mode);
    }
    return fp;
}
Esempio n. 10
0
void loadModels(ApplicationInfo *application){
  application->num_objects=getnumfiles("data/Models",".3ds");
  application->objects = (model_3ds*)malloc(sizeof(model_3ds)*application->num_objects);
  for(int x=0;x< application->num_objects;x++){
    Load3DS(&(application->objects[x]),getfilename("data/Models",".3ds",x));
    Buffer3DS(&(application->objects[x]));
  }
  printf("Buffering done\n");
}
Esempio n. 11
0
string	filepath::getfullname(){
	string tmp;
	tmp = getfullpath();
	if(tmp != ""){
		tmp += "\\";
	}
	tmp += getfilename();
	return tmp;
}
Esempio n. 12
0
void getoutput(string &line, RawSource *rs, FILEMODE m) {
  string n=getfilename(line);
  output.push_back(new Output(n,m));
  onr=(int)output.size()-1;
  rs->GetSource().push_back(new SetOutput(onr));
  rs->GetSource().back()->Process();
  checkjunk(line); line.clear();
  dirCODE(line,rs);
}
Esempio n. 13
0
/* Removes any entry for NAME in DIR.
   Returns true if successful, false on failure,
   which occurs only if there is no file with the given NAME. */
bool
dir_remove (struct dir *dir, const char *name) 
{
  struct dir_entry e;
  struct inode *inode = NULL;
  bool success = false;
  off_t ofs;

  ASSERT (dir != NULL);
  ASSERT (name != NULL);

  //lock the directory for the rest of the lookup operation
  inode_lock(dir->inode);
  name = getfilename(name);

  /* Find directory entry. */
  if (!lookup (dir, name, &e, &ofs))
    goto done;

  /* Open inode. */
  inode = inode_open (e.inode_sector);
  if (inode == NULL)
    goto done;

  //if it is still open don't allow deletion
  if(inode_type(inode) == FILE_DIR) {
	//is file in use?
	if(inode_opencnt(inode) > 1)
		goto done;
	char * temp = (char *)malloc(sizeof(char) * (NAME_MAX + 1) );
	struct dir * dirtemp = dir_open(inode);
	//is dir empty?
	if (dir_readdir(dirtemp,temp)) {
		free(temp);
		dir_close(dirtemp);
		goto done;
	}
	free(temp);
	dir_close(dirtemp);	
  }

  /* Erase directory entry. */
  e.in_use = false;
  if (inode_write_at (dir->inode, &e, sizeof e, ofs) != sizeof e) 
    goto done;

  /* Remove inode. */
  inode_remove (inode);
  success = true;

 done:
  //unlock the directory
  inode_unlock(dir->inode);
  inode_close (inode);
  return success;
}
Esempio n. 14
0
void	main(int argc, char **argv)
{
	char	temp[80];
	char	filetocopy[80];
	char	destdir[80];
	char	opt;

	if (paraminit(1,destdir)<=0)
		help();

	if (!isdir(destdir))
	{
		printf("Last parameter should be destination directory.\n");
		exit(1);
	}
	else
		makedirof(destdir);

	while ((opt=getopt())!=0)
	{
	switch (opt)
	{
	case	'?':
	case	'H':	help();
			break;
	case	'C':	verify=1;
			break;
	case	'V':	verbose=1;
			break;
	case	'A':	assume=1;
			break;
	case	'R':	retry=1;
			break;

	default:	printf("Unknown option '%c'\n",opt);
			exit(1);
	}
	}


	while (getparam(temp)!=NULL)
	{
		if (isdir(temp))
			makedirof(temp);

		while (getfilename(temp,filetocopy,0))
			if (!convert(filetocopy,destdir))
				break;
	}


}
Esempio n. 15
0
File: grfx.c Progetto: j13s/devil
void b_changepogfile(struct w_button *b) {
    char *pogfilename;


    pogfilename = getfilename(&init.pogpath, pig.current_pogname, "POG",
                              "Select pogfile", 0);

    if ( !pogfilename && !yesnomsg(TXT_DEFAULTPOGFILE) ) {
        return;
    }

    changepogfile(pogfilename);
}
int check(gpointer data)
{
	char c;
	int d;
	FILE *ptr;
	char *fname;
	static int flag=0;
	//printf("hi");
	if(!flag)
	{
		c=Read(100);
		if(c==0)
			return 1;
	}
	else
		return 0;
	flag=1;
	switch(c)
	{
		case '0':fname=getfilename();
			printf("%s\n",fname);
			printf("Opening file\n");
			gtk_label_set_text(GTK_LABEL(fstatus),NULL);	
			ptr=fopen(fname,"w");
			while(1)
			{
					
				read(sock,&d,sizeof(int));
				//printf("%s",buf);
				if(d==(-999))
				{
					fclose(ptr);
					printf("\nFile closed\n");
					flag=0;
					free(fname);
					gtk_label_set_text(GTK_LABEL(fstatus),"File Saved");
					return 1;
				}
				//read(sock,&c,1);
				printf("%c",d);
				fprintf(ptr,"%c",d);
			}

			//return 1;
		case '1':close(sock);
			//gtk_widget_destroy_all(window);
			gtk_main_quit();
			exit(0);
	}
	return 1;
}
Esempio n. 17
0
char *
ngraph_get_init_file(const char *init_file)
{
  char *homedir, *confdir, *inifile;;
  struct objlist *sys;

  if (init_file == NULL) {
    return NULL;
  }

  sys = chkobject("system");
  getobj(sys, "home_dir", 0, 0, NULL, &homedir);
  getobj(sys, "conf_dir", 0, 0, NULL, &confdir);

  inifile = NULL;
  if (findfilename(homedir, CONFTOP, init_file)) {
    inifile = getfilename(homedir, CONFTOP, init_file);
  } else if (findfilename(confdir, CONFTOP, init_file)) {
    inifile = getfilename(confdir, CONFTOP, init_file);
  }

  return inifile;
}
Esempio n. 18
0
char *addfilename(char *url, int size, char *pagefile) {
  char buff[BUFFSIZE];

  getfilename(buff, BUFFSIZE, pagefile);

  /* If pagefile filename is unexpected, add to the end of url */
  if (!strncmp(url + strlen(url) - strlen(buff), buff,
	       size - strlen(url) + strlen(buff)))
    return url; /* already ready */

  if (!(url[strlen(url) - 1] == '/'))
    strncat(url, "/", size);
  strncat(url, buff, size);

  return url;
}
Esempio n. 19
0
/* this is the plugin entry point */
enum plugin_status plugin_start(struct plugin_api* api, void* parameter)
{
    unsigned char *result,buf[500];
    int parsefd,hits;
    /* this macro should be called as the first thing you do in the plugin.
       it test that the api version and model the plugin was compiled for
       matches the machine it is running on */
    TEST_PLUGIN_API(api);

    /* if you are using a global api pointer, don't forget to copy it!
       otherwise you will get lovely "I04: IllInstr" errors... :-) */
    rb = api;
    
    audio_bufferbase=audio_bufferpointer=0;
    audio_buffer_free=0;

    /* now go ahead and have fun! */
    PUTS("SearchEngine v0.1");
    parsefd=rb->open(parameter,O_RDONLY);
    if(parsefd<0) {
        rb->splash(2*HZ,true,"Unable to open search tokenstream");
        return PLUGIN_ERROR;    
    }
    result=parse(parsefd);
    rb->snprintf(buf,250,"Retval: 0x%x",result);
    PUTS(buf);
    rb->close(parsefd);
    hits=0;
    if(result!=0) {
        int fd=rb->open("/search.m3u", O_WRONLY|O_CREAT|O_TRUNC);
        int i;
        for(i=0;i<rb->tagdbheader->filecount;i++)
            if(result[i]) {
                hits++;
                rb->fdprintf(fd,"%s\n",getfilename(i));
            }
        rb->close(fd);
    }
    rb->snprintf(buf,250,"Hits: %d",hits);
    rb->splash(HZ*3,true,buf);
    if (result!=0) {
        /* Return PLUGIN_USB_CONNECTED to force a file-tree refresh */
        return PLUGIN_USB_CONNECTED;
    }
    return PLUGIN_OK;
}
Esempio n. 20
0
/* Adds a file named NAME to DIR, which must not already contain a
   file by that name.  The file's inode is in sector
   INODE_SECTOR.
   Returns true if successful, false on failure.
   Fails if NAME is invalid (i.e. too long) or a disk or memory
   error occurs. */
bool
dir_add (struct dir *dir, const char *name, block_sector_t inode_sector)
{
  struct dir_entry e;
  off_t ofs;
  bool success = false;

  name = getfilename(name);

  ASSERT (dir != NULL);
  ASSERT (name != NULL);

  /* Check NAME for validity. */
  if (*name == '\0' || strlen (name) > NAME_MAX) {
    return false;
  }
  //lock the directory for the operation
  inode_lock(dir->inode);

  /* Check that NAME is not in use. */
  if (lookup (dir, name, NULL, NULL))
    goto done;

  /* Set OFS to offset of free slot.
     If there are no free slots, then it will be set to the
     current end-of-file.
     
     inode_read_at() will only return a short read at end of file.
     Otherwise, we'd need to verify that we didn't get a short
     read due to something intermittent such as low memory. */
  for (ofs = 0; inode_read_at (dir->inode, &e, sizeof e, ofs) == sizeof e;
       ofs += sizeof e) 
    if (!e.in_use)
      break;

  /* Write slot. */
  e.in_use = true;
  strlcpy (e.name, name, sizeof e.name);
  e.inode_sector = inode_sector;
  success = inode_write_at (dir->inode, &e, sizeof e, ofs) == sizeof e;

 done:
  //unlock the directory again
  inode_unlock(dir->inode);
  return success;
}
Esempio n. 21
0
File: syntax.c Progetto: ezrec/vasm
static void stab_entry(char *name,int type,int othr,int desc,char *s)
{
  section *stabs;

  if (!(stabs = find_section(stabname,stabattr))) {
    section *str;
    dblock *db;

    stabs = new_section(stabname,stabattr,4);
    if (!(str = find_section(stabstrname,stabstrattr))) {
      str = new_section(stabstrname,stabstrattr,1);
    }
    else {
      if (str->pc != 0)
        ierror(0);
    }
    /* first byte of .stabstr is 0 */
    add_atom(str,new_space_atom(number_expr(1),1,0)); 
    /* compilation unit header has to be patched by output module */
    new_stabstr(getfilename());
    db = new_dblock();
    db->size = 12;
    db->data = mymalloc(12);
    add_atom(stabs,new_data_atom(db,1));
  }

  add_const_datadef(stabs,name?new_stabstr(name):0,32,1);
  add_const_datadef(stabs,type,8,1);
  add_const_datadef(stabs,othr,8,1);
  add_const_datadef(stabs,desc,16,1);
  if (s) {
    operand *op = new_operand();
    int len = oplen(skip_operand(s),s);

    if (parse_operand(s,len,op,DATA_OPERAND(32))) {
      atom *a = new_datadef_atom(32,op);

      a->align = 1;
      add_atom(stabs,a);
    }
    else
      syntax_error(8);
  }
  else
    add_atom(stabs,new_space_atom(number_expr(4),1,0));  /* no value */
}
Esempio n. 22
0
void dumptok(FILE *out){
   unsigned char printfile = -1;
   for(int i=0; i<=token_list.last; i++){
      if(printfile != token_list.tokens[i]->filenr){
         printfile = token_list.tokens[i]->filenr;
         fprintf(out, "#%3d \"%s\"\n",
               printfile, getfilename(printfile));
      }
      fprintf(out, "%4d%4d.%03d%6d   %-15s (%s)\n",
            token_list.tokens[i]->filenr,
            token_list.tokens[i]->linenr,
            token_list.tokens[i]->offset,
            token_list.tokens[i]->symbol,
            get_yytname(token_list.tokens[i]->symbol),
            //need to convert symbol to literal here
            token_list.tokens[i]->lexeme
            );
   }
}
Esempio n. 23
0
static
void
getsource(unsigned long *i, char **s, char **t, unsigned long *u)
{
    char *a;

    *s = *t = NULL;
    *i = *u = 0;
    /* From mpatrol release 1.4.5, the thread id, source function name, file
     * name and line number for each allocation, reallocation and deallocation
     * is also written to the tracing output file.
     */
    if (version >= 10405)
    {
        *i = getuleb128();
        *s = getfuncname();
        *t = getfilename();
        *u = getuleb128();
    }
}
Esempio n. 24
0
int	main(int argc, char **argv)
{
	char	temp[80];
	char	filetocheck[80];
	char	opt;

	if (paraminit(0,temp)<=0)
		help();


	while ((opt=getopt())!=0)
	{
	switch (opt)
	{
	case	'F':	fix=1;
			break;
	case	'V':	verbose=1;
			break;
	case	'H':
	case	'?':	help();
			break;

	default:	printf("Unknown option '%c'\n",opt);
			exit(1);
	}
	}


	while (getparam(temp)!=NULL)
	{
		if (isdir(temp))
		{
			makedirof(temp);
			scandisk(temp);
		}
		while (getfilename(temp,filetocheck,1))
			scan(filetocheck);
	}

	return 0;
}
Esempio n. 25
0
shell()
{
	register int	i;
	register char	*p;
	register char	*shellfile;
	char		*getfilename();
	char		*macro();

	shellfile = getfilename();
	if (*shellfile == 0)
		shellfile = 0;

	fclose(Qryiop);
	if ((Xwaitpid = fork()) == -1)
		syserr("shell: fork");
	if (Xwaitpid == 0)
	{
		setuid(getuid());
#		ifndef xB_UNIX
		setgid(getgid());
#		endif
		for (i = 3; i < MAXFILES; i++)
			close(i);
		p = macro("{shell}");
#		ifdef xMTR3
		tTfp(7, 0, "{shell} = '%o'\n", p);
#		endif
		if (p != 0)
		{
			execl(p, p, shellfile, Qbname, 0);
			printf("Cannot call %s; using /bin/sh\n", p);
		}
		execl("/bin/sh", "sh", shellfile, Qbname, 0);
		syserr("shell: exec");
	}

	if (Nodayfile >= 0)
		printf(">>shell\n");
	/* wait for shell to complete */
	xwait();
}
/* this is the plugin entry point */
enum plugin_status plugin_start(const void* parameter)
{
    unsigned char *result,buf[500];
    int parsefd,hits;

    audio_bufferbase=audio_bufferpointer=0;
    audio_buffer_free=0;

    /* now go ahead and have fun! */
    PUTS("SearchEngine v0.1");
    parsefd=rb->open(parameter,O_RDONLY);
    if(parsefd<0) {
        rb->splash(2*HZ,"Unable to open search tokenstream");
        return PLUGIN_ERROR;    
    }
    result=parse(parsefd);
    rb->snprintf(buf,250,"Retval: 0x%x",result);
    PUTS(buf);
    rb->close(parsefd);
    hits=0;
    if(result!=0) {
        int fd=rb->open("/search.m3u", O_WRONLY|O_CREAT|O_TRUNC, 0666);
        int i;
        for(i=0;i<rb->tagdbheader->filecount;i++)
            if(result[i]) {
                hits++;
                rb->fdprintf(fd,"%s\n",getfilename(i));
            }
        rb->close(fd);
    }
    rb->snprintf(buf,250,"Hits: %d",hits);
    rb->splash(HZ*3,buf);
    if (result!=0) {
        /* Return PLUGIN_USB_CONNECTED to force a file-tree refresh */
        return PLUGIN_USB_CONNECTED;
    }
    return PLUGIN_OK;
}
Esempio n. 27
0
File: tcp.c Progetto: binarylu/cs631
/*
 * Read the source file and copy its content to the target file. Source file can
 * not be a directory.
 */
int
main(int argc, char *argv[])
{
    int fdr, fdw, fddir;
    int n;
    char buf[BUFFSIZE];

    char *src = argv[1];
    char *dst = argv[2];
    struct stat st_src, st_dst;

    setprogname(argv[0]);

    if (argc != 3) {
        fprintf(stderr, "Wrong argument number!\n");
        exit(EXIT_FAILURE);
    }
    
    /* Source file can not be a directory */
    if (stat(src, &st_src) < 0) {
        perror("Fail to access SOURCE");
        exit(EXIT_FAILURE);
    }
    if (S_ISDIR(st_src.st_mode)) {
        fprintf(stderr, "SOURCE cannot be a directory\n");
        exit(EXIT_FAILURE);
    }

    /* Open the source file as a regular file */
    if ((fdr = open(src, O_RDONLY)) == -1) {
        perror("Fail to read SOURCE");
        exit(EXIT_FAILURE);
    }

    /*
     * Create a new file with the specified name that user give if the target
     * file is a regular file or does not exist. If the target is a directory,
     * createa new file named the same name with source file under this
     * directory. 
     */
    if ((fddir = open(dst, O_RDONLY | O_DIRECTORY)) == -1) {
        if (dst[strlen(dst) - 1] == '/') {
            /*
             * If the target file name followed by '/', must open it as a
             * directory.
             */
            fprintf(stderr, "cannot create regular file '%s': Not a directory\n", dst);
            exit(EXIT_FAILURE);
        }
        if ((fdw = open(dst, O_WRONLY | O_CREAT | O_TRUNC,  S_IRUSR | S_IWUSR)) == -1) {
            /*
             * If the target is not a directory and not followed by '/', create
             * it.
             */
            fprintf(stderr, "Unable to open target file '%s': %s\n", dst, strerror(errno));
            exit(EXIT_FAILURE);
        }
    } else {
        /*
         * The target is a directory if it can be opened as a directory.
         */
        close(fddir);
        const char *filename;
        /* Generate a new filename combining path and filename */
        getfilename(src, &filename);
        strcat(dst, "/");
        strcat(dst, filename);
        if ((fdw = open(dst, O_WRONLY | O_CREAT | O_TRUNC,  S_IRUSR | S_IWUSR)) == -1) {
            fprintf(stderr, "Unable to open target file '%s': %s\n", dst, strerror(errno));
            exit(EXIT_FAILURE);
        }
    }

    if (fstat(fdw, &st_dst) < 0) {
        perror("Fail to access TARGET");
        exit(EXIT_FAILURE);
    }
    /* Source file and target file can not be the same files. */
    if (st_src.st_ino == st_dst.st_ino) {
        fprintf(stderr, "'%s' and '%s' are the same file\n", src , dst);
    }

    /* Read the source file contents and write to the target file. */
    while ((n = read(fdr, buf, BUFFSIZE)) > 0) {
        if (write(fdw, buf, n) != n) {
            fprintf(stderr, "Copy failed!\n");
            exit(EXIT_FAILURE);
        }
    }
    if (n < 0) {
        fprintf(stderr, "read error\n");
        exit(EXIT_FAILURE);
    }

    close(fdr);
    close(fdw);
    return 0;
}
Esempio n. 28
0
void CardReader::openFile(char* name, bool read, bool replace_current/*=true*/) {
  if (!cardOK) return;
  if (file.isOpen()) { //replacing current file by new file, or subfile call
    if (!replace_current) {
     if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
       SERIAL_ERROR_START;
       SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
       SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
       kill();
       return;
     }

     SERIAL_ECHO_START;
     SERIAL_ECHOPGM("SUBROUTINE CALL target:\"");
     SERIAL_ECHO(name);
     SERIAL_ECHOPGM("\" parent:\"");

     //store current filename and position
     getAbsFilename(filenames[file_subcall_ctr]);

     SERIAL_ECHO(filenames[file_subcall_ctr]);
     SERIAL_ECHOPGM("\" pos");
     SERIAL_ECHOLN(sdpos);
     filespos[file_subcall_ctr] = sdpos;
     file_subcall_ctr++;
    }
    else {
     SERIAL_ECHO_START;
     SERIAL_ECHOPGM("Now doing file: ");
     SERIAL_ECHOLN(name);
    }
    file.close();
  }
  else { //opening fresh file
    file_subcall_ctr = 0; //resetting procedure depth in case user cancels print while in procedure
    SERIAL_ECHO_START;
    SERIAL_ECHOPGM("Now fresh file: ");
    SERIAL_ECHOLN(name);
  }
  sdprinting = false;

  SdFile myDir;
  curDir = &root;
  char *fname = name;

  char *dirname_start, *dirname_end;
  if (name[0] == '/') {
    dirname_start = &name[1];
    while(dirname_start > 0) {
      dirname_end = strchr(dirname_start, '/');
      //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start - name));
      //SERIAL_ECHO("end  :");SERIAL_ECHOLN((int)(dirname_end - name));
      if (dirname_end > 0 && dirname_end > dirname_start) {
        char subdirname[FILENAME_LENGTH];
        strncpy(subdirname, dirname_start, dirname_end - dirname_start);
        subdirname[dirname_end - dirname_start] = 0;
        SERIAL_ECHOLN(subdirname);
        if (!myDir.open(curDir, subdirname, O_READ)) {
          SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
          SERIAL_PROTOCOL(subdirname);
          SERIAL_PROTOCOLCHAR('.');
          return;
        }
        else {
          //SERIAL_ECHOLN("dive ok");
        }

        curDir = &myDir;
        dirname_start = dirname_end + 1;
      }
      else { // the remainder after all /fsa/fdsa/ is the filename
        fname = dirname_start;
        //SERIAL_ECHOLN("remainder");
        //SERIAL_ECHOLN(fname);
        break;
      }
    }
  }
  else { //relative path
    curDir = &workDir;
  }

  if (read) {
    if (file.open(curDir, fname, O_READ)) {
      filesize = file.fileSize();
      SERIAL_PROTOCOLPGM(MSG_SD_FILE_OPENED);
      SERIAL_PROTOCOL(fname);
      SERIAL_PROTOCOLPGM(MSG_SD_SIZE);
      SERIAL_PROTOCOLLN(filesize);
      sdpos = 0;

      SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED);
      getfilename(0, fname);
      lcd_setstatus(longFilename[0] ? longFilename : fname);
    }
    else {
      SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
      SERIAL_PROTOCOL(fname);
      SERIAL_PROTOCOLCHAR('.');
    }
  }
  else { //write
    if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
      SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
      SERIAL_PROTOCOL(fname);
      SERIAL_PROTOCOLCHAR('.');
    }
    else {
      saving = true;
      SERIAL_PROTOCOLPGM(MSG_SD_WRITE_TO_FILE);
      SERIAL_PROTOCOLLN(name);
      lcd_setstatus(fname);
    }
  }
}
Esempio n. 29
0
void CardReader::openFile(char* name, bool read, bool replace_current/*=true*/, bool lcd_status/*=true*/) {
  if (!cardOK) return;
  if (file.isOpen()) { //replacing current file by new file, or subfile call
    if (!replace_current) {
      if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
        ECHO_LMV(ER, MSG_SD_MAX_DEPTH, SD_PROCEDURE_DEPTH);
        kill(PSTR(MSG_KILLED));
        return;
      }

      ECHO_SMV(DB, "SUBROUTINE CALL target:\"", name);
      ECHO_M("\" parent:\"");

      //store current filename and position
      getAbsFilename(filenames[file_subcall_ctr]);

      ECHO_V(filenames[file_subcall_ctr]);
      ECHO_EMV("\" pos", sdpos);
      filespos[file_subcall_ctr] = sdpos;
      file_subcall_ctr++;
    }
    else {
     ECHO_LMV(DB, "Now doing file: ", name);
    }
    file.close();
  }
  else { // opening fresh file
    file_subcall_ctr = 0; // resetting procedure depth in case user cancels print while in procedure
    ECHO_LMV(DB, "Now fresh file: ", name);
  }
  sdprinting = false;

  SdFile myDir;
  curDir = &root;
  char *fname = name;

  char *dirname_start, *dirname_end;
  if (name[0] == '/') {
    dirname_start = &name[1];
    while (dirname_start > 0) {
      dirname_end = strchr(dirname_start, '/');
      if (dirname_end > 0 && dirname_end > dirname_start) {
        char subdirname[FILENAME_LENGTH];
        strncpy(subdirname, dirname_start, dirname_end - dirname_start);
        subdirname[dirname_end - dirname_start] = 0;
        ECHO_EV(subdirname);
        if (!myDir.open(curDir, subdirname, O_READ)) {
          ECHO_MV(MSG_SD_OPEN_FILE_FAIL, subdirname);
          ECHO_C('.');
          return;
        }
        else {
          //ECHO_EM("dive ok");
        }

        curDir = &myDir;
        dirname_start = dirname_end + 1;
      }
      else { // the remainder after all /fsa/fdsa/ is the filename
        fname = dirname_start;
        //ECHO_EM("remainder");
        //ECHO_EV(fname);
        break;
      }
    }
  }
  else { //relative path
    curDir = &workDir;
  }

  if (read) {
    if (file.open(curDir, fname, O_READ)) {
      filesize = file.fileSize();
      ECHO_MV(MSG_SD_FILE_OPENED, fname);
      ECHO_EMV(MSG_SD_SIZE, filesize);
      sdpos = 0;

      ECHO_EM(MSG_SD_FILE_SELECTED);
      getfilename(0, fname);
      if(lcd_status) lcd_setstatus(longFilename[0] ? longFilename : fname);
    }
    else {
      ECHO_MV(MSG_SD_OPEN_FILE_FAIL, fname);
      ECHO_PGM(".\n");
    }
  }
  else { //write
    if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
      ECHO_MV(MSG_SD_OPEN_FILE_FAIL, fname);
      ECHO_PGM(".\n");
    }
    else {
      saving = true;
      ECHO_EMV(MSG_SD_WRITE_TO_FILE, name);
      if(lcd_status) lcd_setstatus(fname);
    }
  }
}
Esempio n. 30
0
File: sflmail.c Progetto: KubaO/gsl
int smtp_send_mail_ex (
   SMTP *smtp)
{
   FILE
      *fpin;
   int
       iCnt;
   sock_t
       socket_handle;
   char
       message_boundary [256],
       strOut           [514],
       strFile          [256],
       strUUEFile       [256],
       buffer           [BUFFER_SIZE + 1],
      *charset,
      *nb_bit,
      *data,
      *p_buffer,
      *strRcptUserIds;
   Bool
       old_ip_nonblock = ip_nonblock;
   int
       rcptUserIdsLen;
  long
      current_date,
      current_time,
      out_size,
      in_size;
  char
     *quoted_subject = NULL,
     *in_buf,
     *out_buf;

   /* Check required parameters                                              */
   if (smtp == NULL)
       return (SMTP_ERROR_CONNECT);
   if (smtp->strDestUserIds == NULL)
       return (SMTP_ERROR_MISSING_DESTINATION);
   if (smtp->strSubject == NULL)
       return (SMTP_ERROR_MISSING_SUBJECT);
   if (smtp->strSmtpServer == NULL)
       return (SMTP_ERROR_MISSING_SERVER_NAME);

   /*  Make sure we block on socket accesses                                 */
   ip_nonblock = FALSE;
   sock_init ();

   /* Open up the SMTP port (25 most of the time). */

   if (smtp-> connect_retry_cnt < 1)
       smtp-> connect_retry_cnt = 3;

   nb_bit = "7";

   if (smtp-> strCharSet == NULL 
   || *smtp-> strCharSet == '\0')
       charset = "US-ASCII";
   else
     {
       charset = smtp-> strCharSet;
       nb_bit = "8";
       if (smtp-> strSubject)
         {
           if (lexcmp (charset, "iso-2022-jp") == 0
           ||  lexcmp (charset, "shift_jis")   == 0
           ||  lexcmp (charset, "utf-8")       == 0) {
               quoted_subject = encode_mimeb_string (NULL, 0,
                                                  (byte *) smtp->strSubject, charset);
           }
           else
               quoted_subject = encode_quoted_string (NULL, 0,
                                                  (byte *) smtp->strSubject, charset);
         }
     }
   socket_handle = connect_socket (smtp-> strSmtpServer,
                                   "smtp", "tcp", NULL,
                                   smtp-> connect_retry_cnt,
                                   smtp-> retry_wait_time);

   if (socket_handle == INVALID_SOCKET
   ||  getreply (socket_handle, smtp) > SMTP_SERVER_ERROR)
     {
       mem_strfree  (&quoted_subject);
       sock_term ();
       return (SMTP_ERROR_CONNECT);
     }

   /* Format a SMTP meassage header.                                         */
   /* Just say hello to the mail server.                                     */
   xstrcpy (strOut, "HELO ", get_hostname (), "\r\n", NULL);
   send_data (socket_handle, strOut);
   if (getreply (socket_handle, smtp) > SMTP_SERVER_ERROR)
     {
       CLEAN_SEND_MAIL;
       return (SMTP_ERROR_INIT);
     }
   /* Tell the mail server who the message is from. */
   xstrcpy (strOut, "MAIL FROM:<", smtp-> strSenderUserId, ">\r\n", NULL);
   send_data (socket_handle, strOut);
   if (getreply (socket_handle, smtp) > SMTP_SERVER_ERROR)
     {
       CLEAN_SEND_MAIL;
       return (SMTP_ERROR_INVALID_SENDER);
     }
   rcptUserIdsLen = 0;
   if (smtp-> strDestUserIds)
       rcptUserIdsLen += strlen (smtp->strDestUserIds) + 1;
   if (smtp-> strCcUserIds)
       rcptUserIdsLen += strlen (smtp->strCcUserIds)   + 1;
   if (smtp-> strBccUserIds)
       rcptUserIdsLen += strlen (smtp->strBccUserIds)  + 1;

   strRcptUserIds = (char *) mem_alloc (rcptUserIdsLen);
   p_buffer = strRcptUserIds;
   data = smtp-> strDestUserIds;
   while (*data)
       *p_buffer++ = *data++;
   if (smtp-> strCcUserIds)
     {
       *p_buffer++ = ';';
       data = smtp-> strCcUserIds;
       while (*data)
           *p_buffer++ = *data++;
     }
   if (smtp-> strBccUserIds)
     {
       *p_buffer++ = ';';
       data = smtp-> strBccUserIds;
       while (*data)
           *p_buffer++ = *data++;
     }
   *p_buffer = '\0';

   /* The following tells the mail server who to send it to.                 */
   iCnt = 0;
   if (*strRcptUserIds) {
       FOREVER
         {
            getstrfld (strRcptUserIds, iCnt++, 0, ",;", buffer);
            if (*buffer)
             {
               xstrcpy (strOut, "RCPT TO:<", buffer, ">\r\n", NULL);
               send_data (socket_handle, strOut);
               if (getreply (socket_handle, smtp) > SMTP_SERVER_ERROR)
                 {
                   CLEAN_SEND_MAIL;
                   return (SMTP_ERROR_INVALID_RECEIPT_USER);
                 }
             }

           else
               break;
         }
    }
    mem_free (strRcptUserIds);

   /* Now give it the Subject and the message to send.                       */
   send_data (socket_handle, "DATA\r\n");
   if (getreply (socket_handle, smtp) > SMTP_SERVER_ERROR)
     {
       CLEAN_SEND_MAIL;
       return (SMTP_ERROR_INVALID_DATA);
     }

   /* Set the date and time of the message.                                  */
   get_date_time_now (&current_date, &current_time);
   xstrcpy ( strOut, "Date: ", encode_mime_time (current_date, current_time),
             " \r\n", NULL );

   /* The following shows all who it was sent to. */
   if ( smtp-> strFullDestUserIds && *smtp-> strFullDestUserIds )
    {
       replacechrswith (smtp-> strFullDestUserIds, ";", ',');
       xstrcat (strOut, "To: ", smtp-> strFullDestUserIds, "\r\n", NULL);
     }
   else
    {
       replacechrswith (smtp-> strDestUserIds, ";", ',');
       xstrcat (strOut, "To: ", smtp-> strDestUserIds, "\r\n", NULL);
    }

   /* Set up the Reply-To path. */
   if (!smtp-> strRetPathUserId || !*smtp-> strRetPathUserId)
       smtp-> strRetPathUserId = smtp-> strSenderUserId;

   if ( strstr( smtp-> strRetPathUserId, "<" ) != NULL &&
        strstr( smtp-> strRetPathUserId, ">" ) != NULL )
       xstrcat (strOut, "Reply-To:",  smtp-> strRetPathUserId, "\r\n", NULL);
   else
       xstrcat (strOut, "Reply-To:<", smtp-> strRetPathUserId, ">\r\n", NULL);

   if ( smtp-> strFullSenderUserId && *smtp-> strFullSenderUserId )
     {
       xstrcat (strOut, "Sender: ", smtp-> strFullSenderUserId, "\r\n", NULL);
       xstrcat (strOut, "From: ",   smtp-> strFullSenderUserId, "\r\n", NULL);
     }
   else
     {
       xstrcat (strOut, "Sender: ", smtp-> strSenderUserId, "\r\n", NULL);
       xstrcat (strOut, "From: ",   smtp-> strSenderUserId, "\r\n", NULL);
     }
   send_data (socket_handle, strOut);

   *strOut = '\0';

   /* Post any CC's. */
   if (smtp->strFullCcUserIds && *smtp->strFullCcUserIds)
     {
       replacechrswith (smtp->strFullCcUserIds, ";", ',');
       xstrcat (strOut, "Cc:", smtp->strFullCcUserIds, "\r\n", NULL );
     }
   else
   if (smtp->strCcUserIds && *smtp->strCcUserIds)
     {
       replacechrswith (smtp->strCcUserIds, ";", ',');
       xstrcat (strOut, "Cc:", smtp->strCcUserIds, "\r\n", NULL );
     }

   /* Post any BCC's. */
   if (smtp->strFullBccUserIds && *smtp->strFullBccUserIds)
     {
       replacechrswith (smtp->strFullBccUserIds, ";", ',');
       xstrcat (strOut, "Bcc:", smtp->strFullBccUserIds, "\r\n", NULL);
     }
   else
   if (smtp->strBccUserIds && *smtp->strBccUserIds)
     {
       replacechrswith (smtp->strBccUserIds, ";", ',');
       xstrcat (strOut, "Bcc:", smtp->strBccUserIds, "\r\n", NULL);
     }
   /* Post any Return-Receipt-To. */
   if (smtp->strRrcpUserId && *smtp->strRrcpUserId)
       xstrcat (strOut, "Return-Receipt-To:", smtp->strRrcpUserId, ">\r\n",
                NULL);

   if (smtp->strMailerName && *smtp->strMailerName)
       xstrcat (strOut, "X-Mailer: ", smtp->strMailerName, "\r\n", NULL);
   else
       strcat  (strOut, "X-Mailer: sflmail function\r\n");

   /* Set the mime version. */
   get_date_time_now (&current_date, &current_time);
   sprintf (message_boundary, "%s.%ld.%ld", MESSAGE_BOUNDARY,
            current_date, current_time);

   if ( smtp->strHtmlMessageBody && *smtp->strHtmlMessageBody )
       xstrcat (strOut, "MIME-Version: 1.0\r\n",
                "Content-Type: multipart/alternative; boundary=\"", 
	            message_boundary,"\"\r\n", NULL);
   else
       xstrcat (strOut, "MIME-Version: 1.0\r\n",
                "Content-Type: Multipart/Mixed; boundary=\"", 
	            message_boundary,"\"\r\n", NULL);

   send_data (socket_handle, strOut);

   *strOut = '\0';
   /* Write out any message comment included. */
   if (smtp->strMsgComment && *smtp->strMsgComment)
       xstrcpy (strOut, "Comments: ", smtp->strMsgComment, "\r\n", NULL);

   /* Send the subject and message body. */
   if (quoted_subject)
       xstrcat (strOut, "Subject: ", quoted_subject, "\r\n\r\n", NULL);
   else
       xstrcat (strOut, "Subject: ", smtp->strSubject, "\r\n\r\n", NULL);
   send_data (socket_handle, strOut);

   /* Keep rfc822 in mind with all the sections.                             */
    if (smtp->strMessageBody && *smtp->strMessageBody)
      {
        /* check if we got html/alternate files                               */
        if ( smtp->strHtmlMessageBody && *smtp->strHtmlMessageBody )
          {
           xstrcpy (strOut,
                     "\r\n\r\n--", message_boundary, "\r\n",
                     "Content-Type: text/html; charset=", charset, "\r\n",
                     "Content-Transfer-Encoding: 7BIT\r\n",
                     "Content-description: Body of message\r\n\r\n", NULL);
           send_data (socket_handle, strOut);
           send_body (socket_handle, smtp->strHtmlMessageBody);
           send_data (socket_handle, "\r\n");
           xstrcpy (strOut,
                    "\r\n--", message_boundary, "\r\n",
                    "Content-Type: text/plain; charset=", charset, "\r\n",
                    "Content-Transfer-Encoding: ", nb_bit, "BIT\r\n",
                    "Content-description: Body of message\r\n\r\n", NULL);
           send_data (socket_handle, strOut);
           send_body (socket_handle, smtp-> strMessageBody);
           send_data (socket_handle, "\r\n");

         }
       else
         {
           xstrcpy (strOut,
                    "\r\n--", message_boundary, "\r\n",
                    "Content-Type: text/plain; charset=", charset, "\r\n",
                    "Content-Transfer-Encoding: ", nb_bit, "BIT\r\n",
                    "Content-description: Body of message\r\n\r\n", NULL);
           send_data (socket_handle, strOut);
           send_body (socket_handle, smtp-> strMessageBody);
           send_data (socket_handle, "\r\n");
         }
     }
   /* Include any Text type files and Attach them to the message. */
   if (smtp->strTxtFiles && *smtp->strTxtFiles)
     {
       iCnt = 0;
       FOREVER
         {
           getstrfld (smtp->strTxtFiles, iCnt++, 0, ",;", strFile);
           strcrop (strskp (strFile));
           if (*strFile)
             {
               fpin = fopen (strFile, "rb");
               if (!fpin)
                 {
                   strcpy (smtp->strlast_smtp_message, strFile);
                     {
                       CLEAN_SEND_MAIL;
                       return (SMTP_ERROR_MISSING_ATTACH_FILE);
                     }
                 }

               xstrcpy (strOut, "\r\n--", message_boundary, "\r\n",
                       "Content-Type: text/plain; charset=", charset, "\r\n",
                       "Content-Transfer-Encoding: ", nb_bit, "BIT\r\n",
                       "Content-Disposition: attachment; filename=",
                        getfilename (strFile), "\r\n\r\n", NULL);
               send_data (socket_handle, strOut);
               while (fgets (buffer, BUFFER_SIZE, fpin))
                 {
                   if (*buffer == '.')
                       write_TCP (socket_handle, ".", 1);
                   send_data (socket_handle, buffer);
                 }
               fclose (fpin);
             }
           else
               break;
         }
     }