Ejemplo n.º 1
0
/*****************************************************************************
 * Open: initializes dump structures
 *****************************************************************************/
static int Open( vlc_object_t * p_this )
{
    demux_t     *p_demux = (demux_t*)p_this;
    demux_sys_t *p_sys;
    const char  *psz_mode;
    vlc_value_t val;
    bool  b_append;

    /* Accept only if forced */
    if( !p_demux->b_force )
        return VLC_EGENERIC;

    p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
    if( !p_sys )
        return VLC_ENOMEM;

    var_Create( p_demux, "demuxdump-append", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
    var_Get( p_demux, "demuxdump-append", &val );
    b_append = val.b_bool;
    if ( b_append )
        psz_mode = "ab";
    else
        psz_mode = "wb";

    p_demux->pf_demux = Demux;
    p_demux->pf_control = Control;

    p_sys->i_write = 0;
    p_sys->p_file = NULL;
    p_sys->psz_file = var_CreateGetString( p_demux, "demuxdump-file" );
    if( *p_sys->psz_file == '\0' )
    {
        msg_Warn( p_demux, "no dump file name given" );
        free( p_sys->psz_file );
        free( p_sys );
        return VLC_EGENERIC;
    }

    if( !strcmp( p_sys->psz_file, "-" ) )
    {
        msg_Info( p_demux, "dumping raw stream to standard output" );
        p_sys->p_file = stdout;
    }
    else if( ( p_sys->p_file = utf8_fopen( p_sys->psz_file, psz_mode ) ) == NULL )
    {
        msg_Err( p_demux, "cannot create `%s' for writing", p_sys->psz_file );
        free( p_sys->psz_file );
        free( p_sys );
        return VLC_EGENERIC;
    }
    msg_Info( p_demux, "%s raw stream to file `%s'",
              b_append ? "appending" : "dumping", p_sys->psz_file );

    return VLC_SUCCESS;
}
Ejemplo n.º 2
0
/* HTS_fopen: wrapper for fopen */
HTS_File *HTS_fopen(const char *name, const char *opt)
{
   HTS_File *fp = utf8_fopen(name, opt);

   if (fp == NULL) {
      HTS_error(1, "HTS_fopen: Cannot open %s.\n", name);
      return NULL;
   }

   return fp;
}
Ejemplo n.º 3
0
/* load_preset_file: private function that loads a specific preset denoted
   by the given pathname */
int load_preset_file(char * pathname, preset_t * preset) { 
  FILE * fs;
  int retval;

  if (pathname == NULL)
	  return FAILURE;
  if (preset == NULL)
	  return FAILURE;
  
  /* Open the file corresponding to pathname */
  if ((fs = utf8_fopen(pathname, "r")) == 0) {
    if (PRESET_DEBUG) printf("load_preset_file: loading of file %s failed!\n", pathname);
    return ERROR;	
  }

  if (PRESET_DEBUG) printf("load_preset_file: file stream \"%s\" opened successfully\n", pathname);

  /* Parse any comments */
  if (parse_top_comment(fs) < 0) {
    if (PRESET_DEBUG) printf("load_preset_file: no left bracket found...\n");
    fclose(fs);
    return FAILURE;
  }
  
  /* Parse the preset name and a left bracket */
  if (parse_preset_name(fs, preset->name) < 0) {
    if (PRESET_DEBUG) printf("load_preset_file: loading of preset name in file \"%s\" failed\n", pathname);
    fclose(fs);
    return ERROR;
  }
  
  if (PRESET_DEBUG) printf("load_preset_file: preset \"%s\" parsed\n", preset->name);

  /* Parse each line until end of file */
  if (PRESET_DEBUG) printf("load_preset_file: beginning line parsing...\n");
  while ((retval = parse_line(fs, preset)) != EOF) {
    if (retval == PARSE_ERROR) {
      if (PRESET_DEBUG > 1) printf("load_preset_file: parse error in file \"%s\"\n", pathname);
    }
  }
  
  if (PRESET_DEBUG) printf("load_preset_file: finished line parsing successfully\n"); 

  /* Now the preset has been loaded.
     Evaluation calls can be made at appropiate
     times in the frame loop */
  
  fclose(fs);
   
  if (PRESET_DEBUG) printf("load_preset_file: file \"%s\" closed, preset ready\n", pathname);
  return SUCCESS;
  
}
Ejemplo n.º 4
0
int run_file() {
	int result = 0;
	g_current_step = 0;
	file_close();

	g_fd = utf8_fopen(g_filename, "rb");
	if (!g_fd) {
		ERROR_LOG("Cannot open file %s. Error(%d): %s\n", g_filename, errno, strerror(errno));
		result = errno;
		goto cleanup;
	}

	char line[LINE_SIZE];
	char line2[LINE_SIZE];
	while (fgets(line, LINE_SIZE, g_fd)) {
		if (g_abort) {
			break;
		}
		chomp(line);
		if (strcmp(line, "D") == 0) {
			fgets(line, LINE_SIZE, g_fd);
			chomp(line);
			DEBUG_LOG("Making dir %s\n", line);
			int res = TRY(utf8_mkdir(line), res != 0, "mkdir error: (%d) %s\n", errno, strerror(errno));
			g_current_step += MKDIR_STEP;
			inform_progress();
		} else if (strcmp(line, "F") == 0) {
			fgets(line, LINE_SIZE, g_fd);
			chomp(line);
			fgets(line2, LINE_SIZE, g_fd);
			chomp(line2);
			DO(cp(line, line2, CP_BUFFER_SIZE));
		}
	}

cleanup:
	if (g_fd) {
		fclose(g_fd);
		g_fd = NULL;
	}

	if (result == 0 && g_file_full) {
		result = 2;
	}

	if (result == 0 && g_abort) {
		result = 1;
	}
	return result;
}
Ejemplo n.º 5
0
/**
 * Export a playlist to a certain type of playlistfile
 *
 * \param p_playlist the playlist to export
 * \param psz_filename the location where the exported file will be saved
 * \param psz_type the type of playlist file to create.
 * \return VLC_SUCCESS on success
 */
int playlist_Export( playlist_t * p_playlist, const char *psz_filename ,
                     const char *psz_type)
{
    module_t *p_module;
    playlist_export_t *p_export;

    msg_Info( p_playlist, "saving playlist to file %s", psz_filename );

    /* Prepare the playlist_export_t structure */
    p_export = (playlist_export_t *)malloc( sizeof(playlist_export_t) );
    if( !p_export)
    {
        msg_Err( p_playlist, "out of memory");
        return VLC_ENOMEM;
    }
    p_export->psz_filename = NULL;
    if ( psz_filename )
        p_export->psz_filename = strdup( psz_filename );
    p_export->p_file = utf8_fopen( psz_filename, "wt" );
    if( !p_export->p_file )
    {
        msg_Err( p_playlist , "could not create playlist file %s"
                 " (%s)", psz_filename, strerror(errno) );
        return VLC_EGENERIC;
    }

    p_playlist->p_private = (void *)p_export;
    /* Lock the playlist */
    vlc_mutex_lock( &p_playlist->object_lock );

    /* And call the module ! All work is done now */
    p_module = module_Need( p_playlist, "playlist export", psz_type, VLC_TRUE);
    if( !p_module )
    {
        msg_Warn( p_playlist, "exporting playlist failed" );
        vlc_mutex_unlock( &p_playlist->object_lock );
        return VLC_ENOOBJ;
    }
    module_Unneed( p_playlist , p_module );

    /* Clean up */
    fclose( p_export->p_file );
    if ( p_export->psz_filename )
        free( p_export->psz_filename );
    free ( p_export );
    p_playlist->p_private = NULL;
    vlc_mutex_unlock( &p_playlist->object_lock );

    return VLC_SUCCESS;
}
Ejemplo n.º 6
0
void savePreset(char * filename) {

  FILE * fs;

  if (filename == NULL)
    return;
  
  /* Open the file corresponding to pathname */
  if ((fs = utf8_fopen(filename, "w+")) == 0) {
    if (PRESET_DEBUG) printf("savePreset: failed to create filename \"%s\"!\n", filename);
    return;	
  }

  write_stream = fs;

  if (write_preset_name(fs) < 0) {
    write_stream = NULL;
    fclose(fs);
    return;
  }

  if (write_init_conditions(fs) < 0) {
    write_stream = NULL;
    fclose(fs);
    return;
  }

  if (write_per_frame_init_equations(fs) < 0) {
    write_stream = NULL;
    fclose(fs);
    return;
  }

  if (write_per_frame_equations(fs) < 0) {
    write_stream = NULL;
    fclose(fs);
    return;
  }

  if (write_per_pixel_equations(fs) < 0) {
    write_stream = NULL;
    fclose(fs);
    return;
  }
 
  write_stream = NULL;
  fclose(fs);

}
Ejemplo n.º 7
0
int playlist_Export( playlist_t * p_playlist, const char *psz_filename,
                     playlist_item_t *p_export_root, const char *psz_type )
{
    if( p_export_root == NULL ) return VLC_EGENERIC;

    playlist_export_t *p_export =
        vlc_custom_create( p_playlist, sizeof( *p_export ), VLC_OBJECT_GENERIC,
                           "playlist export" );
    if( !p_export )
        return VLC_ENOMEM;

    vlc_object_attach( p_export, p_playlist );
    msg_Dbg( p_export, "saving %s to file %s",
             p_export_root->p_input->psz_name, psz_filename );

    int ret = VLC_EGENERIC;

    /* Prepare the playlist_export_t structure */
    p_export->p_root = p_export_root;
    p_export->psz_filename = psz_filename;
    p_export->p_file = utf8_fopen( psz_filename, "wt" );
    if( p_export->p_file == NULL )
        msg_Err( p_export, "could not create playlist file %s (%m)",
                 psz_filename );
    else
    {
        module_t *p_module;

        /* And call the module ! All work is done now */
        playlist_Lock( p_playlist );
        p_module = module_need( p_export, "playlist export", psz_type, true );
        playlist_Unlock( p_playlist );

        if( p_module == NULL )
            msg_Err( p_playlist, "could not export playlist" );
        else
        {
            module_unneed( p_export, p_module );
            ret = VLC_SUCCESS;
        }
        fclose( p_export->p_file );
   }
   vlc_object_release( p_export );
   return ret;
}
Ejemplo n.º 8
0
int playlist_SaveArt( playlist_t *p_playlist, input_item_t *p_item,
                      const uint8_t *p_buffer, int i_buffer, const char *psz_type )
{
    char *psz_filename = ArtCacheName( p_item, psz_type );

    if( !psz_filename )
        return VLC_EGENERIC;

    char *psz_uri = make_URI( psz_filename );
    if( !psz_uri )
    {
        free( psz_filename );
        return VLC_EGENERIC;
    }

    /* Check if we already dumped it */
    struct stat s;
    if( !utf8_stat( psz_filename, &s ) )
    {
        input_item_SetArtURL( p_item, psz_uri );
        free( psz_filename );
        free( psz_uri );
        return VLC_SUCCESS;
    }

    /* Dump it otherwise */
    FILE *f = utf8_fopen( psz_filename, "wb" );
    if( f )
    {
        if( fwrite( p_buffer, i_buffer, 1, f ) != 1 )
        {
            msg_Err( p_playlist, "%s: %m", psz_filename );
        }
        else
        {
            msg_Dbg( p_playlist, "album art saved to %s", psz_filename );
            input_item_SetArtURL( p_item, psz_uri );
        }
        fclose( f );
    }
    free( psz_filename );
    free( psz_uri );
    return VLC_SUCCESS;
}
Ejemplo n.º 9
0
/****************************************************************************
 * Helpers
 ****************************************************************************/
static int Start( stream_t *s, const char *psz_extension )
{
    stream_sys_t *p_sys = s->p_sys;

    char *psz_file;
    FILE *f;

    /* */
    if( !psz_extension )
        psz_extension = "dat";

    /* Retreive path */
    char *psz_path = var_CreateGetNonEmptyString( s, "input-record-path" );
    if( !psz_path )
        psz_path = config_GetUserDir( VLC_DOWNLOAD_DIR );

    if( !psz_path )
        return VLC_ENOMEM;

    /* Create file name
     * TODO allow prefix configuration */
    psz_file = input_CreateFilename( VLC_OBJECT(s), psz_path, INPUT_RECORD_PREFIX, psz_extension );

    free( psz_path );

    if( !psz_file )
        return VLC_ENOMEM;

    f = utf8_fopen( psz_file, "wb" );
    if( !f )
    {
        free( psz_file );
        return VLC_EGENERIC;
    }
    msg_Dbg( s, "Recording into %s", psz_file );
    free( psz_file );

    /* */
    p_sys->f = f;
    p_sys->b_error = false;
    return VLC_SUCCESS;
}
Ejemplo n.º 10
0
int file_reset(int remove) {
	int result = 0;

	file_close();

	snprintf(g_filename, PATH_SIZE, "%s/synchro_simple.txt", g_tmp_dir);
	if (remove) {
		utf8_unlink(g_filename);
	}
	g_file_full = FALSE;
	g_total_op = 0;
	g_fd = utf8_fopen(g_filename, "ab");
	if (!g_fd) {
		ERROR_LOG("Cannot open file %s. Error(%d): %s\n", g_filename, errno, strerror(errno));
		result = errno;
		goto cleanup;
	}

cleanup:
	return result;
}
Ejemplo n.º 11
0
/**
 * try to open the csv file in w mode
 *
 * \param filename
 *
 * \return a FILE pointer or NULL if problem
 * */
static FILE *gsb_csv_export_open_file ( const gchar *filename )
{
    FILE *csv_file;

    /* Création du fichier, si pb, on marque l'erreur et passe au fichier suivant */
    csv_file = utf8_fopen ( filename, "w" );
    if ( ! csv_file )
    {
        gchar *sMessage = NULL;

        sMessage = g_strdup_printf ( _("Unable to create file \"%s\" :\n%s"),
                         filename, g_strerror ( errno ) );
        dialogue ( sMessage );

        g_free ( sMessage );

        return NULL;
    }

    return csv_file;
}
Ejemplo n.º 12
0
void logInit(const QString &filename)
{
  logfp = utf8_fopen(filename.toUtf8().data(), "w");
  if (!logfp) {
    logfp = stderr;
  }
#ifdef Q_OS_WIN
  /* Windows does not support line-buffering, so use no buffering */
  setvbuf(logfp, NULL, _IONBF, 0);

  /* Also unbuffer stderr when qDebug() cannot be used (non-GUI threads) */
  setvbuf(stderr, NULL, _IONBF, 0);
#else
  setvbuf(logfp, NULL, _IOLBF, 0); /* use line buffering */
#endif

  QLoggingCategory::setFilterRules(QStringLiteral("*.debug=true\nqt.*.debug=false"));
  qInstallMessageHandler(logMsgHandler);

  qDebug(APPNAME " %s (%s)", VERSION, COMMIT_ID);
  logSystemInformation();
}
Ejemplo n.º 13
0
/**
 * Initialization function for the html backend.
 *
 * \return TRUE on succes, FALSE otherwise.
 */
gint html_initialise ( GSList * opes_selectionnees, gchar * filename )
{
    g_return_val_if_fail ( filename, FALSE );

    html_lastline = -1;
    html_lastcol = 0;
    html_last_is_hsep = FALSE;
    html_first_line = TRUE;

    html_out = utf8_fopen ( filename, "w" );
    if ( ! html_out )
    {
      dialogue_error_hint ( _("Make sure file exists and is writable."),
			   g_strdup_printf (_("Cannot open file '%s' for writing"), filename));
      return FALSE;
    }

    fprintf (html_out, 
	     "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"
	     "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
	     "  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n"
	     "<html>\n"
	     "  <head>\n"
	     "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
	     "    <title>");

    if (!gsb_gui_navigation_get_current_report ())
	return FALSE;

    html_safe (etats_titre(gsb_gui_navigation_get_current_report ()));
    fprintf (html_out, 
	     "</title>\n"
	     "  </head>\n\n"
	     "  <body>\n"
	     "    <table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n\n");

    return TRUE;
}
Ejemplo n.º 14
0
/**
 * Reads ACL entries from a file.
 *
 * @param p_acl ACL object in which to insert parsed entries.
 * @param psz_patch filename from which to parse entries.
 *
 * @return 0 on success, -1 on error.
 */
int ACL_LoadFile( vlc_acl_t *p_acl, const char *psz_path )
{
    FILE *file;

    if( p_acl == NULL )
        return -1;

    file = utf8_fopen( psz_path, "r" );
    if( file == NULL )
        return -1;

    msg_Dbg( p_acl->p_owner, "find .hosts in dir=%s", psz_path );

    while( !feof( file ) )
    {
        char line[1024], *psz_ip, *ptr;

        if( fgets( line, sizeof( line ), file ) == NULL )
        {
            if( ferror( file ) )
            {
                msg_Err( p_acl->p_owner, "error reading %s : %m", psz_path );
                goto error;
            }
            continue;
        }

        /* fgets() is cool : never overflow, always nul-terminate */
        psz_ip = line;

        /* skips blanks - cannot overflow given '\0' is not space */
        while( isspace( *psz_ip ) )
            psz_ip++;

        if( *psz_ip == '\0' ) /* empty/blank line */
            continue;

        ptr = strchr( psz_ip, '\n' );
        if( ptr == NULL )
        {
            msg_Warn( p_acl->p_owner, "skipping overly long line in %s",
                      psz_path);
            do
            {
                if( fgets( line, sizeof( line ), file ) == NULL )
                {
                     if( ferror( file ) )
                     {
                         msg_Err( p_acl->p_owner, "error reading %s : %m",
                                  psz_path );
                     }
                     goto error;
                }
            }
            while( strchr( line, '\n' ) == NULL);

            continue; /* skip unusable line */
        }

        /* skips comment-only line */
        if( *psz_ip == '#' )
            continue;

        /* looks for first space, CR, LF, etc. or end-of-line comment */
        /* (there is at least a linefeed) */
        for( ptr = psz_ip; ( *ptr != '#' ) && !isspace( *ptr ); ptr++ );

        *ptr = '\0';

        msg_Dbg( p_acl->p_owner, "restricted to %s", psz_ip );

        ptr = strchr( psz_ip, '/' );
        if( ptr != NULL )
            *ptr++ = '\0'; /* separate address from mask length */

        if( (ptr != NULL)
            ? ACL_AddNet( p_acl, psz_ip, atoi( ptr ), true )
            : ACL_AddHost( p_acl, psz_ip, true ) )
        {
            msg_Err( p_acl->p_owner, "cannot add ACL from %s", psz_path );
            continue;
        }
    }

    fclose( file );
    return 0;

error:
    fclose( file );
    return -1;
}
Ejemplo n.º 15
0
/**
 * create a qif export, according to the filename, the account
 * and eventually, limit the export to the archive if exists
 * this will export all the transactions of the account (except if we ask for an archive...)
 * 	including the archived transactions
 *
 * \param filename that file will be checked and ask to overwrite if needed
 * \param account_nb
 * \param archive_number if 0, just export in qif the account transactions ; if non 0, export just the transactions for that archive and account
 *
 * \return TRUE ok, FALSE pb
 */
gboolean qif_export ( const gchar *filename,
                        gint account_nb,
                        gint archive_number )
{
    FILE * fichier_qif;
    GSList *list_tmp_transactions;
    gint beginning;
    gint floating_point;
	gchar* tmpstr;

    if (!gsb_file_util_test_overwrite (filename))
	return FALSE;

    if ( !( fichier_qif = utf8_fopen ( filename, "w" ) ))
    {
	dialogue_error_hint ( g_strerror(errno),
			      g_strdup_printf ( _("Error opening file '%s'"),
						filename ) );
	return FALSE;
    }

    /* get the floating point of the currency of the amount,
     * ie the number of digits after the . */
    floating_point = gsb_data_currency_get_floating_point (gsb_data_account_get_currency (account_nb));

    /* kind of account */
    if ( gsb_data_account_get_kind (account_nb) == GSB_TYPE_CASH )
	fprintf ( fichier_qif,
		  "!Type:Cash\n" );
    else
	if ( gsb_data_account_get_kind (account_nb) == GSB_TYPE_LIABILITIES
	     ||
	     gsb_data_account_get_kind (account_nb) == GSB_TYPE_ASSET )
	    fprintf ( fichier_qif,
		      "!Type:Oth L\n" );
	else
	    fprintf ( fichier_qif,
		      "!Type:Bank\n" );


    list_tmp_transactions = gsb_data_transaction_get_complete_transactions_list ();
    beginning = 1;

    while ( list_tmp_transactions )
    {
	gint transaction_number_tmp;
	transaction_number_tmp = gsb_data_transaction_get_transaction_number (list_tmp_transactions -> data);

	if ( gsb_data_transaction_get_account_number (transaction_number_tmp) == account_nb
	     &&
	     (!archive_number
	      ||
	      gsb_data_transaction_get_archive_number (transaction_number_tmp) == archive_number))
	{
	    if ( beginning )
	    {
		/* this is the beginning of the qif file, we set some beginnings things */
		fprintf ( fichier_qif,
			  "D%d/%d/%d\n",
			  g_date_get_day (gsb_data_transaction_get_date (transaction_number_tmp)),
			  g_date_get_month (gsb_data_transaction_get_date (transaction_number_tmp)),
			  g_date_get_year (gsb_data_transaction_get_date (transaction_number_tmp)));

		/* met le solde initial */
		tmpstr = utils_real_get_string (gsb_data_account_get_init_balance (account_nb, -1));
		fprintf ( fichier_qif,
			  "T%s\n",
			  tmpstr);
		g_free ( tmpstr );

		fprintf ( fichier_qif,
			  "CX\nPOpening Balance\n" );

		/* met le nom du imported_account */

		fprintf ( fichier_qif,
			  "L%s\n^\n",
			  g_strconcat ( "[",
					gsb_data_account_get_name (account_nb),
					"]",
					NULL ) );
		beginning = 0;
	    }

	    /* si c'est une opé de ventil, on la saute pas elle sera recherchée quand */
	    /* son opé ventilée sera exportée */

	    if ( !gsb_data_transaction_get_mother_transaction_number ( transaction_number_tmp))
	    {
		/* met la date */

		fprintf ( fichier_qif,
			  "D%d/%d/%d\n",
			  g_date_get_day (gsb_data_transaction_get_date (transaction_number_tmp)),
			  g_date_get_month (gsb_data_transaction_get_date (transaction_number_tmp)),
			  g_date_get_year (gsb_data_transaction_get_date (transaction_number_tmp)));

		/* met le pointage */

		if ( gsb_data_transaction_get_marked_transaction ( transaction_number_tmp)== OPERATION_POINTEE
		     ||
		     gsb_data_transaction_get_marked_transaction ( transaction_number_tmp)== OPERATION_TELERAPPROCHEE )
		    fprintf ( fichier_qif,
			      "C*\n" );
		else
		    if ( gsb_data_transaction_get_marked_transaction ( transaction_number_tmp)== OPERATION_RAPPROCHEE )
			fprintf ( fichier_qif,
				  "CX\n" );


		/* met les notes */

		if ( gsb_data_transaction_get_notes ( transaction_number_tmp))
		    fprintf ( fichier_qif,
			      "M%s\n",
			      gsb_data_transaction_get_notes ( transaction_number_tmp));


		/* met le montant, transforme la devise si necessaire */
		tmpstr = utils_real_get_string (gsb_data_transaction_get_adjusted_amount ( transaction_number_tmp, floating_point));
		fprintf ( fichier_qif,
			  "T%s\n",
			  tmpstr);
		g_free ( tmpstr );

		/* met le chèque si c'est un type à numérotation automatique */
		if ( gsb_data_payment_get_automatic_numbering (gsb_data_transaction_get_method_of_payment_number (transaction_number_tmp)))
		    fprintf ( fichier_qif,
			      "N%s\n",
			      gsb_data_transaction_get_method_of_payment_content ( transaction_number_tmp));

		/* met le tiers */

		fprintf ( fichier_qif,
			  "P%s\n",
			  gsb_data_payee_get_name ( gsb_data_transaction_get_party_number ( transaction_number_tmp),
						    FALSE ));

		/*  on met soit un virement, soit une ventil, soit les catégories */

		/* si c'est une imported_splitted, on recherche toutes les opés de cette imported_splitted */
		/* et les met à la suite */
		/* la catégorie de l'opé sera celle de la première opé de imported_splitted */

		if ( gsb_data_transaction_get_split_of_transaction ( transaction_number_tmp))
		{
		    /* it's a split of transactions, look for the children and append them */

		    gint mother_transaction_category_written;
		    GSList *list_tmp_transactions_2;

		    mother_transaction_category_written = 0;
		    list_tmp_transactions_2 = gsb_data_transaction_get_transactions_list ();

		    while ( list_tmp_transactions_2 )
		    {
			gint transaction_number_tmp_2;
			transaction_number_tmp_2 = gsb_data_transaction_get_transaction_number (list_tmp_transactions_2 -> data);

			if (gsb_data_transaction_get_mother_transaction_number (transaction_number_tmp_2) == transaction_number_tmp)
			{
			    /* we are on a child, for the first one, we set the mother category */
			    /*  the child can only be a normal category or a transfer */

			    if ( gsb_data_transaction_get_contra_transaction_number (transaction_number_tmp_2) > 0)
			    {
				/* the child is a transfer */

				if ( !mother_transaction_category_written )
				{
				    fprintf ( fichier_qif,
					      "L%s\n",
					      g_strconcat ( "[",
							    gsb_data_account_get_name (gsb_data_transaction_get_contra_transaction_account (transaction_number_tmp_2)),
							    "]",
							    NULL ));
				    mother_transaction_category_written = 1;
				}
				fprintf ( fichier_qif,
					  "S%s\n",
					  g_strconcat ( "[",
							gsb_data_account_get_name (gsb_data_transaction_get_contra_transaction_account ( transaction_number_tmp_2)),
							"]",
							NULL ));
			    }
			    else
			    {
				/* it's a category : sub-category */

				if ( !mother_transaction_category_written )
				{
				    fprintf ( fichier_qif,
					      "L%s\n",
					      gsb_data_category_get_name (gsb_data_transaction_get_category_number (transaction_number_tmp_2),
									  gsb_data_transaction_get_sub_category_number (transaction_number_tmp_2),
									  _("No category defined")));
				    mother_transaction_category_written = 1;
				}
				fprintf ( fichier_qif,
					  "S%s\n",
					  gsb_data_category_get_name (gsb_data_transaction_get_category_number (transaction_number_tmp_2),
								      gsb_data_transaction_get_sub_category_number (transaction_number_tmp_2),
								      _("No category defined")));
			    }

			    /* set the notes of the split child */

			    if ( gsb_data_transaction_get_notes (transaction_number_tmp_2))
				fprintf ( fichier_qif,
					  "E%s\n",
					  gsb_data_transaction_get_notes (transaction_number_tmp_2));

			    /* set the amount of the split child */

			    tmpstr = utils_real_get_string (gsb_data_transaction_get_adjusted_amount (transaction_number_tmp_2, floating_point));
			    fprintf ( fichier_qif,
				      "$%s\n",
				      tmpstr);
			    g_free ( tmpstr );
			}
			list_tmp_transactions_2 = list_tmp_transactions_2 -> next;
		    }
		}
		else
		{
		    /* if it's a transfer, the contra-account must exist, else we do
		     * as for a normal category */

		    if ( gsb_data_transaction_get_contra_transaction_number (transaction_number_tmp) > 0 )
		    {
			/* it's a transfer */

			fprintf ( fichier_qif,
				  "L%s\n",
				  g_strconcat ( "[",
						gsb_data_account_get_name (gsb_data_transaction_get_contra_transaction_account ( transaction_number_tmp)),
						"]",
						NULL ));
		    }
		    else
		    {
			/* it's a normal category */

			fprintf ( fichier_qif,
				  "L%s\n",
				  gsb_data_category_get_name (gsb_data_transaction_get_category_number (transaction_number_tmp),
							      gsb_data_transaction_get_sub_category_number (transaction_number_tmp),
							      FALSE ));
		    }
		}
		fprintf ( fichier_qif,
			  "^\n" );
	    }
	}
	list_tmp_transactions = list_tmp_transactions -> next;
    }

    if ( beginning )
    {
	/* there is no transaction in the account, so do the opening of the account, bug no date */
	/* met le solde initial */

	gchar* tmpstr = utils_real_get_string (gsb_data_account_get_init_balance (account_nb, -1));
	fprintf ( fichier_qif,
		  "T%s\n",
		  tmpstr);
	g_free ( tmpstr );

	fprintf ( fichier_qif,
		  "CX\nPOpening Balance\n" );

	/* met le nom du imported_account */

	fprintf ( fichier_qif,
		  "L%s\n^\n",
		  g_strconcat ( "[",
				gsb_data_account_get_name (account_nb),
				"]",
				NULL ) );
    }
    fclose ( fichier_qif );
    return TRUE;
}
Ejemplo n.º 16
0
Archivo: switcher.c Proyecto: Kafay/vlc
/*****************************************************************************
 * UnpackFromFile: Read a YUV picture and store it in our format
 *****************************************************************************/
static int UnpackFromFile( sout_stream_t *p_stream, const char *psz_file,
                           int i_width, int i_height,
                           picture_t *p_pic )
{
    int i, j;
    FILE *p_file = utf8_fopen( psz_file, "r" );

    if ( p_file == NULL )
    {
        msg_Err( p_stream, "file %s not found", psz_file );
        return -1;
    }

    if( picture_Setup( p_pic, VLC_CODEC_I420,
                       i_width, i_height,
                       i_width * VOUT_ASPECT_FACTOR / i_height ) )
    {
        msg_Err( p_stream, "unknown chroma" );
        return -1;
    }
    for ( i = 0; i < p_pic->i_planes; i++ )
    {
        p_pic->p[i].p_pixels = malloc( p_pic->p[i].i_lines *
                                           p_pic->p[i].i_pitch );
        memset( p_pic->p[i].p_pixels, 0, p_pic->p[i].i_lines *
                    p_pic->p[i].i_pitch );
    }

    for ( i = 0; i < i_height; i++ )
    {
        int i_chroma;
        uint8_t p_buffer[i_width * 2];
        uint8_t *p_char = p_buffer;
        uint8_t *p_y = &p_pic->p[0].p_pixels[i * p_pic->p[0].i_pitch];
        uint8_t *p_u = &p_pic->p[1].p_pixels[i/2 * p_pic->p[1].i_pitch];
        uint8_t *p_v = &p_pic->p[2].p_pixels[i/2 * p_pic->p[2].i_pitch];

        if ( fread( p_buffer, 2, i_width, p_file ) != (size_t)i_width )
        {
            msg_Err( p_stream, "premature end of file %s", psz_file );
            fclose( p_file );
            for ( i = 0; i < p_pic->i_planes; i++ )
            {
                free( p_pic->p[i].p_pixels );
            }
            return -1;
        }

        i_chroma = 0;
        for ( j = 0; j < i_width; j++ )
        {
            uint8_t **pp_chroma = i_chroma ? &p_v : &p_u;
            i_chroma = !i_chroma;
            if ( i & 1 )
                **pp_chroma = (**pp_chroma + *p_char + 1) / 2;
            else
                **pp_chroma = *p_char;
            (*pp_chroma)++;
            p_char++;
            *p_y++ = *p_char++;
        }
    }

    fclose( p_file );
    return 0;
}
Ejemplo n.º 17
0
Archivo: dump.c Proyecto: squadette/vlc
static void Trigger (access_t *access)
{
    access_sys_t *p_sys = access->p_sys;

    if (p_sys->stream == NULL)
        return; // too late

    if (p_sys->tmp_max == -1)
        return; // already triggered - should we stop? FIXME

    time_t now;
    time (&now);

    struct tm t;
    if (localtime_r (&now, &t) == NULL)
        return; // No time, eh? Well, I'd rather not run on your computer.

    if (t.tm_year > 999999999)
        // Humanity is about 300 times older than when this was written,
        // and there is an off-by-one in the following sprintf().
        return;

    const char *home = config_GetHomeDir();

    /* Hmm what about the extension?? */
    char filename[strlen (home) + sizeof ("/vlcdump-YYYYYYYYY-MM-DD-HH-MM-SS.ts")];
    sprintf (filename, "%s/vlcdump-%04u-%02u-%02u-%02u-%02u-%02u.ts", home,
             t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);

    msg_Info (access, "dumping media to \"%s\"...", filename);

    FILE *newstream = utf8_fopen (filename, "wb");
    if (newstream == NULL)
    {
        msg_Err (access, "cannot create dump file \"%s\": %m", filename);
        return;
    }

    /* This might cause excessive hard drive work :( */
    FILE *oldstream = p_sys->stream;
    rewind (oldstream);

    for (;;)
    {
        char buf[16384];
        size_t len = fread (buf, 1, sizeof (buf), oldstream);
        if (len == 0)
        {
            if (ferror (oldstream))
            {
                msg_Err (access, "cannot read temporary file: %m");
                break;
            }

            /* Done with temporary file */
            fclose (oldstream);
            p_sys->stream = newstream;
            p_sys->tmp_max = -1;
            return;
        }

        if (fwrite (buf, len, 1, newstream) != 1)
        {
            msg_Err (access, "cannot write dump file: %m");
            break;
        }
    }

    /* Failed to copy temporary file */
    fseek (oldstream, 0, SEEK_END);
    fclose (newstream);
    return;
}
Ejemplo n.º 18
0
/*****************************************************************************
 * Open: open a dummy audio device
 *****************************************************************************/
static int Open( vlc_object_t * p_this )
{
    aout_instance_t * p_aout = (aout_instance_t *)p_this;
    char * psz_name, * psz_format;
    const char * const * ppsz_compare = format_list;
    int i_channels, i = 0;

    psz_name = var_CreateGetString( p_this, "audiofile-file" );
    if( !psz_name || !*psz_name )
    {
        msg_Err( p_aout, "you need to specify an output file name" );
        free( psz_name );
        return VLC_EGENERIC;
    }

    /* Allocate structure */
    p_aout->output.p_sys = malloc( sizeof( aout_sys_t ) );
    if( p_aout->output.p_sys == NULL )
        return VLC_ENOMEM;

    if( !strcmp( psz_name, "-" ) )
        p_aout->output.p_sys->p_file = stdout;
    else
        p_aout->output.p_sys->p_file = utf8_fopen( psz_name, "wb" );

    free( psz_name );
    if ( p_aout->output.p_sys->p_file == NULL )
    {
        free( p_aout->output.p_sys );
        return VLC_EGENERIC;
    }

    p_aout->output.pf_play = Play;

    /* Audio format */
    psz_format = var_CreateGetString( p_this, "audiofile-format" );

    while ( *ppsz_compare != NULL )
    {
        if ( !strncmp( *ppsz_compare, psz_format, strlen(*ppsz_compare) ) )
        {
            break;
        }
        ppsz_compare++; i++;
    }

    if ( *ppsz_compare == NULL )
    {
        msg_Err( p_aout, "cannot understand the format string (%s)",
                 psz_format );
        if( p_aout->output.p_sys->p_file != stdout )
            fclose( p_aout->output.p_sys->p_file );
        free( p_aout->output.p_sys );
        free( psz_format );
        return VLC_EGENERIC;
    }
    free( psz_format );

    p_aout->output.output.i_format = format_int[i];
    if ( AOUT_FMT_NON_LINEAR( &p_aout->output.output ) )
    {
        p_aout->output.i_nb_samples = A52_FRAME_NB;
        p_aout->output.output.i_bytes_per_frame = AOUT_SPDIF_SIZE;
        p_aout->output.output.i_frame_length = A52_FRAME_NB;
        aout_VolumeNoneInit( p_aout );
    }
    else
    {
        p_aout->output.i_nb_samples = FRAME_SIZE;
        aout_VolumeSoftInit( p_aout );
    }

    /* Channels number */
    i_channels = var_CreateGetInteger( p_this, "audiofile-channels" );

    if( i_channels > 0 && i_channels <= CHANNELS_MAX )
    {
        p_aout->output.output.i_physical_channels =
            pi_channels_maps[i_channels];
    }

    /* WAV header */
    p_aout->output.p_sys->b_add_wav_header = var_CreateGetBool( p_this,
                                                        "audiofile-wav" );

    if( p_aout->output.p_sys->b_add_wav_header )
    {
        /* Write wave header */
        WAVEHEADER *wh = &p_aout->output.p_sys->waveh;

        memset( wh, 0, sizeof(wh) );

        switch( p_aout->output.output.i_format )
        {
        case VLC_CODEC_FL32:
            wh->Format     = WAVE_FORMAT_IEEE_FLOAT;
            wh->BitsPerSample = sizeof(float) * 8;
            break;
        case VLC_CODEC_U8:
            wh->Format     = WAVE_FORMAT_PCM;
            wh->BitsPerSample = 8;
            break;
        case VLC_CODEC_S16L:
        default:
            wh->Format     = WAVE_FORMAT_PCM;
            wh->BitsPerSample = 16;
            break;
        }

        wh->MainChunkID = VLC_FOURCC('R', 'I', 'F', 'F');
        wh->Length = 0;                    /* temp, to be filled in as we go */
        wh->ChunkTypeID = VLC_FOURCC('W', 'A', 'V', 'E');
        wh->SubChunkID = VLC_FOURCC('f', 'm', 't', ' ');
        wh->SubChunkLength = 16;

        wh->Modus = aout_FormatNbChannels( &p_aout->output.output );
        wh->SampleFreq = p_aout->output.output.i_rate;
        wh->BytesPerSample = wh->Modus * ( wh->BitsPerSample / 8 );
        wh->BytesPerSec = wh->BytesPerSample * wh->SampleFreq;

        wh->DataChunkID = VLC_FOURCC('d', 'a', 't', 'a');
        wh->DataLength = 0;                /* temp, to be filled in as we go */

        /* Header -> little endian format */
        SetWLE( &wh->Format, wh->Format );
        SetWLE( &wh->BitsPerSample, wh->BitsPerSample );
        SetDWLE( &wh->SubChunkLength, wh->SubChunkLength );
        SetWLE( &wh->Modus, wh->Modus );
        SetDWLE( &wh->SampleFreq, wh->SampleFreq );
        SetWLE( &wh->BytesPerSample, wh->BytesPerSample );
        SetDWLE( &wh->BytesPerSec, wh->BytesPerSec );

        if( fwrite( wh, sizeof(WAVEHEADER), 1,
                    p_aout->output.p_sys->p_file ) != 1 )
        {
            msg_Err( p_aout, "write error (%m)" );
        }
    }

    return 0;
}
Ejemplo n.º 19
0
/**
 * Manually parse a gnucash file, tidy it, put result in a temporary
 * file and parse it via libxml.
 *
 * \param filename	Filename to parse.
 *
 * \return		A pointer to a xmlDocPtr containing XML representation of file.
 */
xmlDocPtr parse_gnucash_file ( gchar * filename )
{
  gchar buffer[1024], *tempname;
  FILE * filein, * tempfile;
  xmlDocPtr doc;

  filein = utf8_fopen ( filename, "r" );
  if ( ! filein )
  {
      dialogue_error_hint ( g_strdup_printf ( _("Either file \"%s\" does not exist or it is not a regular file."),
					      filename ),
			    g_strdup_printf ( _("Error opening file '%s'." ), filename ) );
      return NULL;
  }

  tempname = g_strdup_printf ( "gsbgnc%05d", g_random_int_range (0,99999) );
  tempfile = utf8_fopen ( tempname, "w" );
  if ( ! tempfile )
  {
    gchar *tmp_str;
    gchar *tmp_str_2;

    tmp_str = g_strdup ( _("Grisbi needs to open a temporary file in order to import Gnucash data "
                        "but file can't be created.\n"
                        "Check that you have permission to do that.") );
    tmp_str_2 = g_strdup_printf ( _("Error opening temporary file '%s'." ), tempname );

    dialogue_error_hint ( tmp_str, tmp_str_2 );

    g_free ( tmp_str );
    g_free ( tmp_str_2 );

      return NULL;
  }

  /**
   * We need to create a temporary file because Gnucash writes XML
   * files that do not respect the XML specification regarding
   * namespaces.  We need to tidy XML file in order to let libxml
   * handle it gracefully.
   */
  while ( fgets ( buffer, 1024, filein ) )
  {
    gchar * tag;
    tag = g_strrstr ( buffer, "<gnc-v2>" );

    if ( tag )
	{
        gchar *ns[14] = { "gnc", "cd", "book", "act", "trn", "split", "cmdty",
                        "ts", "slots", "slot", "price", "sx", "fs", NULL };
        gchar **iter;

        tag += 7;
        *tag = 0;
        tag++;

	    fputs ( buffer, tempfile );
	    for ( iter = ns ; *iter != NULL ; iter++ )
        {
            gchar *header;

            header = g_strdup_printf (
                        "  xmlns:%s=\"http://www.gnucash.org/lxr/gnucash/source/src/doc/xml/%s-v1.dtd#%s\"\n",
                        *iter, *iter, *iter );
            fputs ( header, tempfile );
            g_free ( header );
	    }
        fputs ( ">\n", tempfile );
	}
    else
	{
	  fputs ( buffer, tempfile );
	}
  }
  fclose ( filein );
  fclose ( tempfile );

  doc = xmlParseFile( g_filename_from_utf8 ( tempname, -1, NULL, NULL, NULL ) );

  /** Once parsed, the temporary file is removed as it is useless.  */
  g_unlink ( tempname );

  return doc;
}
Ejemplo n.º 20
0
static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
{
    char *psz_filename = config_GetConfigFile( p_obj );
    if( psz_filename == NULL )
        return NULL;

    msg_Dbg( p_obj, "opening config file (%s)", psz_filename );

    FILE *p_stream = utf8_fopen( psz_filename, "rt" );
    if( p_stream == NULL && errno != ENOENT )
    {
        msg_Err( p_obj, "cannot open config file (%s): %m",
                 psz_filename );

    }
#if !( defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS) )
    else if( p_stream == NULL && errno == ENOENT )
    {
        /* This is the fallback for pre XDG Base Directory
         * Specification configs */
        char *home = config_GetUserDir(VLC_HOME_DIR);
        char *psz_old;

        if( home != NULL
         && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
                      home ) != -1 )
        {
            p_stream = utf8_fopen( psz_old, "rt" );
            if( p_stream )
            {
                /* Old config file found. We want to write it at the
                 * new location now. */
                msg_Info( p_obj->p_libvlc, "Found old config file at %s. "
                          "VLC will now use %s.", psz_old, psz_filename );
                char *psz_readme;
                if( asprintf(&psz_readme,"%s/.vlc/README",
                             home ) != -1 )
                {
                    FILE *p_readme = utf8_fopen( psz_readme, "wt" );
                    if( p_readme )
                    {
                        fprintf( p_readme, "The VLC media player "
                                 "configuration folder has moved to comply\n"
                                 "with the XDG Base Directory Specification "
                                 "version 0.6. Your\nconfiguration has been "
                                 "copied to the new location:\n%s\nYou can "
                                 "delete this directory and all its contents.",
                                  psz_filename);
                        fclose( p_readme );
                    }
                    free( psz_readme );
                }
            }
            free( psz_old );
        }
        free( home );
    }
#endif
    free( psz_filename );
    return p_stream;
}
Ejemplo n.º 21
0
/*****************************************************************************
 * Open: initialize and create stuff
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
    intf_thread_t *p_intf = (intf_thread_t *)p_this;
    intf_sys_t *p_sys;
    char *psz_mode;

    CONSOLE_INTRO_MSG;
    msg_Info( p_intf, "using logger." );

    /* Allocate instance and initialize some members */
    p_sys = p_intf->p_sys = (intf_sys_t *)malloc( sizeof( intf_sys_t ) );
    if( p_sys == NULL )
        return VLC_ENOMEM;

    p_sys->msg.p_intf = p_intf;
    p_sys->msg.i_mode = MODE_TEXT;
    psz_mode = var_CreateGetString( p_intf, "logmode" );
    if( psz_mode )
    {
        if( !strcmp( psz_mode, "text" ) )
            ;
        else if( !strcmp( psz_mode, "html" ) )
        {
            p_sys->msg.i_mode = MODE_HTML;
        }
#ifdef HAVE_SYSLOG_H
        else if( !strcmp( psz_mode, "syslog" ) )
        {
            p_sys->msg.i_mode = MODE_SYSLOG;
        }
#endif
        else
        {
            msg_Warn( p_intf, "invalid log mode `%s', using `text'", psz_mode );
            p_sys->msg.i_mode = MODE_TEXT;
        }
        free( psz_mode );
    }
    else
    {
        msg_Warn( p_intf, "no log mode specified, using `text'" );
    }

    if( p_sys->msg.i_mode != MODE_SYSLOG )
    {
        char *psz_file = config_GetPsz( p_intf, "logfile" );
        if( !psz_file )
        {
#ifdef __APPLE__
            char *home = config_GetUserDir(VLC_DOCUMENTS_DIR);
            if( home == NULL
             || asprintf( &psz_file, "%s/"LOG_DIR"/%s", home,
                (p_sys->msg.i_mode == MODE_HTML) ? LOG_FILE_HTML
                                             : LOG_FILE_TEXT ) == -1 )
                psz_file = NULL;
            free(home);
#else
            switch( p_sys->msg.i_mode )
            {
            case MODE_HTML:
                psz_file = strdup( LOG_FILE_HTML );
                break;
            case MODE_TEXT:
            default:
                psz_file = strdup( LOG_FILE_TEXT );
                break;
            }
#endif
            msg_Warn( p_intf, "no log filename provided, using `%s'",
                               psz_file );
        }

        /* Open the log file and remove any buffering for the stream */
        msg_Dbg( p_intf, "opening logfile `%s'", psz_file );
        p_sys->msg.p_file = utf8_fopen( psz_file, "at" );
        if( p_sys->msg.p_file == NULL )
        {
            msg_Err( p_intf, "error opening logfile `%s'", psz_file );
            free( p_sys );
            free( psz_file );
            return -1;
        }
        setvbuf( p_sys->msg.p_file, NULL, _IONBF, 0 );

        free( psz_file );

        switch( p_sys->msg.i_mode )
        {
        case MODE_HTML:
            fputs( HTML_HEADER, p_sys->msg.p_file );
            break;
        case MODE_TEXT:
        default:
            fputs( TEXT_HEADER, p_sys->msg.p_file );
            break;
        }

    }
    else
    {
        p_sys->msg.p_file = NULL;
#ifdef HAVE_SYSLOG_H
        int i_facility;
        char *psz_facility = var_CreateGetString( p_intf, "syslog-facility" );
        if( psz_facility )
        {
            bool b_valid = 0;
            for( size_t i = 0; i < fac_entries; ++i )
            {
                if( !strcmp( psz_facility, fac_name[i] ) )
                {
                    i_facility = fac_number[i];
                    b_valid = 1;
                    break;
                }
            }
            if( !b_valid )
            {
                msg_Warn( p_intf, "invalid syslog facility `%s', using `%s'",
                          psz_facility, fac_name[0] );
                i_facility = fac_number[0];
            }
            free( psz_facility );
        }
        else
        {
            msg_Warn( p_intf, "no syslog facility specified, using `%s'",
                      fac_name[0] );
            i_facility = fac_number[0];
        }

        openlog( "vlc", LOG_PID|LOG_NDELAY, i_facility );
#endif
    }

    p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, Overflow, &p_sys->msg );

    return 0;
}
Ejemplo n.º 22
0
/* Parse a directory and recursively add files */
int ParseDirectory( intf_thread_t *p_intf, char *psz_root,
                        char *psz_dir )
{
    intf_sys_t     *p_sys = p_intf->p_sys;
    char           dir[MAX_DIR_SIZE];
    DIR           *p_dir;
    vlc_acl_t     *p_acl;
    FILE          *file;

    char          *user = NULL;
    char          *password = NULL;

    int           i_dirlen;

    if( ( p_dir = utf8_opendir( psz_dir ) ) == NULL )
    {
        if( errno != ENOENT && errno != ENOTDIR )
            msg_Err( p_intf, "cannot open directory (%s)", psz_dir );
        return VLC_EGENERIC;
    }

    i_dirlen = strlen( psz_dir );
    if( i_dirlen + 10 > MAX_DIR_SIZE )
    {
        msg_Warn( p_intf, "skipping too deep directory (%s)", psz_dir );
        closedir( p_dir );
        return 0;
    }

    msg_Dbg( p_intf, "dir=%s", psz_dir );

    snprintf( dir, sizeof( dir ), "%s"DIR_SEP".access", psz_dir );
    if( ( file = utf8_fopen( dir, "r" ) ) != NULL )
    {
        char line[1024];
        int  i_size;

        msg_Dbg( p_intf, "find .access in dir=%s", psz_dir );

        i_size = fread( line, 1, 1023, file );
        if( i_size > 0 )
        {
            char *p;
            while( i_size > 0 && ( line[i_size-1] == '\n' ||
                   line[i_size-1] == '\r' ) )
            {
                i_size--;
            }

            line[i_size] = '\0';

            p = strchr( line, ':' );
            if( p )
            {
                *p++ = '\0';
                user = strdup( line );
                password = strdup( p );
            }
        }
        msg_Dbg( p_intf, "using user=%s (read=%d)", user, i_size );

        fclose( file );
    }

    snprintf( dir, sizeof( dir ), "%s"DIR_SEP".hosts", psz_dir );
    p_acl = ACL_Create( p_intf, false );
    if( ACL_LoadFile( p_acl, dir ) )
    {
        ACL_Destroy( p_acl );

        struct stat st;
        if( utf8_stat( dir, &st ) == 0 )
        {
            free( user );
            free( password );
            closedir( p_dir );
            return VLC_EGENERIC;
        }
        p_acl = NULL;
    }

    for( ;; )
    {
        char *psz_filename;
        /* parse psz_src dir */
        if( ( psz_filename = utf8_readdir( p_dir ) ) == NULL )
        {
            break;
        }

        if( ( psz_filename[0] == '.' )
         || ( i_dirlen + strlen( psz_filename ) > MAX_DIR_SIZE ) )
        {
            free( psz_filename );
            continue;
        }

        snprintf( dir, sizeof( dir ), "%s"DIR_SEP"%s", psz_dir, psz_filename );
        free( psz_filename );

        if( ParseDirectory( p_intf, psz_root, dir ) )
        {
            httpd_file_sys_t *f = NULL;
            httpd_handler_sys_t *h = NULL;
            bool b_index;
            char *psz_name, *psz_ext;

            psz_name = FileToUrl( &dir[strlen( psz_root )], &b_index );
            psz_ext = strrchr( dir, '.' );
            if( psz_ext != NULL )
            {
                int i;
                psz_ext++;
                for( i = 0; i < p_sys->i_handlers; i++ )
                    if( !strcmp( p_sys->pp_handlers[i]->psz_ext, psz_ext ) )
                        break;
                if( i < p_sys->i_handlers )
                {
                    f = malloc( sizeof( httpd_handler_sys_t ) );
                    h = (httpd_handler_sys_t *)f;
                    f->b_handler = true;
                    h->p_association = p_sys->pp_handlers[i];
                }
            }
            if( f == NULL )
            {
                f = malloc( sizeof( httpd_file_sys_t ) );
                f->b_handler = false;
            }

            f->p_intf  = p_intf;
            f->p_file = NULL;
            f->p_redir = NULL;
            f->p_redir2 = NULL;
            f->file = strdup (dir);
            f->name = psz_name;
            f->b_html = strstr( &dir[strlen( psz_root )], ".htm" ) || strstr( &dir[strlen( psz_root )], ".xml" ) ? true : false;

            if( !f->name )
            {
                msg_Err( p_intf , "unable to parse directory" );
                closedir( p_dir );
                free( f );
                return( VLC_ENOMEM );
            }
            msg_Dbg( p_intf, "file=%s (url=%s)",
                     f->file, f->name );

            if( !f->b_handler )
            {
                char *psz_type = strdup( "text/html; charset=UTF-8" );
                if( strstr( &dir[strlen( psz_root )], ".xml" ) )
                {
                    char *psz = strstr( psz_type, "html;" );
                    if( psz )
                    {
                        psz[0] = 'x';
                        psz[1] = 'm';
                        psz[2] = 'l';
                        psz[3] = ';';
                        psz[4] = ' ';
                    }
                }
                f->p_file = httpd_FileNew( p_sys->p_httpd_host,
                                           f->name,
                                           f->b_html ? psz_type : NULL,
                                           user, password, p_acl,
                                           HttpCallback, f );
                free( psz_type );
                if( f->p_file != NULL )
                {
                    TAB_APPEND( p_sys->i_files, p_sys->pp_files, f );
                }
            }
            else
            {
                h->p_handler = httpd_HandlerNew( p_sys->p_httpd_host,
                                                 f->name,
                                                 user, password, p_acl,
                                                 HandlerCallback, h );
                if( h->p_handler != NULL )
                {
                    TAB_APPEND( p_sys->i_files, p_sys->pp_files,
                                (httpd_file_sys_t *)h );
                }
            }

            /* for url that ends by / add
             *  - a redirect from rep to rep/
             *  - in case of index.* rep/index.html to rep/ */
            if( f && f->name[strlen(f->name) - 1] == '/' )
            {
                char *psz_redir = strdup( f->name );
                char *p;
                psz_redir[strlen( psz_redir ) - 1] = '\0';

                msg_Dbg( p_intf, "redir=%s -> %s", psz_redir, f->name );
                f->p_redir = httpd_RedirectNew( p_sys->p_httpd_host, f->name, psz_redir );
                free( psz_redir );

                if( b_index && ( p = strstr( f->file, "index." ) ) )
                {
                    if( asprintf( &psz_redir, "%s%s", f->name, p ) != -1 )
                    {
                        msg_Dbg( p_intf, "redir=%s -> %s", psz_redir, f->name );
                        f->p_redir2 = httpd_RedirectNew( p_sys->p_httpd_host,
                                                         f->name, psz_redir );

                        free( psz_redir );
                    }
                }
            }
        }
    }

    free( user );
    free( password );

    ACL_Destroy( p_acl );
    closedir( p_dir );

    return VLC_SUCCESS;
}
Ejemplo n.º 23
0
/**
 * This function will save a video snapshot to a file
 */
static int VoutWriteSnapshot( vout_thread_t *p_vout, char **ppsz_filename,
                              const block_t *p_image,
                              const char *psz_path,
                              const char *psz_format,
                              const char *psz_prefix_fmt )
{
    /* */
    char *psz_filename;
    DIR *p_path = utf8_opendir( psz_path );
    if( p_path != NULL )
    {
        /* The use specified a directory path */
        closedir( p_path );

        /* */
        char *psz_prefix = NULL;
        if( psz_prefix_fmt )
            psz_prefix = str_format( p_vout, psz_prefix_fmt );
        if( !psz_prefix )
        {
            psz_prefix = strdup( "vlcsnap-" );
            if( !psz_prefix )
                goto error;
        }

        if( var_GetBool( p_vout, "snapshot-sequential" ) )
        {
            int i_num = var_GetInteger( p_vout, "snapshot-num" );
            for( ; ; i_num++ )
            {
                struct stat st;

                if( asprintf( &psz_filename, "%s" DIR_SEP "%s%05d.%s",
                              psz_path, psz_prefix, i_num++, psz_format ) < 0 )
                {
                    free( psz_prefix );
                    goto error;
                }
                if( utf8_stat( psz_filename, &st ) )
                    break;
                free( psz_filename );
            }

            var_SetInteger( p_vout, "snapshot-num", i_num );
        }
        else
        {
            struct tm    curtime;
            time_t       lcurtime = time( NULL ) ;

            if( !localtime_r( &lcurtime, &curtime ) )
            {
                const unsigned int i_id = (p_image->i_pts / 100000) & 0xFFFFFF;

                msg_Warn( p_vout, "failed to get current time. Falling back to legacy snapshot naming" );

                if( asprintf( &psz_filename, "%s" DIR_SEP "%s%u.%s",
                              psz_path, psz_prefix, i_id, psz_format ) < 0 )
                    psz_filename = NULL;
            }
            else
            {
                /* suffix with the last decimal digit in 10s of seconds resolution
                 * FIXME gni ? */
                const int i_id = (p_image->i_pts / (100*1000)) & 0xFF;
                char psz_curtime[128];

                if( !strftime( psz_curtime, sizeof(psz_curtime), "%Y-%m-%d-%Hh%Mm%Ss", &curtime ) )
                    strcpy( psz_curtime, "error" );

                if( asprintf( &psz_filename, "%s" DIR_SEP "%s%s%1u.%s",
                              psz_path, psz_prefix, psz_curtime, i_id, psz_format ) < 0 )
                    psz_filename = NULL;
            }
        }
        free( psz_prefix );
    }
    else
    {
        /* The user specified a full path name (including file name) */
        psz_filename = str_format( p_vout, psz_path );
        path_sanitize( psz_filename );
    }

    if( !psz_filename )
        goto error;

    /* Save the snapshot */
    FILE *p_file = utf8_fopen( psz_filename, "wb" );
    if( !p_file )
    {
        msg_Err( p_vout, "Failed to open '%s'", psz_filename );
        free( psz_filename );
        goto error;
    }
    if( fwrite( p_image->p_buffer, p_image->i_buffer, 1, p_file ) != 1 )
    {
        msg_Err( p_vout, "Failed to write to '%s'", psz_filename );
        fclose( p_file );
        free( psz_filename );
        goto error;
    }
    fclose( p_file );

    /* */
    if( ppsz_filename )
        *ppsz_filename = psz_filename;
    else
        free( psz_filename );

    return VLC_SUCCESS;

error:
    msg_Err( p_vout, "could not save snapshot" );
    return VLC_EGENERIC;
}
Ejemplo n.º 24
0
/**
 * \brief Import QIF data.
 *
 * Open a QIF file and fills in data in a struct_compte_importation
 * data structure.
 *
 * \param assistant	Not used.
 * \param imported	A pointer to structure containing name and
 *			format of imported file.
 *
 * \return		TRUE on success.
 */
gboolean recuperation_donnees_qif ( GtkWidget *assistant, struct imported_file *imported )
{
    gchar *tmp_str;
    struct struct_compte_importation *imported_account;
    gint returned_value = 0;
    gboolean premier_compte = TRUE;
    FILE *qif_file;

    qif_file = utf8_fopen ( imported -> name, "r" );
    if ( ! qif_file )
        return FALSE;

    mismatch_dates = TRUE;

    /* qif_file pointe sur le qif_file qui a été reconnu comme qif */
    rewind ( qif_file );

    imported_account = g_malloc0 ( sizeof ( struct struct_compte_importation ));
    imported_account -> nom_de_compte = unique_imported_name ( _("Invalid QIF file") );
    imported_account -> filename = my_strdup ( imported -> name );
    imported_account -> origine = my_strdup ( "QIF" );

    /* save filename */
    imported_account -> real_filename = my_strdup (imported -> name);

    /* It is positioned on the first line of file */
    returned_value = get_utf8_line_from_file ( qif_file, &tmp_str, imported -> coding_system );

    do
    {
        GSList *tmp_list;
        gchar *account_name = NULL;
        gint order = 0;
        gboolean name_preced = FALSE;
        struct struct_ope_importation *imported_transaction;

        do
        {
            if (  returned_value != EOF
             &&
             tmp_str
             &&
             g_ascii_strncasecmp ( tmp_str, "!Account", 8 ) == 0 )
            {
                /* create and fill the new account */
                imported_account = g_malloc0 ( sizeof ( struct struct_compte_importation ) );
                imported_account -> origine = my_strdup ( "QIF" );

                /* save filename and account_name */
                imported_account -> real_filename = my_strdup ( imported -> name );
                imported_account -> filename = my_strdup ( imported -> name );

                account_name = gsb_qif_get_account_name ( qif_file, imported -> coding_system );
                imported_account -> nom_de_compte = unique_imported_name ( account_name );
                g_free ( account_name );

                name_preced = TRUE;
                premier_compte = FALSE;
                returned_value = get_utf8_line_from_file ( qif_file, &tmp_str, imported -> coding_system );
            }
            else if ( returned_value != EOF
             &&
             tmp_str
             &&
             g_ascii_strncasecmp ( tmp_str, "!Type:Cat", 9 ) == 0 )
            {

                do
                {
                    returned_value = gsb_qif_recupere_categories ( qif_file,
                                        imported -> coding_system );

                    if ( returned_value == 0 )
                        tmp_str = last_header;
                }
                /* continue untill the end of the file or a change of account */
                while ( returned_value != EOF && returned_value != 0 );
            }
            else if ( returned_value != EOF
             &&
             tmp_str
             &&
             g_ascii_strncasecmp ( tmp_str, "!Type", 5 ) == 0 )
            {
                gint account_type;

                account_type = gsb_qif_get_account_type ( tmp_str ) ;
                if ( account_type == -1 )
                {
                    name_preced = FALSE;
                    continue;
                }
                else
                {
                    if ( name_preced == FALSE )
                    {
                        /* create and fill the new account */
                        imported_account = g_malloc0 ( sizeof ( struct struct_compte_importation ) );
                        imported_account -> origine = my_strdup ( "QIF" );

                        /* save filename and account_name */
                        imported_account -> real_filename = my_strdup ( imported -> name );
                        imported_account -> filename = my_strdup ( imported -> name );
                        imported_account -> nom_de_compte = unique_imported_name (
                                                                my_strdup ( _("Imported QIF account" ) ) );

                        premier_compte = FALSE;
                    }

                    if ( account_type == 6 )
                    {
                        /* on considère le imported_account d'investissement comme un imported_account
                         * bancaire mais met un warning car pas implémenté, aucune idée si ça passe ou pas... */
                        gchar *msg;

                        msg = g_strdup_printf ( _("Grisbi found an investment account:\n%s\n"
                                        "which is not implemented yet.  Nevertheless, Grisbi will try "
                                        "to import it as a bank account." ),
                                        imported -> name );
                        dialogue_warning ( msg );
                        g_free ( msg );

                        account_type = 0;
                    }

                    imported_account -> type_de_compte = account_type;
                    returned_value = -2;
                }
            }
            else
                name_preced = FALSE;
        }
        while ( returned_value != EOF && returned_value != -2 );

        if ( returned_value == EOF )
        {
            if ( premier_compte )
            {
            /* no account already saved, so send an error */
                liste_comptes_importes_error = g_slist_append ( liste_comptes_importes_error,
                                        imported_account );
                fclose ( qif_file );
                return FALSE;
            }
            else
            {
                /* we have at least saved an account before, ok, enough for me */
                fclose ( qif_file );
                return TRUE;
            }
        }

        do
        {
            returned_value = gsb_qif_recupere_operations_from_account ( qif_file,
                                        imported -> coding_system,
                                        imported_account );

            if ( returned_value == 0 )
                tmp_str = last_header;
        }
        /* continue untill the end of the file or a change of account */
        while ( returned_value != EOF && returned_value != 0 );

        /* first, we need to check if the first transaction is an opening balance
         * or a normal transaction
         * update : money sometimes translate Opening balance... */
        if ( g_slist_length ( imported_account -> operations_importees) > 0 )
        {
            imported_transaction = imported_account -> operations_importees -> data;
            if ( imported_transaction -> tiers
             &&
             (!g_ascii_strncasecmp ( imported_transaction -> tiers, "Opening Balance", 15 )
             ||
             !g_ascii_strcasecmp ( imported_transaction -> tiers, _("Opening Balance") ) ) )
            {
                /* ok, we are on an opening balance, we transfer the first transaction
                 * to the initial datas of the account */

                /* get the initial amount */
                imported_account -> solde = imported_transaction -> montant;

                /* get the name of account */
                tmp_str = my_strdelimit (imported_transaction -> categ, "[]", "");
                if ( imported_account -> nom_de_compte )
                    g_free ( imported_account -> nom_de_compte );
                imported_account -> nom_de_compte = unique_imported_name ( tmp_str );
                g_free (tmp_str);

                /* get the date of the file */
                imported_account -> date_solde_qif = my_strdup ( imported_transaction -> date_tmp );

                /* now, we can remove the first imported transaction */
                imported_account -> operations_importees = g_slist_remove ( imported_account -> operations_importees,
                                            imported_transaction );
                g_free (imported_transaction);
            }
            /* now we need to transform the dates of transaction into gdate */

            /* try to understand the order */
            order = gsb_qif_get_date_order ( imported_account -> operations_importees );
            if (order == -1)
                dialogue_error ( _("Grisbi couldn't determine the format of the date into the qif file.\n"
                                        "Please contact the Grisbi team ([email protected]) to find "
                                        "the problem.\nFor now, all the dates will be imported as 01.01.1970") );
        }

        tmp_list = imported_account -> operations_importees;
        while (tmp_list)
        {
            imported_transaction = tmp_list -> data;
            if (order == -1)
                /* we didn't find the order */
                imported_transaction -> date = g_date_new_dmy ( 1,1,2000 );
            else
                imported_transaction -> date = gsb_qif_get_date ( imported_transaction -> date_tmp, order );

            tmp_list = tmp_list -> next;
        }

        /* set the date of the qif file */
        if ( imported_account -> date_solde_qif )
            imported_account -> date_fin = gsb_qif_get_date (imported_account -> date_solde_qif, order);

        /* add that account to the others */
        liste_comptes_importes = g_slist_append ( liste_comptes_importes, imported_account );
    }
    /* go to the next account */
    while ( returned_value != EOF );

    fclose ( qif_file );

    return ( TRUE );
}