예제 #1
0
int guiPlaylistInitialize(play_tree_t *my_playtree, m_config_t *config, int enqueue)
{
    play_tree_iter_t *my_pt_iter = NULL;
    int result = 0;

    if(!mygui) guiInit();

    if((my_pt_iter = pt_iter_create(&my_playtree, config)))
    {
        while ((filename = pt_iter_get_next_file(my_pt_iter)) != NULL)
        {
            if (parse_filename(filename, my_playtree, config, 0))
                result = 1;
            else if (import_file_into_gui(filename, 0)) /* Add it to end of list */
                result = 1;
        }
    }
    uiGotoTheNext = 1;

    if (result)
    {
        mygui->playlist->current = 0;
        uiSetFileName(NULL, mygui->playlist->tracks[0]->filename, STREAMTYPE_FILE);
    }

    if (enqueue) filename = NULL;

    return result;
}
예제 #2
0
/* Creates a file named NAME with the given INITIAL_SIZE.
   Returns true if successful, false otherwise.
   Fails if a file named NAME already exists,
   or if internal memory allocation fails. */
bool
filesys_create (const char *name, off_t initial_size, enum file_type type) 
{
  block_sector_t inode_sector = 0;

  char * parse = parse_filename (name); 
  //get the correct dir

  struct dir *dir = dir_lookup_rec (parse);

  bool success = (dir != NULL
                  && free_map_allocate (1, &inode_sector)
                  && inode_create (inode_sector, initial_size, type)
                  && dir_add (dir, parse, inode_sector));

  if (!success && inode_sector != 0) 
    free_map_release (inode_sector, 1);
  if( success == true && type == FILE_DIR ) {
	//we want to add . and .. as well if it is a dir
		//open the created directory
		struct file * created = filesys_open(parse);
		struct dir * mydir = dir_open(file_get_inode (created));
		//add . to it
		dir_add (mydir, ".", inode_sector);
		struct inode * parent = dir_get_inode (dir);
		block_sector_t inode_sector_parent = inode_id(parent);
		//add .. to it
		dir_add (mydir, "..", inode_sector_parent);
		dir_close(mydir);
		file_close(created);
  }
  dir_close (dir);

  return success;
}
void display_loadplaylistwindow(gui_t *gui)
{
    OPENFILENAME playlistopen;
    char playlistfile[MAX_PATH];

    memset(&playlistopen, 0, sizeof(OPENFILENAME));
    memset(playlistfile, 0, sizeof(playlistfile));

    playlistopen.lStructSize = sizeof(OPENFILENAME);
    playlistopen.hwndOwner = gui->mainwindow;
    playlistopen.hInstance = GetModuleHandle(NULL);
    playlistopen.lpstrFilter = "All Files (*.*)\0*.*\0"
                               "Playlist Files (*.m3u;*.pls;*.txt)\0*.m3u;*.pls;*.txt\0";
    playlistopen.nFilterIndex = 0;
    playlistopen.lpstrTitle = "Load Playlist...";
    playlistopen.Flags = OFN_FILEMUSTEXIST | OFN_LONGNAMES | OFN_EXPLORER | OFN_READONLY | OFN_HIDEREADONLY;
    playlistopen.lpstrFile = playlistfile;
    playlistopen.lpstrCustomFilter = NULL;
    playlistopen.nMaxFile = MAXFILE;

    if(GetOpenFileName(&playlistopen))
    {
        if(parse_filename(playlistfile, playtree, mconfig, 1))
            gui->startplay(gui);
    }
}
예제 #4
0
파일: sf.c 프로젝트: heuripedes/sf
static size_t header_func(const void *ptr, size_t size, size_t nmemb, void *data) {
    (void)data;

    if (!file_name[0])
        parse_filename((char*)ptr, size * nmemb);

    return size * nmemb;
}
예제 #5
0
파일: cmdmisc.c 프로젝트: ak-ymst/mruby
static mrb_bool
parse_listcmd_args(mrb_state *mrb, mrdb_state *mrdb, listcmd_parser_state *st)
{
  char *p;

  switch (mrdb->wcnt) {
  case 2:
    p = mrdb->words[1];

    /* mrdb->words[1] ::= <lineno> | <filename> ':' <lineno> | <filename> */
    if (!parse_lineno(mrb, &p, st)) {
      if (parse_filename(mrb, &p, st)) {
        if (skip_char(&p, ':')) {
          if (!parse_lineno(mrb, &p, st)) {
            st->parse_error = TRUE;
          }
        }
      }
      else {
        st->parse_error = TRUE;
      }
    }
    if (*p != '\0') {
      st->parse_error = TRUE;
    }
    break;
  case 1:
  case 0:
    /* do nothing */
    break;
  default:
    st->parse_error = TRUE;
    printf("too many arguments\n");
    break;
  }

  if (!st->parse_error) {
    if (!st->has_line_min) {
      st->line_min = (!st->filename && mrdb->dbg->prvline > 0) ? mrdb->dbg->prvline : 1;
    }

    if (!st->has_line_max) {
      st->line_max = st->line_min + 9;
    }

    if (st->filename == NULL) {
      if (mrdb->dbg->prvfile && strcmp(mrdb->dbg->prvfile, "-")) {
        st->filename = replace_ext(mrb, mrdb->dbg->prvfile, ".rb");
      }
    }
  }

  if (st->parse_error || st->filename == NULL) {
    return FALSE;
  }

  return TRUE;
}
예제 #6
0
static int parse_line( char* in, M3u_Playlist::entry_t& entry )
{
	int result = 0;
	
	// file
	entry.file = in;
	entry.type = "";
	in = parse_filename( in, entry );
	
	// track
	entry.track = -1;
	entry.decimal_track = 0;
	in = parse_track( in, entry, &result );
	
	// name
	entry.name = in;
	in = parse_name( in );
	
	// time
	entry.length = -1;
	in = parse_time( in, &entry.length, &result );
	
	// loop
	entry.intro = -1;
	entry.loop  = -1;
	if ( *in == '-' )
	{
		entry.loop = entry.length;
		in++;
	}
	else
	{
		in = parse_time_( in, &entry.loop );
		if ( entry.loop >= 0 )
		{
			entry.intro = entry.length - entry.loop;
			if ( *in == '-' ) // trailing '-' means that intro length was specified 
			{
				in++;
				entry.intro = entry.loop;
				entry.loop  = entry.length - entry.intro;
			}
		}
	}
	in = next_field( in, &result );
	
	// fade
	entry.fade = -1;
	in = parse_time( in, &entry.fade, &result );
	
	// repeat
	entry.repeat = -1;
	in = parse_int( in, &entry.repeat, &result );
	
	return result;
}
int send_file_tcp(char *filepath, int socket_descriptor)
{
    int totalBytesSent = 0;
    char buffer[BUFFER_SIZE];
    FILE *fd;
    int file_size = fsize(filepath);
    int bytes_read;

    fd = fopen(filepath, "r");

    if (fd == NULL || file_size < 1)
        return -1;

    // Send filename
    char *filename = parse_filename(filepath);
    strcpy(buffer, filename);
    send(socket_descriptor, buffer, BUFFER_SIZE, 0);
    free(filename);
    // Send file size
    itoa(file_size, buffer);
    send(socket_descriptor, buffer, BUFFER_SIZE, 0);

    // number of file data sending iterations between sending out-of-band data
    int oob_count = (file_size / BUFFER_SIZE) / 5;

    // Send file data
    int i = 0;                  // file data sending iterations counter
    while (1) {
        bytes_read = fread(buffer, sizeof(unsigned char), BUFFER_SIZE, fd);

        if (bytes_read <= 0)
            break;

        if (send(socket_descriptor, buffer, bytes_read, 0) == -1) {
            fclose(fd);
            return -1;
        }

        totalBytesSent += bytes_read;

        // Generate out-of-band data
        if (oob_count > 0 && ++i % oob_count == 0) {
            printf("sent %d bytes\n", totalBytesSent);

            if (send(socket_descriptor, "Z", 1, MSG_OOB) == -1)
                perror("send OOB error");
        }

        if (bytes_read < BUFFER_SIZE)
            break;
    }

    printf("Total bytes sent: %d\n", totalBytesSent);
    fclose(fd);
    return 0;
}
예제 #8
0
int guiPlaylist (int what, play_tree_t *playtree, m_config_t *config, int enqueue)
{
    play_tree_iter_t *pt_iter = NULL;
    char *file;
    int added = FALSE;

    switch (what)
    {
        /*  This function imports the initial playtree (based on cmd-line files) into the gui playlist
            by either:
            - overwriting gui pl (enqueue=0) */
        case GUI_PLAYLIST_INIT:

            if(!mygui) guiInit();

            if((pt_iter = pt_iter_create(&playtree, config)))
            {
                while ((file = pt_iter_get_next_file(pt_iter)) != NULL)
                {
                    if (parse_filename(file, playtree, config, 0))
                        added = TRUE;
                    else if (import_file_into_gui(file, 0)) /* Add it to end of list */
                        added = TRUE;
                }
            }
            guiInfo.PlaylistNext = TRUE;

            if (added)
            {
                mygui->playlist->current = 0;
                uiSetFile(NULL, mygui->playlist->tracks[0]->filename, STREAMTYPE_FILE);
            }

            if (enqueue) filename = NULL;

            break;

        /* This function imports and inserts an playtree, that is created "on the fly", for example by
           parsing some MOV-Reference-File; or by loading an playlist with "File Open"
           The file which contained the playlist is thereby replaced with it's contents. */
        case GUI_PLAYLIST_ADD:

            if((pt_iter = pt_iter_create(&playtree, config)))
            {
                while ((file = pt_iter_get_next_file(pt_iter)) != NULL)
                    if (import_file_into_gui(file, 1)) /* insert it into the list and set plCurrent = new item */
                        added = TRUE;
                pt_iter_destroy(&pt_iter);
            }

            break;
    }

    return added;
}
예제 #9
0
/* Deletes the file named NAME.
   Returns true if successful, false on failure.
   Fails if no file named NAME exists,
   or if an internal memory allocation fails. */
bool
filesys_remove (const char *name) 
{
  char * parse = parse_filename (name); 
  //get the correct dir
  struct dir *dir = dir_lookup_rec (parse);

  bool success = dir != NULL && dir_remove (dir, parse);
  dir_close (dir); 

  return success;
}
예제 #10
0
파일: pathinfo.c 프로젝트: robgarv/ulppk2
/*
 * Parse a file path and return a structure containing its
 * components.
 *
 * This function takes a file path (e.g. /var/tmp/myexample.txt)
 * and produces a structure containing points to the path elements.
 *
 * typedef struct _PATHINFO_STRUCT {
 *	char* fullpath;
 *	char* filename;
 *	char* dirpath;
 *	char* extension;
 *	int isdir;
 * } PATHINFO_STRUCT;
 *
 * The PATHINFO_STRUCT structure is allocated from the heap, as are
 * the strings pointed two by its members. This memory must be
 * returned to the heap by calling pathinfo_release, passing a pointer
 * to the PATHINFO_STRUCT returned by pathinfo_parse.
 */
PATHINFO_STRUCT* pathinfo_parse_filepath(const char* pathname) {
	DQHEADER deque;
	PATHINFO_STRUCT* pathinfop;
	char* pathdelim = "/";
	char* pathbuff;
	char* tokenp = NULL;
	char* token_aheadp = NULL;
	int isdir = 0;

	// Get a pathinfo structure
	pathinfop = calloc(1, sizeof(PATHINFO_STRUCT));
	pathinfop->fullpath = strdup(pathname);
	// Initialize a plenty big deque to hold path components.
	dq_init(strlen(pathname) + 1, sizeof(char), &deque);

	// Break the file path into tokens. Copy to a working buffer
	// so we don't alter path with calls to strtok
	pathbuff = strdup(pathname);

	// Check for leading /
	if (pathbuff[0] == '/') {
		push_token(&deque, "/");
	}
	isdir = pathinfo_is_dir(pathname);
	pathinfop->isdir = isdir;

	// Get first token and look ahead token
	tokenp = strtok(pathbuff, pathdelim);
	token_aheadp = strtok(NULL, pathdelim);
	while (tokenp != NULL) {
		if (token_aheadp != NULL) {
			// More tokens in path string
			push_token(&deque, tokenp);
			push_token(&deque, "/");
			tokenp = token_aheadp;
			token_aheadp = strtok(NULL, pathdelim);
		} else {
			// tokenp is the last token in the sequence
			if (!isdir) {
				parse_filename(pathinfop, tokenp);
			} else {
				push_token(&deque, tokenp);
			}
			tokenp = NULL;
		}
	}
	set_dirpath(pathinfop, &deque);
	free(pathbuff);
	return pathinfop;
}
예제 #11
0
int send_file_udp(char *filepath, int socket_descriptor)
{
    int totalBytesSent = 0;
    char buffer[BUFFER_SIZE];
    FILE *fd;
    int file_size = fsize(filepath);
    int bytes_read;

    fd = fopen(filepath, "r");

    if (fd == NULL || file_size < 1)
        return -1;

    // Send filename
    char *filename = parse_filename(filepath);
    strcpy(buffer, filename);
    send(socket_descriptor, buffer, BUFFER_SIZE, 0);
    free(filename);
    // Send file size
    itoa(file_size, buffer);
    send(socket_descriptor, buffer, BUFFER_SIZE, 0);

    // Send file data
    while (1) {
        bytes_read = fread(buffer, sizeof(unsigned char), BUFFER_SIZE, fd);

        if (bytes_read <= 0)
            break;

        if (send(socket_descriptor, buffer, bytes_read, 0) == -1) {
            fclose(fd);
            return -1;
        }

		// Wait reply
		if (recv(socket_descriptor, buffer, 1, 0) < 1) {
			fclose(fd);
			return -1;
		}

        totalBytesSent += bytes_read;
        printf("%d bytes sent\n", totalBytesSent);
    }

    printf("Total bytes sent: %d\n", totalBytesSent);
    fclose(fd);
    return 0;
}
예제 #12
0
/* Opens the file with the given NAME.
   Returns the new file if successful or a null pointer
   otherwise.
   Fails if no file named NAME exists,
   or if an internal memory allocation fails. */
struct file *
filesys_open (const char *name)
{

  char * parse = parse_filename (name); 
  //get the correct dir
  struct dir *dir = dir_lookup_rec (parse);

  struct inode *inode = NULL;

  if (dir != NULL)
    dir_lookup (dir, parse, &inode);
  dir_close (dir);

  return file_open (inode);
}
예제 #13
0
/** Match the same underlying file, and device files with the same name. */
static Bool blobdata_file_same(const OBJECT *newo, const OBJECT *cached)
{
  FILELIST *newflptr ;

  HQASSERT(newo && cached, "Objects missing for file comparison") ;
  HQASSERT(oType(*newo) == OFILE, "Blob data source is not a file") ;
  HQASSERT(oType(*cached) == OFILE || oType(*cached) == OSTRING,
           "Blob data source is not a file or a filename") ;

  newflptr = oFile(*newo) ;
  HQASSERT(newflptr, "No filelist in file object") ;

  /* Object identity has already been checked. The file is the same if:
     1) The file pointers are the same
     2) The file names and devices of the files are the same
     3) The file name and device of the new file match a filename */
  if ( oType(*cached) == OFILE ) {
    FILELIST *oldflptr = oFile(*cached) ;

    if ( oldflptr == newflptr )
      return TRUE ;

    if ( theIDeviceList(oldflptr) != NULL &&
         theIDeviceList(oldflptr) == theIDeviceList(newflptr) &&
         HqMemCmp(theICList(oldflptr), theINLen(oldflptr),
                  theICList(newflptr), theINLen(newflptr)) == 0 )
      return TRUE ;
  } else if ( oType(*cached) == OSTRING ) {
    if ( theIDeviceList(newflptr) != NULL ) {
      uint8 *filename, *devicename ;

      /* file_open stores the filename in a FILELIST as a C-string (zero
         terminated), so we can use strcmp to compare it. */
      if ( parse_filename(oString(*cached), theLen(*cached),
                          &devicename, &filename) == DEVICEANDFILE &&
           strcmp((const char *)theIDevName(theIDeviceList(newflptr)),
                  (const char *)devicename) == 0 &&
           strcmp((const char *)theICList(newflptr),
                  (const char *)filename) == 0 )
        return TRUE ;
    }
  }

  return FALSE ;
}
예제 #14
0
/*
 * Parse the given string and find the bootloader file name, load address and
 * entry point information then call set_bootloader function.
 *
 * @param context	The main context pointer
 * @param token  	The parse token value
 * @param rest   	String to parse
 * @return 0 and 1 for success and failure
 */
static int parse_bootloader(build_image_context *context,
			parse_token token,
			char *rest)
{
	char filename[MAX_BUFFER];
	char e_state[MAX_STR_LEN];
	u_int32_t load_addr;
	u_int32_t entry_point;

	assert(context != NULL);
	assert(rest != NULL);

	if (context->generate_bct != 0)
		return 0;
	/* Parse the file name. */
	rest = parse_filename(rest, filename, MAX_BUFFER);
	if (rest == NULL)
		return 1;

	PARSE_COMMA(1);

	/* Parse the load address. */
	rest = parse_u32(rest, &load_addr);
	if (rest == NULL)
		return 1;

	PARSE_COMMA(1);

	/* Parse the entry point. */
	rest = parse_u32(rest, &entry_point);
	if (rest == NULL)
		return 1;

	PARSE_COMMA(1);

	/* Parse the end state. */
	rest = parse_end_state(rest, e_state, MAX_STR_LEN);
	if (rest == NULL)
		return 1;
	if (strncmp(e_state, "Complete", strlen("Complete")))
		return 1;

	/* Parsing has finished - set the bootloader */
	return set_bootloader(context, filename, load_addr, entry_point);
}
예제 #15
0
/*
 * Parse the given string and find the bct file name.
 *
 * @param context	The main context pointer
 * @param token  	The parse token value
 * @param rest   	String to parse
 * @return 0 and 1 for success and failure
 */
static int
parse_bct_file(build_image_context *context, parse_token token, char *rest)
{
	char   filename[MAX_BUFFER];

	assert(context != NULL);
	assert(rest != NULL);

	/* Parse the file name. */
	rest = parse_filename(rest, filename, MAX_BUFFER);
	if (rest == NULL)
		return 1;

	/* Parsing has finished - set the bctfile */
	context->bct_filename = filename;
	/* Read the bct file to buffer */
	read_bct_file(context);
	update_context(context);
	return 0;
}
예제 #16
0
void filename_input_function ( ui_object *obj, void *arg )
{
	char
		*text;

	text = get_ui_object_text (save_filename_input);

	if (text)
	{
		if (strlen (text) > 0)
		{
			parse_filename (text, FILENAME_MAX_LENGTH);

			set_ui_object_text (save_current_filename, text);
		}
	}

	set_ui_object_drawable (save_current_filename, TRUE);

	set_ui_object_drawable (save_filename_input, FALSE);
}
예제 #17
0
static void notify_save_file_list (ui_object *obj, void *arg)
{
	char
		*text;

	text = get_ui_object_text (obj);

	if (text)
	{
		if (strlen (text) > 0)
		{
			parse_filename (text, FILENAME_MAX_LENGTH);

			set_ui_object_text (save_current_filename, text);
		}
	}

	set_ui_object_drawable (save_current_filename, TRUE);

	set_ui_object_drawable (save_filename_input, FALSE);
}
예제 #18
0
파일: bba_info.c 프로젝트: tridlh/bba
int info_process(s_audinfo_t *inf)
{
	int ret = 0;
    int filetype;

    /* misc check */
    filetype = parse_filename(inf->fnamei, strlen(inf->fnamei));
    Log("%d", filetype);

    /* parse file */
    switch (filetype) {
    case FILE_RAW:
    case FILE_PCM:
        Log("raw data, can not parse");
        ret = 0;
        break;
    case FILE_WAV:
        ret = parsewav(inf);
        break;
    case FILE_MP3:
        ret = parsemp3(inf);
        break;
    case FILE_AAC:
        ret = parseaac(inf);
        break;
    case FILE_AMR:
        ret = parseamr(inf);
        break;
    case FILE_AWB:
        ret = parseawb(inf);
        break;
    default:
        Loge("Unsupported file type");
        break;
    }

    return ret;
}
예제 #19
0
size_t tool_header_cb(void *ptr, size_t size, size_t nmemb, void *userdata)
{
  struct OutStruct *outs = userdata;
  const char *str = ptr;
  const size_t cb = size * nmemb;
  const char *end = (char*)ptr + cb;

  /*
   * Once that libcurl has called back tool_header_cb() the returned value
   * is checked against the amount that was intended to be written, if
   * it does not match then it fails with CURLE_WRITE_ERROR. So at this
   * point returning a value different from sz*nmemb indicates failure.
   */
  size_t failure = (size * nmemb) ? 0 : 1;

  if(!outs->config)
    return failure;

#ifdef DEBUGBUILD
  if(size * nmemb > (size_t)CURL_MAX_HTTP_HEADER) {
    warnf(outs->config, "Header data exceeds single call write limit!\n");
    return failure;
  }
#endif

  if((cb > 20) && checkprefix("Content-disposition:", str)) {
    const char *p = str + 20;

    /* look for the 'filename=' parameter
       (encoded filenames (*=) are not supported) */
    for(;;) {
      char *filename;
      size_t len;

      while(*p && (p < end) && !ISALPHA(*p))
        p++;
      if(p > end - 9)
        break;

      if(memcmp(p, "filename=", 9)) {
        /* no match, find next parameter */
        while((p < end) && (*p != ';'))
          p++;
        continue;
      }
      p += 9;

      /* this expression below typecasts 'cb' only to avoid
         warning: signed and unsigned type in conditional expression
      */
      len = (ssize_t)cb - (p - str);
      filename = parse_filename(p, len);
      if(filename) {
        outs->filename = filename;
        outs->alloc_filename = TRUE;
        outs->s_isreg = TRUE;
        outs->fopened = FALSE;
        outs->stream = NULL;
        break;
      }
      else
        return failure;
    }
  }

  return cb;
}
예제 #20
0
/*	Starts running the client in given mode, parameters:
		struct hostent *hostname	- host information
		int port			- port used by client
		char *filename			- file to be uploaded / downloaded
	
	Return 0 if successful.
*/
int runServer(int port)
{
	int returnval = 0, t_sock = 0, filecheck = 0, rv = 0, sockSrv = 0, stopping = 0;
	packet *pck = NULL;
	init_packet *i_pck = NULL;
	error_packet *e_pck = NULL;
	clientnode *first_cl = NULL, *temp_cl = NULL;
	filedata *files = NULL;
	char *filename = NULL;
	char buffer[TFTP_BLOCK];
	fd_set srv_fd_set;
	struct timeval to;
	
	/* Create socket */
	if((sockSrv = socket(AF_INET,SOCK_DGRAM,0)) < 0) error("Error creating socket");
	
	/* Set own address data */
	own_address.sin_family = AF_INET;
	own_address.sin_addr.s_addr = htons(INADDR_ANY);
	own_address.sin_port = htons(port);
	
	addr_length = sizeof(struct sockaddr_in);
	
	/* Bind socket to own address */
	if(bind(sockSrv,(struct sockaddr *)&own_address,addr_length) < 0)
	{
		error("Port probably in use, select another port.\nUsage:\t./server <port>\n\nError in socket binding");
	}
	
	while(1)
	{
		FD_ZERO(&srv_fd_set);

		to.tv_sec = 0;
		to.tv_usec = 1;
		
		FD_SET(0,&srv_fd_set);

		/* If server is set to stop and wait for current connections to finish, stop listening the server socket */
		if(stopping == 0) FD_SET(sockSrv,&srv_fd_set);
		
		rv = select(sockSrv+1,&srv_fd_set,NULL,NULL,&to);
		
		if (rv < 0) error("Error in select()");
		
		else if(rv > 0)
		{
			/* Adding a client */
			if(FD_ISSET(sockSrv,&srv_fd_set))
			{
				/* Get packet */
				pck = read_packet(sockSrv);
				
				printf("New connection from: %s:%d. ",(char *)inet_ntoa(get_conn_addr().sin_addr), ntohs(get_conn_addr().sin_port));

				/* Create new socket */
				if((t_sock = socket(AF_INET,SOCK_DGRAM,0)) < 0) perror("Error creating socket");
				
				/* Set port and try to bind */
				transfer_address.sin_family = AF_INET;
				transfer_address.sin_addr.s_addr = htons(INADDR_ANY);
				transfer_address.sin_port = htons(create_port(1));
				
				while(bind(t_sock,(struct sockaddr *)&transfer_address,addr_length) < 0)
				{
					transfer_address.sin_port = htons(create_port(0));
				}
				
				printf("Bound to port: %d. ",ntohs(transfer_address.sin_port));

				/* Check packet size */
				if((pck->length < 10) || (pck->length > MAX_MSG))
				{
					pck = encode_error_packet(ERROR_ILLEGAL_OPERATION);
					printf("\nInvalid init packet size\n");
					send_packet(t_sock,pck);
					close(t_sock);
				}
				
				else
				{
					i_pck = decode_init_packet(pck);
		
					/* If client wants to read a file */
					if(ntohs(i_pck->opcode) == OPCODE_RRQ)
					{
						/* File name from packet */
						filename = parse_filename(i_pck->content);

						printf("Requesting file \"%s\".\n",filename);

						first_cl = add_client(first_cl,get_conn_addr(),t_sock,filename,OPCODE_RRQ,files);

						if(read_file_to_block(first_cl) == -1)
						{
							pck = encode_error_packet(ERROR_NOT_FOUND);
							send_packet(t_sock,pck);
							first_cl->state = STOP;
						}
					}
					
					/* If client wants to write a file */
					else if (ntohs(i_pck->opcode) == OPCODE_WRQ)
					{
						/* File name from packet */
						filename = parse_filename(i_pck->content);
						printf("Sending file \"%s\".\n",filename);

						/* Check that it can be written */
						if((filecheck = check_file(filename)) != 0)
						{	
							pck = encode_error_packet(filecheck);
							send_packet(t_sock,pck);
							close(t_sock);
						}
						else
						{
							first_cl = add_client(first_cl,get_conn_addr(),t_sock,filename,OPCODE_WRQ,NULL);
						}
					}
					
					/* Error */
					else if (ntohs(i_pck->opcode) == OPCODE_ERROR)
					{
						e_pck = decode_error_packet(pck);
						printf("Error from client: %s\n",e_pck->content);
						close(t_sock);
					}
					
					/* Else illegal operation */
					else
					{
						pck = encode_error_packet(ERROR_ILLEGAL_OPERATION);
						send_packet(t_sock,pck);
						printf("Invalid opcode\n");
						close(t_sock);
					}
				}
			}
			
			/* If something is typed into stdin */
			if(FD_ISSET(0,&srv_fd_set))
			{
				bzero(&buffer,TFTP_BLOCK);

				fgets(buffer,TFTP_BLOCK-1,stdin);

				/* Closing ? */
				if(strcasecmp(buffer,"CLOSE\n") == 0) stopping = 1;
			}
		}
		
		temp_cl = first_cl;
		
		/* Go through clients */
		while(temp_cl != NULL)
		{
			/* If not set as stopped */
			if(temp_cl->state != STOP)
			{
				/* Set address info */
				set_conn_addr(temp_cl->address);
				
				switch(temp_cl->mode)
				{
					case OPCODE_RRQ:
					
						upload_mode(temp_cl);
						break;
				
					case OPCODE_WRQ:
				
						/* If there was some error while downloading from client - try to remove the file */
						if(download_mode(temp_cl) != 1)
						{
							printf("Error happened. Trying to remove unfinished file ... ");
							if(close(temp_cl->filed) == 0)
							{
								temp_cl->filed = -1;
								if(!remove(temp_cl->filename)) printf("file \"%s\" was removed.\n",temp_cl->filename);
								else printf("file \"%s\" cannot be removed.\n",temp_cl->filename);
							}
						}
						break;
					
					default: break;
				}
			}
			
			temp_cl = temp_cl->next;
		}
		/* Remove stopped clients */
		first_cl = remove_stopped(first_cl);

		if((stopping == 1) && (first_cl == NULL))
		{
			printf("Server stopping\n");
			break;
		}
	}

	close(sockSrv);
	return returnval;
int display_openfilewindow(gui_t *gui, int add)
{
    OPENFILENAME fileopen;
    int result = 0;
    char filelist[MAXFILE];
    char filename[MAX_PATH];
    char directory[MAX_PATH];
    char *filespec = NULL;
    char *filepart = NULL;

    memset(&fileopen, 0, sizeof(OPENFILENAME));
    memset(filelist, 0, sizeof(filelist));

    fileopen.lStructSize = sizeof(OPENFILENAME);
    fileopen.hwndOwner = gui->mainwindow;
    fileopen.hInstance = GetModuleHandle(NULL);
    fileopen.lpstrFilter = "All Files (*.*)\0*.*\0"
                           "Media Files (*.avi;*.asf;*.wmv;*.mpg;*.mpeg;*.m2v;*.mov;\
                                         *.rmvb;*.rm;*.ogm;*.mp3;*.wav;*.wma;*.ra;*.ogg)\0\
                                         *.avi;*.asf;*.wmv;*.mpg;*.mpeg;*.m2v;*.mov;\
                                         *.rmvb;*.rm;*.ogm;*.mp3;*.wav;*.wma;*.ra;*.ogg\0"
                           "Video Files (*.avi;*.mpg;*.mpeg;*.mov)\0*.avi;*.mpg;*.mpeg;*.mov\0"
                           "Avisynth Scripts (*.avs)\0*.avs\0"
                           "Audio Files (*.mp3;*.wav;*.ra)\0*.mp3;*.wav;*.ra\000";
    fileopen.nFilterIndex = 0;
    fileopen.lpstrTitle = "Add file(s)...";
    fileopen.Flags = OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST| OFN_LONGNAMES | OFN_EXPLORER| OFN_READONLY | OFN_HIDEREADONLY;
    fileopen.lpstrFile = filelist;
    fileopen.lpstrCustomFilter = NULL;
    fileopen.nMaxFile = MAXFILE;

    if(GetOpenFileName(&fileopen))
    {
        /* clear playlist */
        if(!add) gui->playlist->clear_playlist(gui->playlist);

        memcpy(directory, fileopen.lpstrFile, fileopen.nFileOffset - 1);
        directory[fileopen.nFileOffset - 1] = 0;

        do
        {
            filespec = &fileopen.lpstrFile[fileopen.nFileOffset];
            filename[0] = 0;
            strcat(filename, directory);
            strcat(filename, "\\");
            strcat(filename, filespec);

            if (GetFileAttributes(filename) & FILE_ATTRIBUTE_DIRECTORY)
                mp_msg(MSGT_GPLAYER, MSGL_V, "[GUI] %s is a directory, skipping...\n", filename);
            else
            {
                if (GetFullPathName(filename, MAX_PATH, filename, &filepart))
                {
                    mplSetFileName(NULL, filename, STREAMTYPE_FILE);
                    if(!parse_filename(filename, playtree, mconfig, 0))
                        gui->playlist->add_track(gui->playlist, filename, NULL, filepart, 0);
                    mp_msg(MSGT_GPLAYER, MSGL_V, "[GUI] Adding file: %s - path %s\n", filespec, filename);
                    result++;
                }
            }
            fileopen.nFileOffset += strlen(filespec) + 1;
        } while (*filespec);
    }
    return result;
}
static LRESULT CALLBACK PlayListWndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
    HWND wdg;
    POINT cursor;
    gui_t *gui = (gui_t *) GetWindowLongPtr(hwnd, GWLP_USERDATA);
    playlist_t *pl = gui ? gui->playlist : NULL;
    switch (iMsg)
    {
        case WM_CREATE:
        {
            wdg = CreateWindow("button", "Play",
                               WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                               4, 10, 80, 25, hwnd,
                               (HMENU) ID_PLAY,
                               ((LPCREATESTRUCT) lParam) -> hInstance,
                               NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT), 0);

            wdg = CreateWindow ("button", "Up",
                                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                                4, 37, 80, 25, hwnd,
                                (HMENU) ID_UP,
                                ((LPCREATESTRUCT) lParam) -> hInstance,
                                NULL);
            SendMessage(wdg, WM_SETFONT,(WPARAM) GetStockObject(DEFAULT_GUI_FONT), 0);

            wdg = CreateWindow ("button", "Down",
                                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                                4, 64, 80, 25, hwnd,
                                (HMENU) ID_DOWN,
                                ((LPCREATESTRUCT) lParam) -> hInstance,
                                NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),0);

            wdg = CreateWindow ("button", "Remove",
                                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                                4, 91, 80, 25, hwnd,
                                (HMENU) ID_REMOVE,
                                ((LPCREATESTRUCT) lParam) -> hInstance,
                                NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),0);

            wdg = CreateWindow ("button", "Load",
                                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                                4, 118, 80, 25, hwnd,
                                (HMENU) ID_PLAYLISTLOAD,
                                ((LPCREATESTRUCT) lParam) -> hInstance,
                                NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),0);

            wdg = CreateWindow ("button", "Save",
                                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                                4, 145, 80, 25, hwnd,
                                (HMENU) ID_PLAYLISTSAVE,
                                ((LPCREATESTRUCT) lParam) -> hInstance,
                                NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),0);

            wdg = CreateWindow ("button", "Close",
                                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                                4, 193, 80, 25, hwnd,
                                (HMENU) ID_CLOSE,
                                ((LPCREATESTRUCT) lParam) -> hInstance,
                                NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),0);

            wdg = CreateWindow ("listbox", "tracklist", WS_CHILD | WS_VISIBLE | LBS_NOTIFY | WS_VSCROLL |
                               WS_HSCROLL | LBS_DISABLENOSCROLL, 92, 10, 300, 208, hwnd, (HMENU) ID_TRACKLIST,
                               ((LPCREATESTRUCT) lParam) -> hInstance, NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT), 0);
            SendMessage(wdg, LB_SETHORIZONTALEXTENT, MAX_PATH*4, 0);
            break;
        }
        case WM_CONTEXTMENU:
        {
            GetCursorPos(&cursor);
            SetForegroundWindow(hwnd);
            TrackPopupMenu(gui->playlistmenu, 0, cursor.x, cursor.y, 0, hwnd, NULL);
            break;
        }
        case WM_COMMAND:
        {
            int selected = 0;
            int i;
            for (i=0; i<pl->trackcount; i++)
                if(0 < SendDlgItemMessage(hwnd, ID_TRACKLIST, LB_GETSEL, i, 0)) selected = i + 1;
            switch (LOWORD(wParam))
            {
                case ID_CLOSE:
                    DestroyWindow(hwnd);
                    return 0;
                case ID_TRACKLIST:
                    if(HIWORD(wParam) == LBN_DBLCLK)
                    {
                case ID_PLAY:
                        if(selected) pl->current = selected - 1;
                        mplSetFileName(NULL, pl->tracks[pl->current]->filename, STREAMTYPE_STREAM);
                        gui->startplay(gui);
                    }
                    return 0;
                case ID_UP:
                {
                    if(selected) pl->moveup_track(pl, selected);
                    selected--;
                    break;
                }
                case ID_DOWN:
                {
                    if(selected) pl->movedown_track(pl, selected);
                    selected++;
                    break;
                }
                case ID_REMOVE:
                    if(selected) pl->remove_track(pl, selected);
                    break;
                case ID_ADDFILE:
                {
                    if(guiIntfStruct.StreamType == STREAMTYPE_DVD ||
                       guiIntfStruct.StreamType == STREAMTYPE_DVDNAV) return 0;
                    display_openfilewindow(gui, 1);
                    break;
                }
                case ID_ADDURL:
                {
                    if(guiIntfStruct.StreamType == STREAMTYPE_DVD ||
                       guiIntfStruct.StreamType == STREAMTYPE_DVDNAV) return 0;
                    display_openurlwindow(gui, 1);
                    break;
                }
                case ID_CLEAR:
                {
                    if(!gui->playlist->trackcount) return 0;
                    gui->playlist->clear_playlist(gui->playlist);
                    break;
                }
                case ID_PLAYLISTLOAD:
                {
                    if(guiIntfStruct.StreamType == STREAMTYPE_DVD ||
                       guiIntfStruct.StreamType == STREAMTYPE_DVDNAV) return 0;
                    display_loadplaylistwindow(gui);
                    break;
                }
                case ID_PLAYLISTSAVE:
                {
                    /* no point saving an empty playlist */
                    if(!gui->playlist->trackcount ||
                        guiIntfStruct.StreamType == STREAMTYPE_DVD ||
                        guiIntfStruct.StreamType == STREAMTYPE_DVDNAV)
                        return 0;
                    display_saveplaylistwindow(gui);
                    break;
                }
            }
            updatetracklist(hwnd);
            if(selected < 1) selected = 1;
            else if(selected>pl->trackcount) selected = pl->trackcount;
            SendDlgItemMessage(hwnd, ID_TRACKLIST, LB_SETCURSEL, selected - 1, 0);
            return 0;
        }
        case WM_DROPFILES:
        {
            char file[MAX_PATH];
            int filecount = DragQueryFile((HDROP) wParam, -1, file, MAX_PATH);
            int i;
            for (i=0; i<filecount; i++)
            {
                DragQueryFile((HDROP) wParam, i, file, MAX_PATH);
                if(!parse_filename(file, playtree, mconfig, 0))
                    pl->add_track(pl, file, NULL, NULL, 0);
            }
            DragFinish((HDROP) wParam);
            updatetracklist(hwnd);
        }
            break;
    }
    return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
static LRESULT CALLBACK OpenUrlWndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
    static HWND url;
    HWND wdg;
    FILE *f;
    char *history = get_path("gui.url");
    gui_t *gui = (gui_t *) GetWindowLongPtr(hwnd, GWLP_USERDATA);
    switch (iMsg)
    {
        case WM_CREATE:
            wdg = CreateWindow("button", "Ok",
                               WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                               4, 43, 80, 25, hwnd,
                               (HMENU) ID_OK,
                               ((LPCREATESTRUCT) lParam) -> hInstance,
                               NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT), 0);

            wdg = CreateWindow("button", "Cancel",
                               WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                               90, 43, 80, 25, hwnd,
                               (HMENU) ID_CANCEL,
                               ((LPCREATESTRUCT) lParam) -> hInstance,
                               NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT), 0);

            url = wdg = CreateWindowEx(WS_EX_CLIENTEDGE,
                               "edit", NULL,
                               WS_CHILD | WS_VISIBLE | ES_LEFT | ES_AUTOHSCROLL,
                               4, 10, 300, 25, hwnd,
                               (HMENU) ID_URL,
                               ((LPCREATESTRUCT) lParam) -> hInstance,
                               NULL);
            SendMessage(wdg, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT), 0);
            SendMessage(wdg, EM_SETLIMITTEXT, MAX_PATH, 0);

            /*subclass the edit box to capture the VK_RETURN key*/
            OldUrlWndProc = (WNDPROC)SetWindowLongPtr(url, GWLP_WNDPROC, (LONG_PTR)SubUrlWndProc);

            if((f = fopen(history, "r")))
            {
               char lasturl[MAX_PATH];
               fgets(lasturl, MAX_PATH, f);
               SendMessage(url, WM_SETTEXT, 0, (LPARAM) lasturl);
               SendMessage(url, EM_SETSEL, 0, -1);
               fclose(f);
            }
            break;
        case WM_KEYDOWN:
            switch (LOWORD(wParam))
            {
                case VK_RETURN:
                    SendMessage(hwnd, WM_COMMAND, (WPARAM) ID_OK, 0);
                    break;
            }
        case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
                case ID_CANCEL:
                    DestroyWindow(hwnd);
                    return 0;
                case ID_OK:
                {
                    char file[MAX_PATH];
                    SendMessage(url, WM_GETTEXT, MAX_PATH, (LPARAM) file);
                    mplSetFileName(NULL, file, STREAMTYPE_STREAM);
                    if((f = fopen(history, "wt+")))
                    {
                        fprintf(f, file);
                        fclose(f);
                    }
                    if(!parse_filename(file, playtree, mconfig, addurl? 0 : 1))
                        gui->playlist->add_track(gui->playlist, file, NULL, NULL, 0);
                    if(!addurl)
                        gui->startplay(gui);
                    else update_playlistwindow();
                    DestroyWindow(hwnd);
                }
                break;
            }
        }
        return 0;
        case WM_DESTROY:
        {
            addurl = 0;
            return 0;
        }
    }
    return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
예제 #24
0
파일: test.c 프로젝트: B0SB05/ironbee
/**
 * Runs a single test.
 *
 * @param[in] filename
 * @param[in] cfg
 * @return A pointer to the instance of htp_connp_t created during
 *         the test, or NULL if the test failed for some reason.
 */
int test_run_ex(const char *testsdir, const char *testname, htp_cfg_t *cfg, htp_connp_t **connp, int clone_count) {
    char filename[1025];
    test_t test;
    struct timeval tv_start, tv_end;
    int rc;

    *connp = NULL;

    strncpy(filename, testsdir, 1024);
    strncat(filename, "/", 1024 - strlen(filename));
    strncat(filename, testname, 1024 - strlen(filename));

    // printf("Filename: %s\n", filename);

    // Initinialize test

    rc = test_init(&test, filename, clone_count);
    if (rc < 0) {
        return rc;
    }

    gettimeofday(&tv_start, NULL);

    test_start(&test);

    // Create parser
    *connp = htp_connp_create(cfg);
    if (*connp == NULL) {
        fprintf(stderr, "Failed to create connection parser\n");
        exit(1);
    }

    htp_connp_set_user_data(*connp, (void *) 0x02);

    // Does the filename contain connection metdata?
    if (strncmp(testname, "stream", 6) == 0) {
        // It does; use it
        char *remote_addr = NULL, *local_addr = NULL;
        int remote_port = -1, local_port = -1;

        parse_filename(testname, &remote_addr, &remote_port, &local_addr, &local_port);
        htp_connp_open(*connp, (const char *) remote_addr, remote_port, (const char *) local_addr, local_port, &tv_start);
        free(remote_addr);
        free(local_addr);
    } else {
        // No connection metadata; provide some fake information instead
        htp_connp_open(*connp, (const char *) "127.0.0.1", 10000, (const char *) "127.0.0.1", 80, &tv_start);
    }

    // Find all chunks and feed them to the parser
    int in_data_other = 0;
    char *in_data = NULL;
    size_t in_data_len = 0;
    size_t in_data_offset = 0;

    int out_data_other = 0;
    char *out_data = NULL;
    size_t out_data_len = 0;
    size_t out_data_offset = 0;

    for (;;) {
        if (test_next_chunk(&test) <= 0) {
            break;
        }

        if (test.chunk_direction == CLIENT) {
            if (in_data_other) {
                test_destroy(&test);
                fprintf(stderr, "Unable to buffer more than one inbound chunk.\n");
                return -1;
            }
            
            rc = htp_connp_req_data(*connp, &tv_start, test.chunk, test.chunk_len);
            if (rc == HTP_STREAM_ERROR) {
                test_destroy(&test);
                return -101;
            }
            if (rc == HTP_STREAM_DATA_OTHER) {
                // Parser needs to see the outbound stream in order to continue
                // parsing the inbound stream.
                in_data_other = 1;
                in_data = test.chunk;
                in_data_len = test.chunk_len;
                in_data_offset = htp_connp_req_data_consumed(*connp);                
            }
        } else {
            if (out_data_other) {
                rc = htp_connp_res_data(*connp, &tv_start, out_data + out_data_offset, out_data_len - out_data_offset);
                if (rc == HTP_STREAM_ERROR) {
                    test_destroy(&test);
                    return -104;
                }
                
                out_data_other = 0;
            }

            rc = htp_connp_res_data(*connp, &tv_start, test.chunk, test.chunk_len);
            if (rc == HTP_STREAM_ERROR) {
                test_destroy(&test);
                return -102;
            }
            if (rc == HTP_STREAM_DATA_OTHER) {
                // Parser needs to see the outbound stream in order to continue
                // parsing the inbound stream.
                out_data_other = 1;
                out_data = test.chunk;
                out_data_len = test.chunk_len;
                out_data_offset = htp_connp_res_data_consumed(*connp);
                // printf("# YYY out offset is %d\n", out_data_offset);
            }

            if (in_data_other) {
                rc = htp_connp_req_data(*connp, &tv_start, in_data + in_data_offset, in_data_len - in_data_offset);
                if (rc == HTP_STREAM_ERROR) {
                    test_destroy(&test);
                    return -103;
                }
                
                in_data_other = 0;
            }
        }
    }

    if (out_data_other) {
        rc = htp_connp_res_data(*connp, &tv_start, out_data + out_data_offset, out_data_len - out_data_offset);
        if (rc == HTP_STREAM_ERROR) {
            test_destroy(&test);
            return -104;
        }
        out_data_other = 0;
    }

    gettimeofday(&tv_end, NULL);

    // Close the connection
    htp_connp_close(*connp, &tv_end);

    // Clean up
    test_destroy(&test);

    return 1;
}
예제 #25
0
파일: file.c 프로젝트: fachat/XD2031
// opens the file, registers an error code in command->error if necessary
// If the open was successful, setup a channel for the given channel number
// (note: explicitely not secondary device number, as IEEE and IEC in parallel
// use overlapping numbers, so they may be shifted or similar to avoid clashes)
//
// The command buffer is used as transmit buffer, so it must not be overwritten
// until the open has been sent.
//
// note that if it returns a value <0 on error, it has to have the error message
// set appropriately.
//
int8_t file_open(uint8_t channel_no, bus_t *bus, errormsg_t *errormsg,
                 void (*callback)(int8_t errnum, uint8_t *rxdata), uint8_t openflag) {

    assert_not_null(bus, "file_open: bus is null");

    cmd_t *command = &(bus->command);
    rtconfig_t *rtconf = &(bus->rtconf);

#ifdef DEBUG_FILE
    debug_printf("OPEN FILE: FOR CHAN: %d WITH NAME: '%s', OPENFLAG=%d\n",
                 channel_no, (char*)&(command->command_buffer), openflag);
#endif

    // note: in a preemtive env, the following would have to be protected
    // to be atomic as we modify static variables

    parse_filename(command, &nameinfo, (openflag & OPENFLAG_LOAD) ? PARSEHINT_LOAD : 0);

#ifdef DEBUG_FILE
    debug_printf("  PARSE -> ACCESS=%c, TYPE=%c\n", nameinfo.access, nameinfo.type);
#endif

    // drive handling needed for error message drive
    if (nameinfo.drive == NAMEINFO_LAST_DRIVE) {
        nameinfo.drive = rtconf->last_used_drive;
    }
    else if (nameinfo.drive == NAMEINFO_UNUSED_DRIVE) {
        // TODO: match CBM behavior
        nameinfo.drive = rtconf->last_used_drive;
    }
    int8_t errdrive = rtconf->errmsg_with_drive ? nameinfo.drive : -1;

    // post-parse

    if (nameinfo.cmd != CMD_NONE && nameinfo.cmd != CMD_DIR && nameinfo.cmd != CMD_OVERWRITE) {
        // command name during open
        // this is in fact ignored by CBM DOS as checked with VICE's true drive emulation
        debug_printf("NO CORRECT CMD: %s\n", command_to_name(nameinfo.cmd));
        nameinfo.cmd = 0;
    }
    if (nameinfo.type != 0 && nameinfo.type != 'S' && nameinfo.type != 'P'
            && nameinfo.type != 'U' && nameinfo.type != 'L') {
        // not set, or set as not sequential and not program
        debug_puts("UNKOWN FILE TYPE: ");
        debug_putc(nameinfo.type);
        debug_putcrlf();
        set_error_tsd(errormsg, CBM_ERROR_FILE_TYPE_MISMATCH, 0, 0, errdrive);
        return -1;
    }
    if (nameinfo.access != 0 && nameinfo.access != 'W' && nameinfo.access != 'R'
            && nameinfo.access != 'A' && nameinfo.access != 'X') {
        debug_puts("UNKNOWN FILE ACCESS TYPE ");
        debug_putc(nameinfo.access);
        debug_putcrlf();
        // not set, or set as not read, write, or append, or r/w ('X')
        set_error_tsd(errormsg, CBM_ERROR_SYNTAX_UNKNOWN, 0, 0, errdrive);
        return -1;
    }
    if (nameinfo.cmd == CMD_DIR && (nameinfo.access != 0 && nameinfo.access != 'R')) {
        // trying to write to a directory
        debug_puts("WRITE TO DIRECTORY!");
        debug_putcrlf();
        set_error_tsd(errormsg, CBM_ERROR_FILE_EXISTS, 0, 0, errdrive);
        return -1;
    }

    uint8_t type = FS_OPEN_RD;

    // file access default
    if (nameinfo.access == 0) {
        if (openflag == OPENFLAG_LOAD) {
            nameinfo.access = 'R';
        } else if (openflag == OPENFLAG_SAVE) {
            nameinfo.access = 'W';
        }
    }

    // file type defaults
    if (nameinfo.type == 0) {
        // do we create a file (access=='W')?
        if (nameinfo.access == 'W') {
            // write (like save)
            if (openflag == OPENFLAG_SAVE) {
                nameinfo.type = 'P';
            } else {
                nameinfo.type = 'S';
            }
        }
        if (nameinfo.access == 'R') {
            if (openflag == OPENFLAG_LOAD) {
                // on load, 'P' is the default
                nameinfo.type = 'P';
            }
        }
    }

    if (nameinfo.access == 'X') {
        // trying to open up a R/W channel
        debug_puts("OPENING UP A R/W CHANNEL!");
        debug_putcrlf();
        type = FS_OPEN_RW;
    }

    if (nameinfo.name[0] == '#') {
        // trying to open up a direct channel
        // Note: needs to be supported for D64 support with U1/U2/...
        // Note: '#' is still blocking on read!
        debug_puts("OPENING UP A DIRECT CHANNEL!");
        debug_putcrlf();

        type = FS_OPEN_DIRECT;
    }

    // if ",W" or secondary address is one, i.e. save
    if (nameinfo.access == 'W') {
        type = FS_OPEN_WR;
    }
    if (nameinfo.access == 'A') {
        type = FS_OPEN_AP;
    }
    if (nameinfo.cmd == CMD_DIR) {
        if (openflag & OPENFLAG_LOAD) {
            type = FS_OPEN_DR;
        } else {
            type = FS_OPEN_RD;
        }
    } else if (nameinfo.cmd == CMD_OVERWRITE) {
        type = FS_OPEN_OW;
    }

#ifdef DEBUG_FILE
    debug_printf("NAME='%s' (%d)\n", nameinfo.name, nameinfo.namelen);
    debug_printf("ACCESS=%c\n", nameinfo.access);
    debug_printf("CMD=%d\n", nameinfo.cmd);
    debug_flush();
#endif

    return file_submit_call(channel_no, type, command->command_buffer, errormsg, rtconf, callback, 0);

}
예제 #26
0
파일: tool_cb_hdr.c 프로젝트: AndyUI/curl
size_t tool_header_cb(void *ptr, size_t size, size_t nmemb, void *userdata)
{
  struct HdrCbData *hdrcbdata = userdata;
  struct OutStruct *outs = hdrcbdata->outs;
  struct OutStruct *heads = hdrcbdata->heads;
  const char *str = ptr;
  const size_t cb = size * nmemb;
  const char *end = (char*)ptr + cb;

  /*
   * Once that libcurl has called back tool_header_cb() the returned value
   * is checked against the amount that was intended to be written, if
   * it does not match then it fails with CURLE_WRITE_ERROR. So at this
   * point returning a value different from sz*nmemb indicates failure.
   */
  size_t failure = (size * nmemb) ? 0 : 1;

  if(!heads->config)
    return failure;

#ifdef DEBUGBUILD
  if(size * nmemb > (size_t)CURL_MAX_HTTP_HEADER) {
    warnf(heads->config->global, "Header data exceeds single call write "
          "limit!\n");
    return failure;
  }
#endif

  /*
   * Write header data when curl option --dump-header (-D) is given.
   */

  if(heads->config->headerfile && heads->stream) {
    size_t rc = fwrite(ptr, size, nmemb, heads->stream);
    if(rc != cb)
      return rc;
    /* flush the stream to send off what we got earlier */
    (void)fflush(heads->stream);
  }

  /*
   * This callback sets the filename where output shall be written when
   * curl options --remote-name (-O) and --remote-header-name (-J) have
   * been simultaneously given and additionally server returns an HTTP
   * Content-Disposition header specifying a filename property.
   */

  if(hdrcbdata->honor_cd_filename &&
     (cb > 20) && checkprefix("Content-disposition:", str)) {
    const char *p = str + 20;

    /* look for the 'filename=' parameter
       (encoded filenames (*=) are not supported) */
    for(;;) {
      char *filename;
      size_t len;

      while(*p && (p < end) && !ISALPHA(*p))
        p++;
      if(p > end - 9)
        break;

      if(memcmp(p, "filename=", 9)) {
        /* no match, find next parameter */
        while((p < end) && (*p != ';'))
          p++;
        continue;
      }
      p += 9;

      /* this expression below typecasts 'cb' only to avoid
         warning: signed and unsigned type in conditional expression
      */
      len = (ssize_t)cb - (p - str);
      filename = parse_filename(p, len);
      if(filename) {
        outs->filename = filename;
        outs->alloc_filename = TRUE;
        outs->is_cd_filename = TRUE;
        outs->s_isreg = TRUE;
        outs->fopened = FALSE;
        outs->stream = NULL;
        hdrcbdata->honor_cd_filename = FALSE;
        break;
      }
      else
        return failure;
    }
  }

  return cb;
}
예제 #27
0
void get_files( CAMHandle hCam, CAMDeviceInfoPtr pDevInfo, OPTS *pOpts)
{
    int             ret;
    int             fName;
    char           *pName;
    uint32_t       *pHandle;
    uint32_t       *pEnd;
    CAMObjectHandlePtr pHandles = 0;
    CAMObjectInfoPtr   pObjInfo = 0;
    FNSTRUCT        fns;
    char            path[260];

    if (GetObjectHandles( hCam, 0xffffffff, 0, 0, &pHandles)) {
        camcli_error( "Could not get object handles");
        return;
    }

    fName = parse_filename( pOpts->value, &fns);
    if (fName)
        pName = path;
    else
        pName = 0;

    if (!validate_range( pHandles, pOpts, &pHandle, &pEnd)) {
        if (pHandles)
            free( pHandles);
        return;
    }

    if (pOpts->flags & OPT_THUMBNAIL) {
        printf ( "\n Save thumbnails  %s\n", pDevInfo->Model);
        printf (   " ===============  %s\n", underline( pDevInfo->Model));
    }
    else {
        printf ( "\n Save files  %s\n", pDevInfo->Model);
        printf (   " ==========  %s\n", underline( pDevInfo->Model));
    }

    for (; pHandle <= pEnd; pHandle++) {

        ret = GetObjectInfo( hCam, *pHandle, &pObjInfo);
        if (ret) {
            camcli_error( "Could not get info for handle %d", *pHandle);
            if (ret == CAMERR_USBFAILURE)
                ClearStall( hCam);
            continue;
        }

        if (pObjInfo->ObjectFormat == PTP_OFC_Association)
            printf( " Handle %d is not a file - skipping...\n", *pHandle);
        else {
            if (fName)
                make_filename( pName, pObjInfo->Filename, &fns);
            ret = os2_get_file( hCam, pObjInfo, *pHandle, pName,
                               (pOpts->flags & OPT_REPLACE),
                               (pOpts->flags & OPT_THUMBNAIL));

            if (ret == CAMERR_USBFAILURE)
                ClearStall( hCam);
        }

        free( pObjInfo);
        pObjInfo = 0;
    }

    if (pObjInfo)
        free( pObjInfo);
    if (pHandles)
        free( pHandles);

    return;
}
예제 #28
0
파일: chain2.c 프로젝트: crooks/mixmaster
int
chain_2 (int argc, char *argv[])
{
  FILE *in;
  char line[256], filename[80] = "", *destination[NUMDEST], outfile[80] = "";
  char *subject[NUMSUB], *t;
  int chain[HOPMAX];
  byte numdest = 0, numsub = 0;
  int i, num_remailers, outfileflag = 0;
  REMAILER remailer_list[256];
  int filter = 0, rfcmsg = 0, dummy = 0;

  num_remailers = read_remailer_list (remailer_list);

  chain[0] = 0;

  /* what is in those arguments */
  /* Here is the expected format */
  /* mixmaster [-c][-f][filename][-[o,O] outfile][-to who@where][-s "subject"][-l 1 2 3 4] */
  /* if no outfile given, then pipe to sendmail. outfile = stdout send to stdout */
  for (i = 1; i < argc; i++)
    {
      if (streq (argv[i], "-c"))
	{
	  /* nop */
	}
      else if (strleft (argv[i], "-h") || streq (argv[i], "--help"))
	{
	  /* Print help and exit */
	  printf ("Mixmaster %s (C) Copyright Lance M. Cottrell 1995, 1996\n",
		  VERSION);
	  printf ("Released under the GNU public license. No warranty!\n\n");
	  printf ("Client Mode command line arguments:\n");
	  printf ("mixmaster [-c] [infile] [-f] [-m] [-s subject] [-v 'Header: text' [-v ...]]\n[-n numcopies] [-[o,O] outfile] [-to who@where] [-l 1 2 3 ...]\n");
	  exit (-1);
	}
      else if (streq (argv[i], "-f"))
	{
	  /* set filter mode */
	  filter = 1;
	}
      else if (streq (argv[i], "-m"))
	{
	  filter = 1;
	  rfcmsg = 1;
	}
      else if (streq (argv[i], "-d"))
	{
	  filter = 1;
	  destination[0] = (char *) calloc (1, DESTSIZE);
	  strcpy (destination[0], "null:");
	  numdest = 1;
	  REQUIRE[0] = '\0';
	  REJECT[0] = '\0';
	  dummy = 5 + random_number (11);
	}
      else if (streq (argv[i], "-s"))
	{
	  if (i < argc - 1)
	    i++;
	  subject[numsub] = (char *) calloc (1, SUBSIZE);
	  strcpy (subject[numsub], "Subject: ");
	  strncat (subject[numsub], argv[i], SUBSIZE - sizeof ("Subject: "));
	  numsub++;
	}
      else if (streq (argv[i], "-v"))
	{
	  if (i < argc - 1)
	    i++;
	  subject[numsub] = (char *) calloc (1, SUBSIZE);
	  subject[numsub][0] = 0;
	  strncat (subject[numsub], argv[i], SUBSIZE - 1);
	  numsub++;
	}
      else if (streq (argv[i], "-o") || streq (argv[i], "-O"))
	{
	  if (streq (argv[i], "-O"))
	    outfileflag = 1;	/* add To: line */
	  if (i < argc - 1)
	    i++;
	  if (streq (argv[i], "stdout"))
	    strcpy (outfile, "-");
	  else
	    parse_filename (outfile, argv[i]);
	}
      else if (streq (argv[i], "-n"))
	{
	  if (i < argc - 1)
	    i++;
	  sscanf (argv[i], "%d", &NUMCOPIES);
	}
      else if (streq (argv[i], "-to") && numdest < NUMDEST)
	{
	  if (i < argc - 1)
	    i++;
	  destination[numdest] = (char *) calloc (1, DESTSIZE);
	  strncpy (destination[numdest], argv[i], DESTSIZE - 1);
	  destination[numdest][DESTSIZE - 1] = '\0';
	  chop (destination[numdest]);
	  numdest++;
	}
      else if (streq (argv[i], "-l"))
	{
	  for (i++; i < argc && chain[0] < HOPMAX; i++)
	    if ((chain[++chain[0]] =
		 select_remailer (remailer_list,
				  num_remailers, argv[i])) < 0)
	      exit (-1);	/* Invalid remailer */
	}
      else
	{
	  if (strlen (filename) != 0)
	    {
	      fprintf (errlog, "problem with the command line\n");
	      return (-1);
	    }
	  strncpy (filename, argv[i], sizeof (filename));
	}
    }

  if (numdest == 0 && !rfcmsg)
    {
      if (!filter)
	fprintf (errlog, "Enter final destinations (one per line return when done).\n");
      do
	{
	  if (!filter)
	    fprintf (errlog, "Enter destination :");
	  getline (line, sizeof (line), stdin);
	  if (strlen (line) >= 2 && numdest < NUMDEST)
	    {
	      destination[numdest] = (char *) calloc (1, DESTSIZE);
	      strncpy (destination[numdest], line, DESTSIZE - 1);
	      destination[numdest][DESTSIZE - 1] = '\0';
	      numdest++;
	    }
	}
      while (strlen (line) > 0 || numdest == 0);
    }
  if (numdest == 0 && filter && !rfcmsg)
    exit (-1);			/* no destination and in filter mode */

  if (numsub == 0 && !dummy)
    {
      if (!filter)
	{
	  fprintf (errlog, "Enter message headers (one per line, return when done).\n");
	  fprintf (errlog, "You must include the header name, e.g. 'Subject: foo'\n");
	}
      do
	{
	  if (!filter)
	    fprintf (errlog, "Enter header :");
	  getline (line, sizeof (line), stdin);
	  if (rfcmsg && (strileft (line, "To:") || strileft (line, "Newsgroups:")) && numdest < NUMDEST)
	    {
	      destination[numdest] = (char *) calloc (1, DESTSIZE);
	      if (strileft (line, "To:"))
		{
		  t = line + sizeof ("To:") - 1;
		  while (*t == ' ' || *t == '\t')
		    t++;
		  strncpy (destination[numdest], t, DESTSIZE - 1);
		}
	      else
		{
		  t = line + sizeof ("Newsgroups:") - 1;
		  while (*t == ' ' || *t == '\t')
		    t++;
		  strcpy (destination[numdest], "post: ");
		  strncat (destination[numdest], t, DESTSIZE - sizeof ("post: "));
		}
	      destination[numdest][DESTSIZE - 1] = '\0';
	      numdest++;
	    }
	  else if (strlen (line) > 0 && numsub < NUMSUB)
	    {
	      subject[numsub] = (char *) calloc (1, SUBSIZE);
	      strncpy (subject[numsub], line, SUBSIZE - 1);
	      subject[numsub][SUBSIZE - 1] = '\0';
	      numsub++;
	    }
	}
      while (strlen (line) > 0);
    }

  if (!strchr (REQUIRE, 'N'))
    for (i = 0; i < numdest; i++)
      if (strileft (destination[i], "post:"))
	{
	  strcat (REQUIRE, "N");
	  break;
	}

  if (chain[0] == 0 && strlen (CHAIN))
    if (scan_remailer_list (CHAIN, chain, remailer_list, num_remailers) < 0)
      return (-1);
  if (chain[0] == 0 && dummy)
    {
      while (chain[0] < dummy)
	chain[++chain[0]] = 0;
    }
  if (chain[0] == 0 && !filter)
    {
      get_chain (remailer_list, num_remailers, chain);
    }
  if (chain[0] == 0)
    {
      return (-1);
    }
#if 1
  if ((chain[chain[0]] > 0)
      && check_abilities (remailer_list[chain[chain[0]]].abilities,
			  REQUIRE, REJECT) == 0)
    {
      fprintf (errlog, "Warning: Remailer %s has insufficient capabilities!\n",
	       remailer_list[chain[chain[0]]].shortname);
    }
#else
  while ((chain[chain[0]] > 0)
	 && check_abilities (remailer_list[chain[chain[0]]].abilities,
			     REQUIRE, REJECT) == 0)
    {
      fprintf (errlog, "Remailer %s has insufficient capabilities!\n",
	       remailer_list[chain[chain[0]]].shortname);
      if (!filter)
	{
	  chain[0]--;
	  get_chain (remailer_list, num_remailers, chain);
	}
      else
	exit (-1);
    }
#endif

  /* if file = stdin then I will take stdin */
  if (strlen (filename) == 0 && !filter)
    {
      fprintf (errlog, "Please enter the name of the file to chain: ");
      getline (filename, sizeof (filename), stdin);
    }
  if (streq (filename, "stdin"))
    strcpy (filename, "-");
  parse_filename (line, filename);
  if (dummy)
    in = NULL;
  else if (streq (filename, "-") || strlen (filename) == 0)
    {
      if (!filter)
	fprintf (errlog, "Please enter the message.\n");
      in = stdin;
    }
  else
    in = open_user_file (line, "r");
  /* ok, that should be everything we need to know */

#ifdef DEBUG
  printf ("filtermode %d\n", filter);	/*debug */
  printf ("source file %s\n", filename);	/*debug */
  printf ("#destinations %d\n", numdest);	/*debug */
  for (i = 0; i < numdest; i++)
    printf ("destination %d  %s\n", i, destination[i]);	/*debug */
  for (i = 1; i <= chain[0]; i++)
    printf ("remailer %d\n", chain[i]);	/*debug */
  for (i = 0; i < numsub; i++)
    printf ("header %d  %s\n", i, subject[i]);	/*debug */
#endif

  return (build_message (in, numdest, destination, chain,
			 numsub, subject, outfile, outfileflag,
			 remailer_list, num_remailers, 1));
}
예제 #29
0
파일: tool_cb_hdr.c 프로젝트: ETrun/curl
size_t tool_header_cb(char *ptr, size_t size, size_t nmemb, void *userdata)
{
  struct HdrCbData *hdrcbdata = userdata;
  struct OutStruct *outs = hdrcbdata->outs;
  struct OutStruct *heads = hdrcbdata->heads;
  const char *str = ptr;
  const size_t cb = size * nmemb;
  const char *end = (char *)ptr + cb;
  long protocol = 0;

  /*
   * Once that libcurl has called back tool_header_cb() the returned value
   * is checked against the amount that was intended to be written, if
   * it does not match then it fails with CURLE_WRITE_ERROR. So at this
   * point returning a value different from sz*nmemb indicates failure.
   */
  size_t failure = (size && nmemb) ? 0 : 1;

  if(!heads->config)
    return failure;

#ifdef DEBUGBUILD
  if(size * nmemb > (size_t)CURL_MAX_HTTP_HEADER) {
    warnf(heads->config->global, "Header data exceeds single call write "
          "limit!\n");
    return failure;
  }
#endif

  /*
   * Write header data when curl option --dump-header (-D) is given.
   */

  if(heads->config->headerfile && heads->stream) {
    size_t rc = fwrite(ptr, size, nmemb, heads->stream);
    if(rc != cb)
      return rc;
    /* flush the stream to send off what we got earlier */
    (void)fflush(heads->stream);
  }

  /*
   * This callback sets the filename where output shall be written when
   * curl options --remote-name (-O) and --remote-header-name (-J) have
   * been simultaneously given and additionally server returns an HTTP
   * Content-Disposition header specifying a filename property.
   */

  curl_easy_getinfo(outs->config->easy, CURLINFO_PROTOCOL, &protocol);
  if(hdrcbdata->honor_cd_filename &&
     (cb > 20) && checkprefix("Content-disposition:", str) &&
     (protocol & (CURLPROTO_HTTPS|CURLPROTO_HTTP))) {
    const char *p = str + 20;

    if(!outs->stream && !tool_create_output_file(outs, FALSE))
      return failure;

    /* look for the 'filename=' parameter
       (encoded filenames (*=) are not supported) */
    for(;;) {
      char *filename;
      size_t len;

      while(*p && (p < end) && !ISALPHA(*p))
        p++;
      if(p > end - 9)
        break;

      if(memcmp(p, "filename=", 9)) {
        /* no match, find next parameter */
        while((p < end) && (*p != ';'))
          p++;
        continue;
      }
      p += 9;

      /* this expression below typecasts 'cb' only to avoid
         warning: signed and unsigned type in conditional expression
      */
      len = (ssize_t)cb - (p - str);
      filename = parse_filename(p, len);
      if(filename) {
        if(outs->stream) {
          /* already opened and possibly written to */
          if(outs->fopened)
            fclose(outs->stream);
          outs->stream = NULL;

          /* rename the initial file name to the new file name */
          rename(outs->filename, filename);
          if(outs->alloc_filename)
            free(outs->filename);
        }
        outs->is_cd_filename = TRUE;
        outs->s_isreg = TRUE;
        outs->fopened = FALSE;
        outs->filename = filename;
        outs->alloc_filename = TRUE;
        hdrcbdata->honor_cd_filename = FALSE; /* done now! */
        if(!tool_create_output_file(outs, TRUE))
          return failure;
      }
      break;
    }
  }

  if(hdrcbdata->config->show_headers &&
     (protocol & (CURLPROTO_HTTP|CURLPROTO_HTTPS|CURLPROTO_RTSP))) {
    /* bold headers only happen for HTTP(S) and RTSP */
    char *value = NULL;

    if(!outs->stream && !tool_create_output_file(outs, FALSE))
      return failure;

    if(hdrcbdata->global->isatty && hdrcbdata->global->styled_output)
      value = memchr(ptr, ':', cb);
    if(value) {
      size_t namelen = value - ptr;
      fprintf(outs->stream, BOLD "%.*s" BOLDOFF ":", namelen, ptr);
      fwrite(&value[1], cb - namelen - 1, 1, outs->stream);
    }
    else
      /* not "handled", just show it */
      fwrite(ptr, cb, 1, outs->stream);
  }
  return cb;
}
예제 #30
0
int main(int argc, char *argv[])
{
#else
int OCG_main(char is_local_server[FILENAME_LENGTH_MAX])
{
#endif
  int state = STATE_START_OCG;
  char web_XML_folder[DIR_LENGTH_MAX] = "";
  char output_dir[DIR_LENGTH_MAX] = ""; // the output folder during the OCG procedure. Change step by step

  char *OPENAIR_TARGETS=getenv("OPENAIR_TARGETS");

  if (OPENAIR_TARGETS == NULL) {
    LOG_E(OCG, "please set the PATH for OPENAIR_TARGETS");
    exit(EXIT_FAILURE);
  }

  if (!strcmp(is_local_server, "0")) { // Eurecom web server
    strcpy(web_XML_folder, WEB_XML_FOLDER);
    strcat(output_dir, OUTPUT_DIR);
  } else { // local user

    sprintf(web_XML_folder,"%s/SIMU/EXAMPLES/OSD/WEBXML/",getenv("OPENAIR_TARGETS"));
    sprintf(output_dir,"%s/SIMU/EXAMPLES/OSD/RESULTS/",getenv("OPENAIR_TARGETS"));
    /*
    strcpy(web_XML_folder, OPENAIR_TARGETS);
    strcpy(output_dir, OPENAIR_TARGETS);

    char *slash;
    slash = web_XML_folder + strlen(web_XML_folder) - 1;
    if (strcmp(slash, "/")) { // check if the path OPENAIR_TARGETS is ended with a '/'
      strcat(web_XML_folder, "/");
      strcat(output_dir, "/");
    }
    strcat(web_XML_folder, "SIMU/EXAMPLES/OSD/WEBXML/");
    strcat(output_dir, "SIMU/EXAMPLES/OSD/RESULTS/");
    */
  }

  LOG_I(OCG, "Folder for detecting the XML configuration file is %s\n", web_XML_folder);
  LOG_I(OCG, "Folder for generating the results is %s\n", output_dir);
  LOG_I(OCG, "OSD XML config file is %s\n", is_local_server);


  while(state != STATE_END) {

    switch(state) {

    case STATE_START_OCG :
      LOG_I(OCG, "OCG starts ...\n\n");
      get_opt_OK = MODULE_NOT_PROCESSED; // -9999 is the initial value, representing the module not processed
      detect_file_OK = MODULE_NOT_PROCESSED;
      create_dir_OK = MODULE_NOT_PROCESSED;

      // to write the pid into a file 'OCG.pid' so that the web portal part could check if OCG is running
      /*
      pid_t pid;
      pid = getpid();
      FILE *OCG_pid;
      OCG_pid = fopen("OCG.pid", "w");
      fprintf(OCG_pid, "%d\n", pid);
      fclose(OCG_pid);
      */
#ifdef TEST_OCG
      state = STATE_GET_OPT;

    case STATE_GET_OPT :
      get_opt_OK = get_opt(argc, argv);

      if (get_opt_OK == MODULE_OK) {
        strcpy(src_file, LOCAL_XML_FOLDER);
        copy_or_move = 1;
        state = STATE_INI_EMU;
      } else if (get_opt_OK == GET_HELP) state = STATE_END;
      else state = STATE_DETECT_FILE;

      break;
#else
      state = STATE_DETECT_FILE;
      //get_opt_OK == MODULE_OK;
#endif

    case STATE_DETECT_FILE :
      strcpy(src_file, web_XML_folder);
      detect_file_OK = detect_file(src_file, is_local_server);

      if (detect_file_OK == MODULE_OK) {
        if ((!strcmp(is_local_server, "0")) || (!strcmp(is_local_server, "-1"))) copy_or_move = 2;

        state = STATE_INI_EMU;
      } else if (detect_file_OK == MODULE_ERROR) state = STATE_GENERATE_REPORT;
      else if (detect_file_OK == NO_FILE) {
        state = STATE_DETECT_FILE;
        sleep(1);
      }

      break;

    case STATE_INI_EMU : // before initiating an emu, an XML file should be found above
      parse_filename_OK = MODULE_NOT_PROCESSED;
      create_dir_OK = MODULE_NOT_PROCESSED;
      parse_XML_OK = MODULE_NOT_PROCESSED;
      save_XML_OK = MODULE_NOT_PROCESSED;
      //        call_emu_OK = MODULE_NOT_PROCESSED;
      //config_mobi_OK = MODULE_NOT_PROCESSED;
      generate_report_OK = MODULE_NOT_PROCESSED;

      LOG_I(OCG, "An emulation for file %s is initiated\n", filename);
      state = STATE_PARSE_FILENAME;
      break;

    case STATE_PARSE_FILENAME :
      strcat(src_file, filename);

      if ((parse_filename_OK = parse_filename(filename)) == MODULE_OK) state = STATE_CREATE_DIR;
      else {
        if (copy_or_move == 2) {
          remove(src_file);
          state = STATE_DETECT_FILE;
        } else state = STATE_GENERATE_REPORT;
      }

      break;

    case STATE_CREATE_DIR :
      if ((create_dir_OK = create_dir(output_dir, user_name, file_date)) == MODULE_OK) {
        state = STATE_PARSE_XML;
        strcat(output_dir, user_name);
        strcat(output_dir, "/");
        strcat(output_dir, file_date);
        strcat(output_dir, "/");
        strcpy(dst_dir, output_dir);
        oai_emulation.info.output_path = dst_dir; // information for other modules within OAI
      } else state = STATE_GENERATE_REPORT;

      break;

    case STATE_PARSE_XML :
      if ((parse_XML_OK = parse_XML(src_file)) == MODULE_OK) state = STATE_SAVE_XML;
      else {
        if (copy_or_move == 2) remove(src_file);

        state = STATE_GENERATE_REPORT;
      }

      break;

    case STATE_SAVE_XML :
      if ((save_XML_OK = save_XML(copy_or_move, src_file, output_dir, filename)) == MODULE_OK)
        state = STATE_CALL_EMU;
      else state = STATE_GENERATE_REPORT;

      break;

    case STATE_CALL_EMU : // change this state to set_params

      if ((detect_file_OK == MODULE_OK) && (parse_filename_OK == MODULE_OK) && (create_dir_OK == MODULE_OK) && (parse_XML_OK == MODULE_OK) && (save_XML_OK == MODULE_OK)) {
        // if the above tasks are all successful, we could tell the oaisim_config.c that everything is ready before running the emulation
        oai_emulation.info.ocg_ok = 1;
      }

#ifdef TEST_OCG
      call_emu_OK = call_emu(output_dir);
      // config_mobi_OK = config_mobi("RWMEmulator.xml", filename); // generate the XML for Mobigen
#endif
      state = STATE_GENERATE_REPORT;
      break;

    case STATE_GENERATE_REPORT :
      if (create_dir_OK != MODULE_OK) {
        // a temp folder is required when the output folder could not be correctly generated
        strncpy(output_dir, OPENAIR_TARGETS, sizeof(output_dir));
        output_dir[sizeof(output_dir) - 1] = 0; // terminate string
        strncat(output_dir, "SIMU/EXAMPLES/OSD/", sizeof(output_dir) - strlen(output_dir) - 1);
        strncat(output_dir, TEMP_OUTPUT_DIR, sizeof(output_dir) - strlen(output_dir) - 1);
        struct stat st;

        if(stat(output_dir, &st) != 0) { // if temp output directory does not exist, we create it here
          mkdir(output_dir, S_IRWXU | S_IRWXG | S_IRWXO);
          LOG_I(OCG, "temp output directory %s is created", output_dir);
        }
      } else {
        //strcat(output_dir, "SCENARIO/STATE/"); // if needeed the outpur directory can be further set
        LOG_I(OCG, "Output directory is %s \n", output_dir);
      }

      generate_report(output_dir, "OCG_report.xml");

      if (copy_or_move == 1) state = STATE_END;
      else state = STATE_END;

      //else state = STATE_DETECT_FILE;
      break;
    }
  } // end while

  // Cleanup function for the XML library.
  xmlCleanupParser();
  // this is to debug memory for regression tests
  xmlMemoryDump();
  LOG_I(OCG, "... OCG ends\n\n");
#ifdef TEST_OCG
  return 0;
#else
  return 1;
#endif
}