示例#1
0
文件: main.c 项目: md81544/c
int main(int argc, char *argv[])
{
    // Initialise the cfg structure (this sets up a linked list
    // of key / value pairs)
    struct Config *cfg = cfg_init("settings.cfg");

    // Search for a key. Note that the return value is a pointer
    // in the cfg structure so should NOT be freed (it is freed
    // eventually by cfg_free.);
    char *value = cfg_get_string(cfg, "barney", "The default value");
    printf("\"%s\"\n", value);

    // Search for a non-existent key to show default value being returned
    char *value2 = cfg_get_string(cfg, "non-existent", "A default value");
    printf("\"%s\"\n", value2);

    // Get a number
    long num = cfg_get_long(cfg, "NuMbEr", 69);
    printf("Number is %ld\n", num);

    // Dump everything - showing the cfg_foreach() function
    printf("DEBUG dump all:\n");
    cfg_foreach(cfg, callback);

    // Finally tear down the cfg structure. This will invalidate any 
    // strings we've been returned, so we should make copies of 
    // anything we want to keep first.
    cfg_free(cfg);

    return 0;
}
示例#2
0
文件: main.c 项目: pinkfluid/apme
/**
 * Check the environment and set the environment name
 */
void apme_cfg_apply(void)
{
    char cfg[1024];

    if (cfg_get_string(CFG_SEC_APP, "name", cfg, sizeof(cfg)))
    {
        con_printf("MAIN: CFG name = %s\n", cfg);
        aion_player_name_set(cfg);
    }

    if (cfg_get_string(CFG_SEC_APP, "apformat", cfg, sizeof(cfg)))
    {
        con_printf("MAIN: CFG apformat = %s\n", cfg);
        aion_aploot_fmt_set(cfg);
    }
}
示例#3
0
static void _cfg_load_midi_part_locked(struct midi_port *q)
{
        struct cfg_section *c;
        /*struct midi_provider *p;*/
        cfg_file_t cfg;
        const char *sn;
        char *ptr, *ss, *sp;
        char buf[256];
        int j;

        ss = q->name;
        if (!ss) return;
        while (isspace(*ss)) ss++;
        if (!*ss) return;

        sp = q->provider ? q->provider->name : NULL;
        if (sp) {
                while (isspace(*sp)) sp++;
                if (!*sp) sp = NULL;
        }

        ptr = dmoz_path_concat(cfg_dir_dotschism, "config");
        cfg_init(&cfg, ptr);

        /* look for MIDI port sections */
        for (c = cfg.sections; c; c = c->next) {
                j = -1;
                sscanf(c->name, "MIDI Port %d", &j);
                if (j < 1) continue;
                sn = cfg_get_string(&cfg, c->name, "name", buf, 255, NULL);
                if (!sn) continue;
                if (strcasecmp(ss, sn) != 0) continue;
                sn = cfg_get_string(&cfg, c->name, "provider", buf, 255, NULL);
                if (sn && sp && strcasecmp(sp, sn) != 0) continue;
                /* okay found port */
                if ((q->iocap & MIDI_INPUT) && cfg_get_number(&cfg, c->name, "input", 0)) {
                        q->io |= MIDI_INPUT;
                }
                if ((q->iocap & MIDI_OUTPUT) && cfg_get_number(&cfg, c->name, "output", 0)) {
                        q->io |= MIDI_OUTPUT;
                }
                if (q->io && q->enable) q->enable(q);
        }

        cfg_free(&cfg);
        free(ptr);
}
示例#4
0
void load_menu (void)
{
    char    menu_filename[1024], *language;
    
    // find out what language user wants
    if (options.english_menu || cmdline.english)
    {
        language = "english";
    }
    else
    {
        language = cfg_get_string (CONFIG_NFTP, fl_opt.platform_nick, "language");
        str_strip (language, " ");
    }

    // Try $user_libpath directory
    snprintf1 (menu_filename, sizeof (menu_filename),
               "%s/nftp.mnu", paths.user_libpath);
    if (access (menu_filename, R_OK) == 0) goto Found;

    // Try $system_libpath directory
    snprintf1 (menu_filename, sizeof (menu_filename),
               "%s/nftp.mnu", paths.system_libpath);
    if (access (menu_filename, R_OK) == 0) goto Found;

    // Try current directory
    strcpy (menu_filename, "nftp.mnu");
    if (access (menu_filename, R_OK) == 0) goto Found;

    /*
    if (strcmp (language, "english") != 0)
    {
        if (fl_opt.has_console && !fl_opt.initialized)
            fly_ask_ok (0, "Failed to load \"%s.mnu\", trying English.\n", language);
        language = "english";
        goto Rescan;
    }
    */

    fly_error ("Failed to load \"nftp.mnu\".");

Found:

    if (main_menu != NULL)
    {
        menu_unload (main_menu);
    }
    
    if (fl_opt.has_console && !fl_opt.initialized)
        fly_ask_ok (0, "loading %s......\n", menu_filename);
    main_menu = menu_load (menu_filename, options.keytable,
                           sizeof(options.keytable)/sizeof(options.keytable[0]));
}
示例#5
0
static void cfg_load_palette(cfg_file_t *cfg)
{
        uint8_t colors[48];
        int n;
        char palette_text[49] = "";
        const char *ptr;

        palette_load_preset(cfg_get_number(cfg, "General", "palette", 2));

        cfg_get_string(cfg, "General", "palette_cur", palette_text, 48, "");
        for (n = 0; n < 48; n++) {
                if (palette_text[n] == '\0' || (ptr = strchr(palette_trans, palette_text[n])) == NULL)
                        return;
                colors[n] = ptr - palette_trans;
        }
        memcpy(current_palette, colors, sizeof(current_palette));
}
示例#6
0
static void spawn_watchman(void) {
#ifndef _WIN32
  // If we have a site-specific spawning requirement, then we'll
  // invoke that spawner rather than using any of the built-in
  // spawning functionality.
  const char *site_spawn = cfg_get_string(NULL, "spawn_watchman_service", NULL);
  if (site_spawn) {
    spawn_site_specific(site_spawn);
    return;
  }
#endif

#ifdef USE_GIMLI
  spawn_via_gimli();
#elif defined(__APPLE__)
  spawn_via_launchd();
#elif defined(_WIN32)
  spawn_win32();
#else
  daemonize();
#endif
}
示例#7
0
文件: cfg.cpp 项目: facebook/watchman
const char *cfg_get_trouble_url(void) {
  return cfg_get_string(
      "troubleshooting_url",
      "https://facebook.github.io/watchman/docs/troubleshooting.html");
}
示例#8
0
void cfg_load_midi(cfg_file_t *cfg)
{
        midi_config_t *md, *mc;
        char buf[17], buf2[33];
        int i;

        CFG_GET_MI(flags, MIDI_TICK_QUANTIZE | MIDI_RECORD_NOTEOFF
                | MIDI_RECORD_VELOCITY | MIDI_RECORD_AFTERTOUCH
                | MIDI_PITCHBEND);
        CFG_GET_MI(pitch_depth, 12);
        CFG_GET_MI(amplification, 100);
        CFG_GET_MI(c5note, 60);

        song_lock_audio();
        md = &default_midi_config;
        cfg_get_string(cfg,"MIDI","start", md->start, 31, "FF");
        cfg_get_string(cfg,"MIDI","stop", md->stop, 31, "FC");
        cfg_get_string(cfg,"MIDI","tick", md->tick, 31, "");
        cfg_get_string(cfg,"MIDI","note_on", md->note_on, 31, "9c n v");
        cfg_get_string(cfg,"MIDI","note_off", md->note_off, 31, "9c n 0");
        cfg_get_string(cfg,"MIDI","set_volume", md->set_volume, 31, "");
        cfg_get_string(cfg,"MIDI","set_panning", md->set_panning, 31, "");
        cfg_get_string(cfg,"MIDI","set_bank", md->set_bank, 31, "");
        cfg_get_string(cfg,"MIDI","set_program", md->set_program, 31, "Cc p");
        for (i = 0; i < 16; i++) {
                snprintf(buf, 16, "SF%X", i);
                cfg_get_string(cfg, "MIDI", buf, md->sfx[i], 31,
                                i == 0 ? "F0F000z" : "");
        }

        for (i = 0; i < 128; i++) {
                snprintf(buf, 16, "Z%02X", i + 0x80);
                if (i < 16)
                        snprintf(buf2, 32, "F0F001%02x", i * 8);
                else
                        buf2[0] = '\0';
                cfg_get_string(cfg, "MIDI", buf, md->zxx[i], 31, buf2);
        }

        mc = &current_song->midi_config;
        memcpy(mc, md, sizeof(midi_config_t));


        song_unlock_audio();
}
示例#9
0
int init (int argc, char *argv[])
{
    char    *p;
    int     rc = 0, oldmode, i;
    url_t   u;
    int     x0=-1, y0=-1, r=-1, c=-1;
    struct hostent     *remote;
    char    buffer[MAX_PATH];

    if (action == ACTION_TESTONLY) exit (0);
    if (action == ACTION_BADARGS)
    {
        usage ();
        exit (1);
    }

    if (options.keep_winsize)
    {
        r = cfg_get_integer (CONFIG_NFTP, fl_opt.platform_nick, "rows");
        c = cfg_get_integer (CONFIG_NFTP, fl_opt.platform_nick, "cols");
        if (r == 0 && c == 0) r = -1, c = -1;
    }

    if (options.keep_winpos)
    {
        x0 = cfg_get_integer (CONFIG_NFTP, fl_opt.platform_nick, "x0");
        y0 = cfg_get_integer (CONFIG_NFTP, fl_opt.platform_nick, "y0");
        if (x0 == 0 || y0 == 0) x0 = -1, y0 = -1;
    }

    p = cfg_get_string (CONFIG_NFTP, fl_opt.platform_nick, "font");
    if (p[0] == '\0') p = NULL;

    fly_init (x0, y0, r, c, p);
    fly_mouse (options.mouse);
    wintitle = get_window_name ();

    if (fl_opt.platform == PLATFORM_OS2_VIO)
    {
        strcpy (buffer, paths.system_libpath);
        str_cats (buffer, "nftp.ico");
        if (access (buffer, R_OK) == 0)
            set_icon (buffer);
    }

    if (main_menu != NULL)
    {
        menu_activate (main_menu);
    }

    display.rshift = 0;
    display.lshift = 0;
    display.tabsize = 8;
    display.view[V_LEFT] = -1;
    display.view[V_RIGHT] = -1;
    display.cursor = V_LEFT;
    display.parsed = TRUE;

    for (i=0; i<MAX_SITE; i++)
    {
        site[i].set_up = FALSE;
        site[i].CC.na = 0;
        site[i].CC.n = 0;
    }

    // ignore "broken PIPE" signals
    signal (SIGPIPE, SIG_IGN);

    set_window_name ("NFTP%s(C) Copyright Sergey Ayukov", NFTP_VERSION);

    lcache.lda = 0;
    lcache.ld  = 0;
    lcache.L   = NULL;

    local[V_LEFT].dir.name = NULL;
    local[V_LEFT].dir.files = NULL;
    local[V_LEFT].dir.nfiles = 0;
    local[V_LEFT].sortmode = abs (options.default_localsort);
    if (options.default_localsort >= 0)
        local[V_LEFT].sortdirection = 1;
    else
        local[V_LEFT].sortdirection = -1;
    l_chdir (V_LEFT, NULL);

    local[V_RIGHT].dir.name = NULL;
    local[V_RIGHT].dir.files = NULL;
    local[V_RIGHT].dir.nfiles = 0;
    local[V_RIGHT].sortmode = abs (options.default_localsort);
    if (options.default_localsort >= 0)
        local[V_RIGHT].sortdirection = 1;
    else
        local[V_RIGHT].sortdirection = -1;
    l_chdir (V_RIGHT, NULL);


    PutLineIntoResp (RT_COMM, 0, "NFTP Version%s(%s, %s) -- %s", NFTP_VERSION, __DATE__, __TIME__, fl_opt.platform_name);
    PutLineIntoResp (RT_RESP, 0, "Copyright (C) 1994--2000 Sergey Ayukov <*****@*****.**>");
    PutLineIntoResp (RT_RESP, 0, "Portions Copyright (C) Eric Young <*****@*****.**>");
    status.usage_interval = 0;
    if (!fl_opt.has_osmenu)
        PutLineIntoResp (RT_RESP, 0, MSG(M_RESP_F9_FOR_MENU));
    update (1);

    if (options.firewall_type != 0)
    {
        if (options.fire_server[0] == '\0')
        {
            fly_ask_ok (ASK_WARN, MSG(M_PROXY_ISNT_SPECIFIED));
            options.firewall_type = 0;
        }
        else
        {
            if (strspn (options.fire_server, " .0123456789") == strlen (options.fire_server))
            {
                firewall.fwip = inet_addr (options.fire_server);
            }
            else
            {
                PutLineIntoResp (RT_COMM, 0, MSG(M_RESP_LOOKING_UP), options.fire_server);
                remote = gethostbyname (options.fire_server);
                if (remote == NULL)
                {
                    PutLineIntoResp (RT_COMM, 0, MSG(M_RESP_CANNOT_RESOLVE), options.fire_server);
                    options.firewall_type = 0;
                }
                else
                {
                    firewall.fwip = *((unsigned long *)(remote->h_addr));
                    PutLineIntoResp (RT_COMM,0, MSG(M_RESP_FOUND), remote->h_name);
                }
            }
        }
    }

    // read password cache
    psw_read ();

    // analyze arguments
    switch (action)
    {
    case ACTION_NONE:
        if (options.download_path != NULL)
        {
            l_chdir (V_RIGHT, options.download_path);
        }
        else
        {
            p = cfg_get_string (CONFIG_NFTP, "", "local-directory-left");
            if (p[0] != '\0')
            {
                l_chdir (V_LEFT, p);
            }
            p = cfg_get_string (CONFIG_NFTP, "", "local-directory-right");
            if (p[0] != '\0')
            {
                l_chdir (V_RIGHT, p);
            }
        }
        switch (options.start_prompt)
        {
        case 1:  return FMSG_BASE_MENU + KEY_GEN_LOGIN;
        case 2:  return FMSG_BASE_MENU + KEY_GEN_BOOKMARKS;
        case 3:  return FMSG_BASE_MENU + KEY_GEN_HISTORY;
        case 5:  return FMSG_BASE_MENU + KEY_MENU;
        }
        return 0;

    case ACTION_DOWNLOAD:
    case ACTION_UPLOAD:
        oldmode = status.batch_mode;
        status.batch_mode = TRUE;
        if (action == ACTION_DOWNLOAD) rc = do_get (optarg1);
        if (action == ACTION_UPLOAD) rc = do_put (optarg1);
        //set_view_mode (VIEW_CONTROL);
        //update (1);
        if (rc && !cmdline.batchmode) fly_ask_ok (0, MSG(M_TRANSFER_FAILED), optarg1);
        if ((disc_after && rc == 0) || cmdline.batchmode)
        {
            Logoff (0);
            terminate ();
            exit (0);
        }
        status.batch_mode = oldmode;
        return 0;

    //case ACTION_CMDLIST:
    //    rc = runscript (optarg1);
    //    return 0;

    case ACTION_NICK_BOOK:
    case ACTION_NICK_HIST:
        if (action == ACTION_NICK_BOOK && bookmark_nickname (optarg1, &u) == 0) return 0;
        if (action == ACTION_NICK_HIST && history_nickname (optarg1, &u) == 0) return 0;
        rc = Login (-1, &u, V_LEFT);
        if (rc) return 0;
        if ((action == ACTION_NICK_BOOK && MAX_SITE > 1 && optarg2 != NULL &&
             bookmark_nickname (optarg2, &u) == 1) ||
            (action == ACTION_NICK_HIST && MAX_SITE > 1 && optarg2 != NULL &&
             history_nickname (optarg2, &u) == 1))
        {
            rc = Login (-1, &u, V_RIGHT);
        }
        if (options.login_bell) Bell (3);
        return 0;

    case ACTION_OPEN_BOOKMARKS:
        return FMSG_BASE_MENU + KEY_GEN_BOOKMARKS;

    case ACTION_OPEN_HISTORY:
        return FMSG_BASE_MENU + KEY_GEN_HISTORY;

    case ACTION_LOGIN:
        // if download_path was specified in nftp.ini, set it now
        if (options.download_path != NULL)
        {
            l_chdir (V_LEFT, options.download_path);
            l_chdir (V_RIGHT, options.download_path);
        }
        dmsg ("optarg1 is [%s]\n", optarg1);
        parse_url (optarg1, &u);
        rc = Login (-1, &u, V_LEFT);
        if (MAX_SITE > 1 && optarg2 != NULL)
        {
            parse_url (optarg2, &u);
            rc = Login (-1, &u, V_RIGHT);
        }
        // attempt to download file if chdir failed
        /*if (site.set_up && strcmp (site.u.pathname, RCURDIR.name) != 0)
        {
            rc = do_get (optarg1);
        }
        if (rc) return 0;
        */
        if (options.login_bell) Bell (3);
        return 0;

    case ACTION_TESTONLY:
        terminate ();
        exit (0);
    }
    fly_error ("internal error in init()");
    return 0;
}
示例#10
0
void GetProfileOptions (char *ini_name)
{
    char    *p, buf[16];
    int     i;

    if (infLoad (ini_name) < 0)
    {
        fly_error (M("Error loading %s; terminating"), ini_name);
    }

    // put defaults in place

    for (i=0; i<sizeof(boptions)/sizeof(boptions[0]); i++) *(boptions[i].value) = boptions[i].def;
    for (i=0; i<sizeof(ioptions)/sizeof(ioptions[0]); i++) *(ioptions[i].value) = ioptions[i].def;
    for (i=0; i<sizeof(soptions)/sizeof(soptions[0]); i++) *(soptions[i].value) = soptions[i].def;
    for (i=0; i<sizeof(xoptions)/sizeof(xoptions[0]); i++) if (xoptions[i].def != 255) *(xoptions[i].value) = xoptions[i].def;

    if (fl_opt.is_unix || fl_opt.platform == PLATFORM_OS2_X || fl_opt.platform == PLATFORM_OS2_X11) options.pseudographics = 2;

    // some defaults
    options.psw_file = str_strdup1 (paths.user_libpath, 9);
    str_cats (options.psw_file, "nftp.psw");
    
    options.history_file = str_strdup1 (paths.user_libpath, 9);
    str_cats (options.history_file, "nftp.hst");
    
    // retrieve options
    
    for (i=0; i<sizeof(boptions)/sizeof(boptions[0]); i++)
        infGetBoolean (boptions[i].sect, boptions[i].name, boptions[i].value);

    for (i=0; i<sizeof(ioptions)/sizeof(ioptions[0]); i++)
        infGetInteger (ioptions[i].sect, ioptions[i].name, ioptions[i].value);

    for (i=0; i<sizeof(soptions)/sizeof(soptions[0]); i++)
        infGetString (soptions[i].sect, soptions[i].name, soptions[i].value);
    
    for (i=0; i<sizeof(xoptions)/sizeof(xoptions[0]); i++)
        infGetHexbyte (xoptions[i].sect, xoptions[i].name, (char *)xoptions[i].value);


    if (infGetInteger (sect_psw, "encryption-type", &options.psw_enctype) < 0)
    {
        if (fl_opt.platform != PLATFORM_UNIX_TERM && fl_opt.platform != PLATFORM_UNIX_X11)
            options.psw_enctype = 2;
    }
    
    if (infGetBoolean (sect_options, "query-bfs-attributes-support", &options.query_bfsattrs) < 0)
    {
        if (fl_opt.platform == PLATFORM_BEOS_TERM) options.query_bfsattrs = TRUE;
        else                                       options.query_bfsattrs = FALSE;
    }

    if (options.user_agent == NULL)
    {
        strcpy (buf, NFTP_VERSION);
        str_strip2 (buf, " ");
        options.user_agent = str_join ("NFTP-", buf);
    }
    
    // post-config
    
    if (fl_opt.has_osmenu) fl_opt.menu_onscreen = FALSE;
    
    // INI file editor
    
    if (fl_opt.platform == PLATFORM_OS2_VIO)
    {
        options.texteditor = "tedit.exe";
        infGetString (sect_options, "text-editor-os2vio", &options.texteditor);
    }
    
    if (fl_opt.platform == PLATFORM_OS2_PM)
    {
        options.texteditor = "e.exe";
        infGetString (sect_options, "text-editor-os2pm", &options.texteditor);
    }
    
    if (fl_opt.platform == PLATFORM_OS2_X || fl_opt.platform == PLATFORM_OS2_X11)
    {
        options.texteditor = "xedit.exe";
        infGetString (sect_options, "text-editor-os2x", &options.texteditor);
    }
    
    if (fl_opt.platform == PLATFORM_WIN32_CONS)
    {
        options.texteditor = "Notepad.exe";
        infGetString (sect_options, "text-editor-win32cons", &options.texteditor);
    }

    if (fl_opt.platform == PLATFORM_WIN32_GUI)
    {
        options.texteditor = "Notepad.exe";
        infGetString (sect_options, "text-editor-win32gui", &options.texteditor);
    }

    if (fl_opt.platform == PLATFORM_BEOS_TERM)
    {
        options.texteditor = "vi";
        infGetString (sect_options, "text-editor-beosterm", &options.texteditor);
    }
    
    if (fl_opt.platform == PLATFORM_UNIX_TERM)
    {
        options.texteditor = "vi";
        infGetString (sect_options, "text-editor-unixterm", &options.texteditor);
    }

    if (fl_opt.platform == PLATFORM_UNIX_X11)
    {
        options.texteditor = "xedit";
        infGetString (sect_options, "text-editor-unix_x11", &options.texteditor);
    }

    // others
    
    if (options.log_trans)
    {
        if (infGetString (sect_options, "log-transfers-name", &p) == 0)
        {
            strcpy (options.log_trans_name, p);
            free (p);
        }
        else
        {
            strcpy (options.log_trans_name, paths.user_libpath);
            str_cats (options.log_trans_name, "nftp.fls");
        }
    }
    
    if (infGetString (sect_options, "bookmarks-file", &p) == 0)
    {
        strcpy (options.bmk_name, p);
        free (p);
    }
    else
    {
        strcpy (options.bmk_name, paths.user_libpath);
        str_cats (options.bmk_name, "nftp.bmk");
    }
    
    // registration information
    
    if ((cfg_get_string (CONFIG_NFTP, NULL, "registration-name"))[0] == '\0')
    {
        if (infGetString (sect_registration, "name", &p) == 0)
        {
            cfg_set_string (CONFIG_NFTP, NULL, "registration-name", p);
            free (p);
        }

        if (infGetString (sect_registration, "code", &p) == 0)
        {
            cfg_set_string (CONFIG_NFTP, NULL, "registration-code", p);
            free (p);
        }
    }

    // clear key definition table
    for (i=0; i<sizeof(options.keytable)/sizeof(int); i++)
    {
        options.keytable[i]  = KEY_NOTHING;
        options.keytable2[i] = KEY_NOTHING;
    }
    
    def_key_assignments ();
    key_assignments ();
    
    // retrieve colours
    if ((options.monochrome && !cmdline.colour) || cmdline.monochrome)
    {
        options.attr_pointer_marked_dir = VID_REVERSE;
        options.attr_pointer_marked     = VID_REVERSE;
        options.attr_pointer_dir        = VID_REVERSE;
        options.attr_pointer            = VID_REVERSE;
        options.attr_pointer_desc       = VID_REVERSE;
        options.attr_marked_dir         = VID_BRIGHT;
        options.attr_marked             = VID_BRIGHT;
        options.attr_dir                = VID_NORMAL;
        options.attr_description        = VID_NORMAL;           
        options.attr_                   = VID_NORMAL;           
                                                                
        options.attr_background         = VID_NORMAL;           
        options.attr_status             = VID_NORMAL;
        options.attr_status2            = VID_REVERSE;
        options.attr_statmarked         = VID_REVERSE;
        options.attr_tr_info            = VID_NORMAL;           
        options.attr_help               = VID_REVERSE;          
        options.attr_status_local       = VID_NORMAL;

        options.attr_tp_file     = VID_NORMAL;
        options.attr_tp_dir      = VID_NORMAL;
        options.attr_tp_file_m   = VID_NORMAL;
        options.attr_tp_dir__m   = VID_NORMAL;
        options.attr_tp_file_p   = VID_REVERSE;
        options.attr_tp_dir__p   = VID_REVERSE;
        options.attr_tp_file_mp  = VID_REVERSE;
        options.attr_tp_dir__mp  = VID_REVERSE;
        
        options.attr_cntr_header        = VID_REVERSE;
        options.attr_cntr_resp          = VID_NORMAL;
        options.attr_cntr_cmd           = VID_BRIGHT;
        options.attr_cntr_comment       = VID_BRIGHT;

        options.attr_bmrk_back          = VID_REVERSE;
        options.attr_bmrk_pointer       = VID_NORMAL;
        options.attr_bmrk_hostpath      = VID_REVERSE;
        options.attr_bmrk_hostpath_pointer = VID_BRIGHT;
    }

    infFree ();
}
示例#11
0
int init (int argc, char *argv[])
{
    char    *p;
    int     rc = 0, oldmode;
    url_t   u;
    int     x0=-1, y0=-1, r=-1, c=-1;
    struct hostent     *remote;
    char    buffer[MAX_PATH];

    if (action == ACTION_TESTONLY) exit (0);
    if (action == ACTION_BADAGS)
    {
        usage ();
        exit (1);
    }

    if (options.keep_winsize)
    {
        r = cfg_get_integer (CONFIG_NFTP, fl_opt.platform_nick, "rows");
        c = cfg_get_integer (CONFIG_NFTP, fl_opt.platform_nick, "cols");
        if (r == 0 && c == 0) r = -1, c = -1;
    }

    if (options.keep_winpos)
    {
        x0 = cfg_get_integer (CONFIG_NFTP, fl_opt.platform_nick, "x0");
        y0 = cfg_get_integer (CONFIG_NFTP, fl_opt.platform_nick, "y0");
        if (x0 == 0 || y0 == 0) x0 = -1, y0 = -1;
    }

    p = cfg_get_string (CONFIG_NFTP, fl_opt.platform_nick, "font");
    if (p[0] == '\0') p = NULL;

    fly_init (x0, y0, r, c, p);
    if (options.show_hw_cursor) video_cursor_state (1);
    fly_mouse (options.mouse);
    wintitle = get_window_name ();

    if (fl_opt.platform == PLATFORM_OS2_VIO)
    {
        strcpy (buffer, paths.system_libpath);
        str_cats (buffer, "nftp.ico");
        if (access (buffer, R_OK) == 0)
            set_icon (buffer);
    }

    if (main_menu != NULL)
    {
        menu_activate (main_menu);
        adjust_menu_status ();
    }
    
    display.dir_mode = options.defaultdirmode;
    display.view_mode = VIEW_CONTROL;
    
    display.rshift = 0;
    display.lshift = 0;
    display.tabsize = 8;
    if (options.slowlink)
        set_view_mode (VIEW_REMOTE);
    else
        set_view_mode (VIEW_CONTROL);
    site.maxndir = 1024;
    site.dir = malloc (sizeof(directory)*site.maxndir);

    // ignore "broken PIPE" signals
    signal (SIGPIPE, SIG_IGN);

    set_window_name ("NFTP%s(C) Copyright Sergey Ayukov", NFTP_VERSION);

    local.dir.files = NULL;
    local.sortmode = abs (options.default_localsort);
    if (options.default_localsort >= 0)
        local.sortdirection = 1;
    else
        local.sortdirection = -1;
    build_local_filelist (NULL);

    site.batch_mode = FALSE;
    site.chunks = NULL;

    PutLineIntoResp2 ("NFTP Version%s(%s, %s) -- %s", NFTP_VERSION, __DATE__, __TIME__, fl_opt.platform_name);
    PutLineIntoResp1 ("Copyright (C) 1994-2003 Sergey Ayukov <*****@*****.**>");
    PutLineIntoResp1 ("Portions Copyright (C) Eric Young <*****@*****.**>");
    //PutLineIntoResp1 ("Portions Copyright (C) Martin Nicolay <*****@*****.**>");
    status.usage_interval = 0;
    if (!fl_opt.has_osmenu)
        PutLineIntoResp1 (M("Press F9 or Ctrl-F for menu"));
    update (1);

    if (options.firewall_type != 0)
    {
        if (options.fire_server[0] == '\0')
        {
            fly_ask_ok (ASK_WARN, M("Firewall proxy host isn't specified in NFTP.INI"));
            options.firewall_type = 0;
        }
        else
        {
            if (strspn (options.fire_server, " .0123456789") == strlen (options.fire_server))
            {
                firewall.fwip = inet_addr (options.fire_server);
            }
            else
            {
                PutLineIntoResp2 (M("Looking up '%s'"), options.fire_server);
                remote = gethostbyname (options.fire_server);
                if (remote == NULL)
                {
                    PutLineIntoResp2 (M("Cannot find '%s'"), options.fire_server);
                    options.firewall_type = 0;
                }
                else
                {
                    firewall.fwip = *((unsigned long *)(remote->h_addr));
                    PutLineIntoResp2 (M("Found '%s'"), remote->h_name);
                }
            }
        }
    }

    // read password cache
    psw_read ();
        
    // analyze arguments
    switch (action)
    {
    case 0:
        if (options.download_path != NULL)
        {
            set_local_path (options.download_path);
        }
        else
        {
            p = cfg_get_string (CONFIG_NFTP, "", "local-directory");
            if (p[0] != '\0')
                set_local_path (p);
        }
        build_local_filelist (NULL);
        switch (options.start_prompt)
        {
        case 1:  return FMSG_BASE_MENU + KEY_GEN_LOGIN;
        case 2:  return FMSG_BASE_MENU + KEY_GEN_BOOKMARKS;
        case 3:  return FMSG_BASE_MENU + KEY_GEN_HISTORY;
        case 5:  return FMSG_BASE_MENU + KEY_MENU;
        }
        return 0;
        
    case ACTION_DOWNLOAD:
    case ACTION_UPLOAD:
        oldmode = site.batch_mode;
        site.batch_mode = TRUE;
        if (action == ACTION_DOWNLOAD) rc = do_get (optarg1);
        if (action == ACTION_UPLOAD) rc = do_put (optarg1);
        //set_view_mode (VIEW_CONTROL);
        //update (1);
        if (rc && !cmdline.batchmode)
            fly_ask_ok (0, M("Transfer of '%s' has failed"), optarg1);
        if ((disc_after && rc == 0) || cmdline.batchmode)
        {
            Logoff ();
            terminate ();
            exit (0);
        }
        site.batch_mode = oldmode;
        return 0;

    case ACTION_CMDLIST:
        rc = runscript (optarg1);
        return 0;

    case ACTION_NICK_BOOK:
    case ACTION_NICK_HIST:
        if (action == ACTION_NICK_BOOK && bookmark_nickname (optarg1, &u) == 0) return 0;
        if (action == ACTION_NICK_HIST && history_nickname (optarg1, &u) == 0) return 0;
        rc = Login (&u);
        if (rc) return 0;
        if (options.login_bell) Bell (3);
        return 0;

    case ACTION_OPEN_BOOKMARKS:
        return FMSG_BASE_MENU + KEY_GEN_BOOKMARKS;
        
    case ACTION_OPEN_HISTORY:
        return FMSG_BASE_MENU + KEY_GEN_HISTORY;

    case ACTION_LOGIN:
        // if download_path was specified in nftp.ini, set it now
        if (options.download_path != NULL)
            set_local_path (options.download_path);
        build_local_filelist (NULL);
        parse_url (optarg1, &u);
        rc = Login (&u);
        // attempt to download file if chdir failed
        /*if (site.set_up && strcmp (site.u.pathname, RCURDIR.name) != 0)
        {
            rc = do_get (optarg1);
        }
        if (rc) return 0;
        */
        if (options.login_bell) Bell (3);
        return 0;

    case ACTION_TESTONLY:
        terminate ();
        exit (0);
    }
    fly_error ("internal error in init()");
    return 0;
}
示例#12
0
文件: md.c 项目: SahanGH/psi4public
static struct md *md_create(struct state *state)
{
	struct md *md = xcalloc(1, sizeof(struct md));

	md->state = state;
	md->box = box_from_str(cfg_get_string(state->cfg, "periodic_box"));

	switch (cfg_get_enum(state->cfg, "ensemble")) {
		case ENSEMBLE_TYPE_NVE:
			md->get_invariant = get_invariant_nve;
			md->update_step = update_step_nve;
			break;
		case ENSEMBLE_TYPE_NVT:
			md->get_invariant = get_invariant_nvt;
			md->update_step = update_step_nvt;
			md->data = xcalloc(1, sizeof(struct nvt_data));
			break;
		case ENSEMBLE_TYPE_NPT:
			md->get_invariant = get_invariant_npt;
			md->update_step = update_step_npt;
			md->data = xcalloc(1, sizeof(struct npt_data));
			break;
		default:
			assert(0);
	}

	md->n_bodies = state->sys->n_frags;
	md->bodies = xcalloc(md->n_bodies, sizeof(struct body));

	double coord[6 * md->n_bodies];
	check_fail(efp_get_coordinates(state->efp, coord));

	for (size_t i = 0; i < md->n_bodies; i++) {
		struct body *body = md->bodies + i;

		body->pos.x = coord[6 * i + 0];
		body->pos.y = coord[6 * i + 1];
		body->pos.z = coord[6 * i + 2];

		double a = coord[6 * i + 3];
		double b = coord[6 * i + 4];
		double c = coord[6 * i + 5];

		euler_to_matrix(a, b, c, &body->rotmat);

		body->vel.x = md->state->sys->frags[i].vel[0];
		body->vel.y = md->state->sys->frags[i].vel[1];
		body->vel.z = md->state->sys->frags[i].vel[2];

		set_body_mass_and_inertia(state->efp, i, body);

		body->angmom.x = md->state->sys->frags[i].vel[3] * body->inertia.x;
		body->angmom.y = md->state->sys->frags[i].vel[4] * body->inertia.y;
		body->angmom.z = md->state->sys->frags[i].vel[5] * body->inertia.z;

		md->n_freedom += 3;

		if (body->inertia.x > EPSILON)
			md->n_freedom++;
		if (body->inertia.y > EPSILON)
			md->n_freedom++;
		if (body->inertia.z > EPSILON)
			md->n_freedom++;
	}

	return (md);
}
示例#13
0
void cfg_load(void)
{
        char *tmp;
        const char *ptr;
        int i;
        cfg_file_t cfg;

        tmp = dmoz_path_concat(cfg_dir_dotschism, "config");
        cfg_init(&cfg, tmp);
        free(tmp);

        /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

        cfg_get_string(&cfg, "Video", "driver", cfg_video_driver, 64, "");
        cfg_video_fullscreen = !!cfg_get_number(&cfg, "Video", "fullscreen", 0);
        cfg_video_mousecursor = cfg_get_number(&cfg, "Video", "mouse_cursor", MOUSE_EMULATED);
        cfg_video_mousecursor = CLAMP(cfg_video_mousecursor, 0, MOUSE_MAX_STATE);
        ptr = cfg_get_string(&cfg, "Video", "aspect", NULL, 0, NULL);
        if (ptr && *ptr)
                put_env_var("SCHISM_VIDEO_ASPECT", ptr);

        tmp = get_home_directory();
        cfg_get_string(&cfg, "Directories", "modules", cfg_dir_modules, PATH_MAX, tmp);
        cfg_get_string(&cfg, "Directories", "samples", cfg_dir_samples, PATH_MAX, tmp);
        cfg_get_string(&cfg, "Directories", "instruments", cfg_dir_instruments, PATH_MAX, tmp);
        free(tmp);

        ptr = cfg_get_string(&cfg, "Directories", "module_pattern", NULL, 0, NULL);
        if (ptr) {
                strncpy(cfg_module_pattern, ptr, PATH_MAX);
                cfg_module_pattern[PATH_MAX] = 0;
        }

        ptr = cfg_get_string(&cfg, "Directories", "export_pattern", NULL, 0, NULL);
        if (ptr) {
                strncpy(cfg_export_pattern, ptr, PATH_MAX);
                cfg_export_pattern[PATH_MAX] = 0;
        }

        ptr = cfg_get_string(&cfg, "General", "numlock_setting", NULL, 0, NULL);
        if (!ptr)
                status.fix_numlock_setting = NUMLOCK_GUESS;
        else if (strcasecmp(ptr, "on") == 0)
                status.fix_numlock_setting = NUMLOCK_ALWAYS_ON;
        else if (strcasecmp(ptr, "off") == 0)
                status.fix_numlock_setting = NUMLOCK_ALWAYS_OFF;
        else
                status.fix_numlock_setting = NUMLOCK_HONOR;

        set_key_repeat(cfg_get_number(&cfg, "General", "key_repeat_delay", key_repeat_delay()),
                       cfg_get_number(&cfg, "General", "key_repeat_rate", key_repeat_rate()));

        /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

        cfg_load_info(&cfg);
        cfg_load_patedit(&cfg);
        cfg_load_audio(&cfg);
        cfg_load_midi(&cfg);
        cfg_load_disko(&cfg);
        cfg_load_dmoz(&cfg);

        /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

        if (cfg_get_number(&cfg, "General", "classic_mode", 0))
                status.flags |= CLASSIC_MODE;
        else
                status.flags &= ~CLASSIC_MODE;
        if (cfg_get_number(&cfg, "General", "make_backups", 1))
                status.flags |= MAKE_BACKUPS;
        else
                status.flags &= ~MAKE_BACKUPS;
        if (cfg_get_number(&cfg, "General", "numbered_backups", 0))
                status.flags |= NUMBERED_BACKUPS;
        else
                status.flags &= ~NUMBERED_BACKUPS;

        i = cfg_get_number(&cfg, "General", "time_display", TIME_PLAY_ELAPSED);
        /* default to play/elapsed for invalid values */
        if (i < 0 || i >= TIME_PLAYBACK)
                i = TIME_PLAY_ELAPSED;
        status.time_display = i;

        i = cfg_get_number(&cfg, "General", "vis_style", VIS_OSCILLOSCOPE);
        /* default to oscilloscope for invalid values */
        if (i < 0 || i >= VIS_SENTINEL)
                i = VIS_OSCILLOSCOPE;
        status.vis_style = i;

        kbd_sharp_flat_toggle(cfg_get_number(&cfg, "General", "accidentals_as_flats", 0) == 1);

#ifdef MACOSX
# define DEFAULT_META 1
#else
# define DEFAULT_META 0
#endif
        if (cfg_get_number(&cfg, "General", "meta_is_ctrl", DEFAULT_META))
                status.flags |= META_IS_CTRL;
        else
                status.flags &= ~META_IS_CTRL;
        if (cfg_get_number(&cfg, "General", "altgr_is_alt", 1))
                status.flags |= ALTGR_IS_ALT;
        else
                status.flags &= ~ALTGR_IS_ALT;
        if (cfg_get_number(&cfg, "Video", "lazy_redraw", 0))
                status.flags |= LAZY_REDRAW;
        else
                status.flags &= ~LAZY_REDRAW;

        if (cfg_get_number(&cfg, "General", "midi_like_tracker", 0))
                status.flags |= MIDI_LIKE_TRACKER;
        else
                status.flags &= ~MIDI_LIKE_TRACKER;

        cfg_get_string(&cfg, "General", "font", cfg_font, NAME_MAX, "font.cfg");

        cfg_load_palette(&cfg);

        /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

        cfg_free(&cfg);
}
示例#14
0
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */
{
	php_stream *stream = NULL;
	php_url *resource = NULL;
	int use_ssl;
	int use_proxy = 0;
	char *scratch = NULL;
	char *tmp = NULL;
	char *ua_str = NULL;
	zval **ua_zval = NULL, **tmpzval = NULL;
	int scratch_len = 0;
	int body = 0;
	char location[HTTP_HEADER_BLOCK_SIZE];
	zval *response_header = NULL;
	int reqok = 0;
	char *http_header_line = NULL;
	char tmp_line[128];
	size_t chunk_size = 0, file_size = 0;
	int eol_detect = 0;
	char *transport_string, *errstr = NULL;
	int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0;
	char *protocol_version = NULL;
	int protocol_version_len = 3; /* Default: "1.0" */
	struct timeval timeout;
	char *user_headers = NULL;
	int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0);
	int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0);
	php_stream_filter *transfer_encoding = NULL;

	tmp_line[0] = '\0';

	if (redirect_max < 1) {
		php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting");
		return NULL;
	}

	resource = php_url_parse(path);
	if (resource == NULL) {
		return NULL;
	}

	if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) {
		if (!context || 
			php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE ||
			Z_TYPE_PP(tmpzval) != IS_STRING ||
			Z_STRLEN_PP(tmpzval) <= 0) {
			php_url_free(resource);
			return php_stream_open_wrapper_ex(path, mode, ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context);
		}
		/* Called from a non-http wrapper with http proxying requested (i.e. ftp) */
		request_fulluri = 1;
		use_ssl = 0;
		use_proxy = 1;

		transport_len = Z_STRLEN_PP(tmpzval);
		transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
	} else {
		/* Normal http request (possibly with proxy) */
	
		if (strpbrk(mode, "awx+")) {
			php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections");
			php_url_free(resource);
			return NULL;
		}

		use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's';
		/* choose default ports */
		if (use_ssl && resource->port == 0)
			resource->port = 443;
		else if (resource->port == 0)
			resource->port = 80;

		if (context &&
			php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS &&
			Z_TYPE_PP(tmpzval) == IS_STRING &&
			Z_STRLEN_PP(tmpzval) > 0) {
			use_proxy = 1;
			transport_len = Z_STRLEN_PP(tmpzval);
			transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
		} else {
			transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port);
		}
	}

	if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) {
		SEPARATE_ZVAL(tmpzval);
		convert_to_double_ex(tmpzval);
		timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval);
		timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000);
	} else {
		timeout.tv_sec = FG(default_socket_timeout);
		timeout.tv_usec = 0;
	}

	stream = php_stream_xport_create(transport_string, transport_len, options,
			STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT,
			NULL, &timeout, context, &errstr, NULL);
    
	if (stream) {
		php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout);
	}
			
	if (errstr) {
		php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr);
		efree(errstr);
		errstr = NULL;
	}

	efree(transport_string);

	if (stream && use_proxy && use_ssl) {
		smart_str header = {0};

		smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1);
		smart_str_appends(&header, resource->host);
		smart_str_appendc(&header, ':');
		smart_str_append_unsigned(&header, resource->port);
		smart_str_appendl(&header, " HTTP/1.0\r\n\r\n", sizeof(" HTTP/1.0\r\n\r\n")-1);
		if (php_stream_write(stream, header.c, header.len) != header.len) {
			php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
			php_stream_close(stream);
			stream = NULL;
		}
 	 	smart_str_free(&header);

 	 	if (stream) {
 	 		char header_line[HTTP_HEADER_BLOCK_SIZE];

			/* get response header */
			while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL)	{
				if (header_line[0] == '\n' ||
				    header_line[0] == '\r' ||
				    header_line[0] == '\0') {
				  break;
				}
			}
		}

		/* enable SSL transport layer */
		if (stream) {
			if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 ||
			    php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) {
				php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
				php_stream_close(stream);
				stream = NULL;
			}
		}
	}

	if (stream == NULL)	
		goto out;

	/* avoid buffering issues while reading header */
	if (options & STREAM_WILL_CAST)
		chunk_size = php_stream_set_chunk_size(stream, 1);
	
	/* avoid problems with auto-detecting when reading the headers -> the headers
	 * are always in canonical \r\n format */
	eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
	stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);

	php_stream_context_set(stream, context);

	php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0);

	if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) {
		SEPARATE_ZVAL(tmpzval);
		convert_to_long_ex(tmpzval);
		redirect_max = Z_LVAL_PP(tmpzval);
	}

	if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) {
		if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
			/* As per the RFC, automatically redirected requests MUST NOT use other methods than
			 * GET and HEAD unless it can be confirmed by the user */
			if (!redirected
				|| (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0)
				|| (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0)
			) {
				scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval);
				scratch = emalloc(scratch_len);
				strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1);
				strcat(scratch, " ");
			}
		}
	}
 
	if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) {
		SEPARATE_ZVAL(tmpzval);
		convert_to_double_ex(tmpzval);
		protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval));
	}

	if (!scratch) {
		scratch_len = strlen(path) + 29 + protocol_version_len;
		scratch = emalloc(scratch_len);
		strcpy(scratch, "GET ");
	}

	/* Should we send the entire path in the request line, default to no. */
	if (!request_fulluri &&
		context &&
		php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) {
		zval tmp = **tmpzval;

		zval_copy_ctor(&tmp);
		convert_to_boolean(&tmp);
		request_fulluri = Z_BVAL(tmp) ? 1 : 0;
		zval_dtor(&tmp);
	}

	if (request_fulluri) {
		/* Ask for everything */
		strcat(scratch, path);
	} else {
		/* Send the traditional /path/to/file?query_string */

		/* file */
		if (resource->path && *resource->path) {
			strlcat(scratch, resource->path, scratch_len);
		} else {
			strlcat(scratch, "/", scratch_len);
		}

		/* query string */
		if (resource->query)	{
			strlcat(scratch, "?", scratch_len);
			strlcat(scratch, resource->query, scratch_len);
		}
	}

	/* protocol version we are speaking */
	if (protocol_version) {
		strlcat(scratch, " HTTP/", scratch_len);
		strlcat(scratch, protocol_version, scratch_len);
		strlcat(scratch, "\r\n", scratch_len);
		efree(protocol_version);
		protocol_version = NULL;
	} else {
		strlcat(scratch, " HTTP/1.0\r\n", scratch_len);
	}

	/* send it */
	php_stream_write(stream, scratch, strlen(scratch));

	if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) {
		tmp = NULL;
		
		if (Z_TYPE_PP(tmpzval) == IS_ARRAY) {
			HashPosition pos;
			zval **tmpheader = NULL;
			smart_str tmpstr = {0};

			for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos);
				SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos);
				zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)
			) {
				if (Z_TYPE_PP(tmpheader) == IS_STRING) {
					smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader));
					smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1);
				}
			}
			smart_str_0(&tmpstr);
			/* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */
			if (tmpstr.c) {
				tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC);
				smart_str_free(&tmpstr);
			}
		}
		if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {
			/* Remove newlines and spaces from start and end php_trim will estrndup() */
			tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC);
		}
		if (tmp && strlen(tmp) > 0) {
			if (!header_init) { /* Remove post headers for redirects */
				int l = strlen(tmp);
				char *s, *s2, *tmp_c = estrdup(tmp);
				
				php_strtolower(tmp_c, l);
				if ((s = strstr(tmp_c, "content-length:"))) {
					if ((s2 = memchr(s, '\n', tmp_c + l - s))) {
						int b = tmp_c + l - 1 - s2;
						memmove(tmp, tmp + (s2 + 1 - tmp_c), b);
						memmove(tmp_c, s2 + 1, b);
						
					} else {
						tmp[s - tmp_c] = *s = '\0';
					}
					l = strlen(tmp_c);
				}
				if ((s = strstr(tmp_c, "content-type:"))) {
					if ((s2 = memchr(s, '\n', tmp_c + l - s))) {
						memmove(tmp, tmp + (s2 + 1 - tmp_c), tmp_c + l - 1 - s2);
					} else {
						tmp[s - tmp_c] = '\0';
					}
				}
				efree(tmp_c);
				tmp_c = php_trim(tmp, strlen(tmp), NULL, 0, NULL, 3 TSRMLS_CC);
				efree(tmp);
				tmp = tmp_c;
			}

			user_headers = estrdup(tmp);

			/* Make lowercase for easy comparison against 'standard' headers */
			php_strtolower(tmp, strlen(tmp));
			if (strstr(tmp, "user-agent:")) {
				 have_header |= HTTP_HEADER_USER_AGENT;
			}
			if (strstr(tmp, "host:")) {
				 have_header |= HTTP_HEADER_HOST;
			}
			if (strstr(tmp, "from:")) {
				 have_header |= HTTP_HEADER_FROM;
				}
			if (strstr(tmp, "authorization:")) {
				 have_header |= HTTP_HEADER_AUTH;
			}
			if (strstr(tmp, "content-length:")) {
				 have_header |= HTTP_HEADER_CONTENT_LENGTH;
			}
			if (strstr(tmp, "content-type:")) {
				 have_header |= HTTP_HEADER_TYPE;
			}
		}
		if (tmp) {
			efree(tmp);
		}
	}

	/* auth header if it was specified */
	if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) {
		/* decode the strings first */
		php_url_decode(resource->user, strlen(resource->user));

		/* scratch is large enough, since it was made large enough for the whole URL */
		strcpy(scratch, resource->user);
		strcat(scratch, ":");

		/* Note: password is optional! */
		if (resource->pass) {
			php_url_decode(resource->pass, strlen(resource->pass));
			strcat(scratch, resource->pass);
		}

		tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL);
		
		if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) {
			php_stream_write(stream, scratch, strlen(scratch));
			php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0);
		}

		efree(tmp);
		tmp = NULL;
	}

	/* if the user has configured who they are, send a From: line */
	if (((have_header & HTTP_HEADER_FROM) == 0) && cfg_get_string("from", &tmp) == SUCCESS)	{
		if (snprintf(scratch, scratch_len, "From: %s\r\n", tmp) > 0)
			php_stream_write(stream, scratch, strlen(scratch));
	}

	/* Send Host: header so name-based virtual hosts work */
	if ((have_header & HTTP_HEADER_HOST) == 0) {
		if ((use_ssl && resource->port != 443 && resource->port != 0) || 
			(!use_ssl && resource->port != 80 && resource->port != 0))	{
			if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0)
				php_stream_write(stream, scratch, strlen(scratch));
		} else {
			if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) {
				php_stream_write(stream, scratch, strlen(scratch));
			}
		}
	}

	if (context && 
	    php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS &&
		Z_TYPE_PP(ua_zval) == IS_STRING) {
		ua_str = Z_STRVAL_PP(ua_zval);
	} else if (FG(user_agent)) {
		ua_str = FG(user_agent);
	}

	if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) {
#define _UA_HEADER "User-Agent: %s\r\n"
		char *ua;
		size_t ua_len;
		
		ua_len = sizeof(_UA_HEADER) + strlen(ua_str);
		
		/* ensure the header is only sent if user_agent is not blank */
		if (ua_len > sizeof(_UA_HEADER)) {
			ua = emalloc(ua_len + 1);
			if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) {
				ua[ua_len] = 0;
				php_stream_write(stream, ua, ua_len);
			} else {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header");
			}

			if (ua) {
				efree(ua);
			}
		}	
	}

	if (user_headers) {
		/* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST
		 * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first.
		 */
		if (
				header_init &&
				context &&
				!(have_header & HTTP_HEADER_CONTENT_LENGTH) &&
				php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
				Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0
		) {
			scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
			php_stream_write(stream, scratch, scratch_len);
			have_header |= HTTP_HEADER_CONTENT_LENGTH;
		}

		php_stream_write(stream, user_headers, strlen(user_headers));
		php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
		efree(user_headers);
	}

	/* Request content, such as for POST requests */
	if (header_init && context &&
		php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
		Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
		if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) {
			scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
			php_stream_write(stream, scratch, scratch_len);
		}
		if (!(have_header & HTTP_HEADER_TYPE)) {
			php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n",
				sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1);
			php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded");
		}
		php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
		php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
		php_stream_write(stream, "\r\n\r\n", sizeof("\r\n\r\n")-1);
	} else {
		php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
	}

	location[0] = '\0';

	if (!EG(active_symbol_table)) {
		zend_rebuild_symbol_table(TSRMLS_C);
	}

	if (header_init) {
		zval *tmp;
		MAKE_STD_ZVAL(tmp);
		array_init(tmp);
		ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", tmp);
	}

	{
		zval **rh;
		zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh);
		response_header = *rh;
	}

	if (!php_stream_eof(stream)) {
		size_t tmp_line_len;
		/* get response header */

		if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) {
			zval *http_response;
			int response_code;

			if (tmp_line_len > 9) {
				response_code = atoi(tmp_line + 9);
			} else {
				response_code = 0;
			}
			if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) {
				ignore_errors = zend_is_true(*tmpzval);
			}
			/* when we request only the header, don't fail even on error codes */
			if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) {
				reqok = 1;
			}
			/* all status codes in the 2xx range are defined by the specification as successful;
			 * all status codes in the 3xx range are for redirection, and so also should never
			 * fail */
			if (response_code >= 200 && response_code < 400) {
				reqok = 1;
			} else {
				switch(response_code) {
					case 403:
						php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT,
								tmp_line, response_code);
						break;
					default:
						/* safety net in the event tmp_line == NULL */
						if (!tmp_line_len) {
							tmp_line[0] = '\0';
						}
						php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE,
								tmp_line, response_code);
				}
			}
			if (tmp_line[tmp_line_len - 1] == '\n') {
				--tmp_line_len;
				if (tmp_line[tmp_line_len - 1] == '\r') {
					--tmp_line_len;
				}
			}
			MAKE_STD_ZVAL(http_response);
			ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1);
			zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL);
		}
	} else {
		php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!");
		goto out;
	}
	
	/* read past HTTP headers */
	
	http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE);

	while (!body && !php_stream_eof(stream)) {
		size_t http_header_line_length;
		if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') {
			char *e = http_header_line + http_header_line_length - 1;
			if (*e != '\n') {
				do { /* partial header */
					php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length);
					e = http_header_line + http_header_line_length - 1;
				} while (*e != '\n');
				continue;
			}
			while (*e == '\n' || *e == '\r') {
				e--;
			}
			http_header_line_length = e - http_header_line + 1;
			http_header_line[http_header_line_length] = '\0';

			if (!strncasecmp(http_header_line, "Location: ", 10)) {
				strlcpy(location, http_header_line + 10, sizeof(location));
			} else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) {
				php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0);
			} else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) {
				file_size = atoi(http_header_line + 16);
				php_stream_notify_file_size(context, file_size, http_header_line, 0);
			} else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) {

				/* create filter to decode response body */
				if (!(options & STREAM_ONLY_GET_HEADERS)) {
					long decode = 1;

					if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) {
						SEPARATE_ZVAL(tmpzval);
						convert_to_boolean(*tmpzval);
						decode = Z_LVAL_PP(tmpzval);
					}
					if (decode) {
						transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC);
						if (transfer_encoding) {
							/* don't store transfer-encodeing header */
							continue;
						}
					}
				}
			}

			if (http_header_line[0] == '\0') {
				body = 1;
			} else {
				zval *http_header;

				MAKE_STD_ZVAL(http_header);

				ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1);
				
				zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL);
			}
		} else {
			break;
		}
	}
	
	if (!reqok || location[0] != '\0') {
		if (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1) {
			goto out;
		}

		if (location[0] != '\0')
			php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);

		if (context) { /* keep the context for the next try */
			zend_list_addref(context->rsrc_id);
		}
		php_stream_close(stream);
		stream = NULL;

		if (location[0] != '\0')	{

			char new_path[HTTP_HEADER_BLOCK_SIZE];
			char loc_path[HTTP_HEADER_BLOCK_SIZE];

			*new_path='\0';
			if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && 
							strncasecmp(location, "https://", sizeof("https://")-1) && 
							strncasecmp(location, "ftp://", sizeof("ftp://")-1) && 
							strncasecmp(location, "ftps://", sizeof("ftps://")-1))) 
			{
				if (*location != '/') {
					if (*(location+1) != '\0' && resource->path) {		
						char *s = strrchr(resource->path, '/');
						if (!s) {
							s = resource->path;
							if (!s[0]) {
								efree(s);
								s = resource->path = estrdup("/");
							} else {
								*s = '/';
							}
						}
						s[1] = '\0'; 
						if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') {
							snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location);
						} else {
							snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location);
						}
					} else {
						snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location);
					}
				} else {
					strlcpy(loc_path, location, sizeof(loc_path));
				}
				if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {
					snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path);
				} else {
					snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path);
				}
			} else {
				strlcpy(new_path, location, sizeof(new_path));
			}

			php_url_free(resource);
			/* check for invalid redirection URLs */
			if ((resource = php_url_parse(new_path)) == NULL) {
				php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path);
				goto out;
			}

#define CHECK_FOR_CNTRL_CHARS(val) {	\
	if (val) {	\
		unsigned char *s, *e;	\
		int l;	\
		l = php_url_decode(val, strlen(val));	\
		s = (unsigned char*)val; e = s + l;	\
		while (s < e) {	\
			if (iscntrl(*s)) {	\
				php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path);	\
				goto out;	\
			}	\
			s++;	\
		}	\
	}	\
}
			/* check for control characters in login, password & path */
			if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) {
				CHECK_FOR_CNTRL_CHARS(resource->user)
				CHECK_FOR_CNTRL_CHARS(resource->pass)
				CHECK_FOR_CNTRL_CHARS(resource->path)
			}
			stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC);
		} else {
示例#15
0
static void compute_file_name(char **strp,
    const char *user,
    const char *suffix,
    const char *what)
{
  char *str = NULL;

  str = *strp;

  if (!str) {
    /* We'll put our various artifacts in a user specific dir
     * within the state dir location */
    char *state_dir = NULL;
    const char *state_parent = test_state_dir ? test_state_dir :
#ifdef WATCHMAN_STATE_DIR
          WATCHMAN_STATE_DIR
#else
          watchman_tmp_dir
#endif
          ;

    ignore_result(asprintf(&state_dir, "%s%c%s-state",
          state_parent,
          WATCHMAN_DIR_SEP,
          user));

    if (!state_dir) {
      w_log(W_LOG_ERR, "out of memory computing %s\n", what);
      exit(1);
    }

    if (mkdir(state_dir, 0700) == 0 || errno == EEXIST) {
#ifndef _WIN32
      // verify ownership
      struct stat st;
      DIR *dirp;
      int dir_fd;
      int ret = 0;
      uid_t euid = geteuid();
      // TODO: also allow a gid to be specified here
      const char *sock_group_name = cfg_get_string(NULL, "sock_group", NULL);
      // S_ISGID is set so that files inside this directory inherit the group
      // name
      mode_t dir_perms = cfg_get_perms(NULL, "sock_access",
                                       false /* write bits */,
                                       true /* execute bits */) | S_ISGID;

      dirp = opendir(state_dir);
      if (!dirp) {
        w_log(W_LOG_ERR, "opendir(%s): %s\n", state_dir, strerror(errno));
        exit(1);
      }

      dir_fd = dirfd(dirp);
      if (dir_fd == -1) {
        w_log(W_LOG_ERR, "dirfd(%s): %s\n", state_dir, strerror(errno));
        goto bail;
      }

      if (fstat(dir_fd, &st) != 0) {
        w_log(W_LOG_ERR, "fstat(%s): %s\n", state_dir, strerror(errno));
        ret = 1;
        goto bail;
      }
      if (euid != st.st_uid) {
        w_log(W_LOG_ERR,
            "the owner of %s is uid %d and doesn't match your euid %d\n",
            state_dir, st.st_uid, euid);
        ret = 1;
        goto bail;
      }
      if (st.st_mode & 0022) {
        w_log(W_LOG_ERR,
            "the permissions on %s allow others to write to it. "
            "Verify that you own the contents and then fix its "
            "permissions by running `chmod 0700 %s`\n",
            state_dir,
            state_dir);
        ret = 1;
        goto bail;
      }

      if (sock_group_name) {
        struct group *sock_group;
        // This explicit errno statement is necessary to distinguish between the
        // group not existing and an error.
        errno = 0;
        sock_group = getgrnam(sock_group_name);
        if (!sock_group) {
          if (errno == 0) {
            w_log(W_LOG_ERR, "group '%s' does not exist", sock_group_name);
          } else {
            w_log(W_LOG_ERR, "getting gid for '%s' failed: %s", sock_group_name,
                  strerror(errno));
          }
          ret = 1;
          goto bail;
        }

        if (fchown(dir_fd, -1, sock_group->gr_gid) == -1) {
          w_log(W_LOG_ERR, "setting up group '%s' failed: %s", sock_group_name,
                strerror(errno));
          ret = 1;
          goto bail;
        }
      }

      // Depending on group and world accessibility, change permissions on the
      // directory. We can't leave the directory open and set permissions on the
      // socket because not all POSIX systems respect permissions on UNIX domain
      // sockets, but all POSIX systems respect permissions on the containing
      // directory.
      w_log(W_LOG_DBG, "Setting permissions on state dir to 0%o", dir_perms);
      if (fchmod(dir_fd, dir_perms) == -1) {
        w_log(W_LOG_ERR, "fchmod(%s, %#o): %s\n", state_dir, dir_perms,
              strerror(errno));
        ret = 1;
        goto bail;
      }

    bail:
      closedir(dirp);
      if (ret) {
        exit(ret);
      }
#endif
    } else {
      w_log(W_LOG_ERR, "while computing %s: failed to create %s: %s\n", what,
            state_dir, strerror(errno));
      exit(1);
    }

    ignore_result(asprintf(&str, "%s%c%s",
          state_dir, WATCHMAN_DIR_SEP, suffix));

    if (!str) {
      w_log(W_LOG_ERR, "out of memory computing %s", what);
      abort();
    }

    free(state_dir);
  }

#ifndef _WIN32
  if (str[0] != '/') {
    w_log(W_LOG_ERR, "invalid %s: %s", what, str);
    abort();
  }
#endif

  *strp = str;
}
FILE *php_fopen_url_wrap_ftp(char *path, char *mode, int options, int *issock, int *socketd, char **opened_path)
{
	FILE *fp=NULL;
	php_url *resource=NULL;
	char tmp_line[512];
	unsigned short portno;
	char *scratch;
	int result;
	int i;
	char *tpath, *ttpath;
	
	resource = url_parse((char *) path);
	if (resource == NULL) {
		php_error(E_WARNING, "Invalid URL specified, %s", path);
		*issock = BAD_URL;
		return NULL;
	} else if (resource->path == NULL) {
		php_error(E_WARNING, "No file-path specified");
		free_url(resource);
		*issock = BAD_URL;
		return NULL;
	}
	/* use port 21 if one wasn't specified */
	if (resource->port == 0)
		resource->port = 21;

	*socketd = php_hostconnect(resource->host, resource->port, SOCK_STREAM, 0);
	if (*socketd == -1)
		goto errexit;
#if 0
	if ((fpc = fdopen(*socketd, "r+")) == NULL) {
		free_url(resource);
		return NULL;
	}
#ifdef HAVE_SETVBUF
	if ((setvbuf(fpc, NULL, _IONBF, 0)) != 0) {
		free_url(resource);
		fclose(fpc);
		return NULL;
	}
#endif
#endif
	
	/* Start talking to ftp server */
	result = php_get_ftp_result(*socketd);
	if (result > 299 || result < 200)
		goto errexit;

	/* send the user name */
	SOCK_WRITE("USER ", *socketd);
	if (resource->user != NULL) {
		php_raw_url_decode(resource->user, strlen(resource->user));
		SOCK_WRITE(resource->user, *socketd);
	} else {
		SOCK_WRITE("anonymous", *socketd);
	}
	SOCK_WRITE("\r\n", *socketd);
	
	/* get the response */
	result = php_get_ftp_result(*socketd);
	
	/* if a password is required, send it */
	if (result >= 300 && result <= 399) {
		SOCK_WRITE("PASS ", *socketd);
		if (resource->pass != NULL) {
			php_raw_url_decode(resource->pass, strlen(resource->pass));
			SOCK_WRITE(resource->pass, *socketd);
		} else {
			/* if the user has configured who they are,
			   send that as the password */
			if (cfg_get_string("from", &scratch) == SUCCESS) {
				SOCK_WRITE(scratch, *socketd);
			} else {
				SOCK_WRITE("anonymous", *socketd);
			}
		}
		SOCK_WRITE("\r\n", *socketd);
		
		/* read the response */
		result = php_get_ftp_result(*socketd);
	}
	if (result > 299 || result < 200)
		goto errexit;
	
	/* set the connection to be binary */
	SOCK_WRITE("TYPE I\r\n", *socketd);
	result = php_get_ftp_result(*socketd);
	if (result > 299 || result < 200)
		goto errexit;
	
	/* find out the size of the file (verifying it exists) */
	SOCK_WRITE("SIZE ", *socketd);
	SOCK_WRITE(resource->path, *socketd);
	SOCK_WRITE("\r\n", *socketd);
	
	/* read the response */
	result = php_get_ftp_result(*socketd);
	if (mode[0] == 'r') {
		/* when reading file, it must exist */
		if (result > 299 || result < 200) {
			php_error(E_WARNING, "File not found");
			free_url(resource);
			SOCK_FCLOSE(*socketd);
			*socketd = 0;
			errno = ENOENT;
			return NULL;
		}
	} else {
		/* when writing file, it must NOT exist */
		if (result <= 299 && result >= 200) {
			php_error(E_WARNING, "File already exists");
			free_url(resource);
			SOCK_FCLOSE(*socketd);
			*socketd = 0;
			errno = EEXIST;
			return NULL;
		}
	}
	
	/* set up the passive connection */

    /* We try EPSV first, needed for IPv6 and works on some IPv4 servers */
	SOCK_WRITE("EPSV\r\n", *socketd);
	while (SOCK_FGETS(tmp_line, sizeof(tmp_line)-1, *socketd) &&
		   !(isdigit((int) tmp_line[0]) && isdigit((int) tmp_line[1]) &&
			 isdigit((int) tmp_line[2]) && tmp_line[3] == ' '));

	/* check if we got a 229 response */
	if (strncmp(tmp_line, "229", 3)) {
		/* EPSV failed, let's try PASV */
		SOCK_WRITE("PASV\r\n", *socketd);
		while (SOCK_FGETS(tmp_line, sizeof(tmp_line)-1, *socketd) &&
			   !(isdigit((int) tmp_line[0]) && isdigit((int) tmp_line[1]) &&
				 isdigit((int) tmp_line[2]) && tmp_line[3] == ' '));
		/* make sure we got a 227 response */
		if (strncmp(tmp_line, "227", 3))
			goto errexit;
		/* parse pasv command (129,80,95,25,13,221) */
		tpath = tmp_line;
		/* skip over the "227 Some message " part */
		for (tpath += 4; *tpath && !isdigit((int) *tpath); tpath++);
		if (!*tpath)
			goto errexit;
		/* skip over the host ip, we just assume it's the same */
		for (i = 0; i < 4; i++) {
			for (; isdigit((int) *tpath); tpath++);
			if (*tpath != ',')
				goto errexit;
			tpath++;
		}
		/* pull out the MSB of the port */
		portno = (unsigned short) strtol(tpath, &ttpath, 10) * 256;
		if (ttpath == NULL) {
			/* didn't get correct response from PASV */
			goto errexit;
		}
		tpath = ttpath;
		if (*tpath != ',')
			goto errexit;
		tpath++;
		/* pull out the LSB of the port */
		portno += (unsigned short) strtol(tpath, &ttpath, 10);
	} else {
		/* parse epsv command (|||6446|) */
		for (i = 0, tpath = tmp_line + 4; *tpath; tpath++) {
			if (*tpath == '|') {
				i++;
				if (i == 3)
					break;
			}
		}
		if (i < 3)
			goto errexit;
		/* pull out the port */
		portno = (unsigned short) strtol(tpath + 1, &ttpath, 10);
	}
	
	if (ttpath == NULL) {
		/* didn't get correct response from EPSV/PASV */
		goto errexit;
	}
	
	if (mode[0] == 'r') {
		/* retrieve file */
		SOCK_WRITE("RETR ", *socketd);
	} else {
		/* store file */
		SOCK_WRITE("STOR ", *socketd);
	} 
	if (resource->path != NULL) {
		SOCK_WRITE(resource->path, *socketd);
	} else {
		SOCK_WRITE("/", *socketd);
	}
	
	/* close control connection */
	SOCK_WRITE("\r\nQUIT\r\n", *socketd);
	SOCK_FCLOSE(*socketd);

	/* open the data channel */
	*socketd = php_hostconnect(resource->host, portno, SOCK_STREAM, 0);
	if (*socketd == -1)
		goto errexit;
#if 0
	if (mode[0] == 'r') {
		if ((fp = fdopen(*socketd, "r+")) == NULL) {
			free_url(resource);
			return NULL;
		}
	} else {
		if ((fp = fdopen(*socketd, "w+")) == NULL) {
			free_url(resource);
			return NULL;
		}
	}
#ifdef HAVE_SETVBUF
	if ((setvbuf(fp, NULL, _IONBF, 0)) != 0) {
		free_url(resource);
		fclose(fp);
		return NULL;
	}
#endif
#endif
	free_url(resource);
	*issock = 1;
	return (fp);

 errexit:
	free_url(resource);
	SOCK_FCLOSE(*socketd);
	*socketd = 0;
	return NULL;
}
示例#17
0
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int header_init STREAMS_DC TSRMLS_DC)
{
    php_stream *stream = NULL;
    php_url *resource = NULL;
    int use_ssl;
    char *scratch = NULL;
    char *tmp = NULL;
    char *ua_str = NULL;
    zval **ua_zval = NULL, **tmpzval = NULL;
    int scratch_len = 0;
    int body = 0;
    char location[HTTP_HEADER_BLOCK_SIZE];
    zval **response_header = NULL;
    int reqok = 0;
    char *http_header_line = NULL;
    char tmp_line[128];
    size_t chunk_size = 0, file_size = 0;
    int eol_detect, have_header = 0;

    if (redirect_max < 1) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Circular redirect, aborting.");
        return NULL;
    }

    if (strpbrk(mode, "aw+")) {
        php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections.");
        return NULL;
    }

    resource = php_url_parse(path);
    if (resource == NULL) {
        return NULL;
    }

    if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) {
        php_url_free(resource);
        return php_stream_open_wrapper_ex(path, mode, ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context);
    }

    use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's';

    /* choose default ports */
    if (use_ssl && resource->port == 0)
        resource->port = 443;
    else if (resource->port == 0)
        resource->port = 80;

    stream = php_stream_sock_open_host(resource->host, resource->port, SOCK_STREAM, NULL, 0);
    if (stream == NULL) {
        eol_detect = 0;
        goto out;
    }

    /* avoid problems with auto-detecting when reading the headers -> the headers
     * are always in canonical \r\n format */
    eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
    stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);

    php_stream_context_set(stream, context);

    php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0);

#ifdef HAVE_OPENSSL_EXT
    if (use_ssl)	{

        if (context) {
            /* set the CN we expect to be on the remote cert.
             * You still need to have enabled verification (verify_peer) in the context for
             * this to have an effect */
            zval *cn;

            ALLOC_INIT_ZVAL(cn);
            ZVAL_STRING(cn, resource->host, 1);
            php_stream_context_set_option(context, "ssl", "CN_match", cn);
        }

        if (php_stream_sock_ssl_activate(stream, 1) == FAILURE)	{
            php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Unable to activate SSL mode");
            php_stream_close(stream);
            stream = NULL;
            goto out;
        }
    }
#endif

    if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) {
        if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
            scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval);
            scratch = (char *)emalloc(scratch_len);
            strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1);
            strcat(scratch, " ");
        }
    }

    if (!scratch) {
        scratch_len = strlen(path) + 32;
        scratch = (char *)emalloc(scratch_len);
        strcpy(scratch, "GET ");
    }

    /* file */
    if (resource->path && *resource->path)
        strlcat(scratch, resource->path, scratch_len);
    else
        strlcat(scratch, "/", scratch_len);

    /* query string */
    if (resource->query)	{
        strlcat(scratch, "?", scratch_len);
        strlcat(scratch, resource->query, scratch_len);
    }

    /* protocol version we are speaking */
    strlcat(scratch, " HTTP/1.0\r\n", scratch_len);

    /* send it */
    php_stream_write(stream, scratch, strlen(scratch));

    if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS && Z_STRLEN_PP(tmpzval)) {
        /* Remove newlines and spaces from start and end, php_trim will estrndup() */
        tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC);
        if (strlen(tmp) > 0) {
            /* Output trimmed headers with \r\n at the end */
            php_stream_write(stream, tmp, strlen(tmp));
            php_stream_write(stream, "\r\n", sizeof("\r\n") - 1);

            /* Make lowercase for easy comparison against 'standard' headers */
            php_strtolower(tmp, strlen(tmp));
            if (strstr(tmp, "user-agent:")) {
                have_header |= HTTP_HEADER_USER_AGENT;
            }
            if (strstr(tmp, "host:")) {
                have_header |= HTTP_HEADER_HOST;
            }
            if (strstr(tmp, "from:")) {
                have_header |= HTTP_HEADER_FROM;
            }
            if (strstr(tmp, "authorization:")) {
                have_header |= HTTP_HEADER_AUTH;
            }
        }
        efree(tmp);
    }

    /* auth header if it was specified */
    if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user && resource->pass) {
        /* decode the strings first */
        php_url_decode(resource->user, strlen(resource->user));
        php_url_decode(resource->pass, strlen(resource->pass));

        /* scratch is large enough, since it was made large enough for the whole URL */
        strcpy(scratch, resource->user);
        strcat(scratch, ":");
        strcat(scratch, resource->pass);

        tmp = (char *)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL);

        if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) {
            php_stream_write(stream, scratch, strlen(scratch));
            php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0);
        }

        efree(tmp);
        tmp = NULL;
    }

    /* if the user has configured who they are, send a From: line */
    if (((have_header & HTTP_HEADER_FROM) == 0) && cfg_get_string("from", &tmp) == SUCCESS)	{
        if (snprintf(scratch, scratch_len, "From: %s\r\n", tmp) > 0) {
            php_stream_write(stream, scratch, strlen(scratch));
        }
    }

    /* Send Host: header so name-based virtual hosts work */
    if ((have_header & HTTP_HEADER_HOST) == 0) {
        if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80))	{
            if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0) {
                php_stream_write(stream, scratch, strlen(scratch));
            }
        } else {
            if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) {
                php_stream_write(stream, scratch, strlen(scratch));
            }
        }
    }

    if (context &&
            php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS) {
        ua_str = Z_STRVAL_PP(ua_zval);
    } else if (FG(user_agent)) {
        ua_str = FG(user_agent);
    }

    if (ua_str) {
#define _UA_HEADER "User-Agent: %s\r\n"
        char *ua;
        size_t ua_len;

        ua_len = sizeof(_UA_HEADER) + strlen(ua_str);

        /* ensure the header is only sent if user_agent is not blank */
        if (ua_len > sizeof(_UA_HEADER)) {
            ua = (char *)emalloc(ua_len + 1);
            if ((ua_len = snprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) {
                ua[ua_len] = 0;
                php_stream_write(stream, ua, ua_len);
            } else {
                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header");
            }

            if (ua) {
                efree(ua);
            }
        }
    }

    php_stream_write(stream, "\r\n", sizeof("\r\n")-1);

    /* Request content, such as for POST requests */
    if (context && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_STRLEN_PP(tmpzval) > 0) {
        php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
        php_stream_write(stream, "\r\n\r\n", sizeof("\r\n\r\n")-1);
    }

    location[0] = '\0';

    /*
     * We need to read the HTTP response header one-by-one, because
     * the original author did not know about MSG_PEEK.
     * The chunk_size will be reset later, once we have read the
     * header completely.
     */
    if (options & STREAM_WILL_CAST)
        chunk_size = php_stream_set_chunk_size(stream, 1);

    if (!header_init && FAILURE == zend_hash_find(EG(active_symbol_table),
            "http_response_header", sizeof("http_response_header"), (void **) &response_header)) {
        header_init = 1;
    }

    if (header_init) {
        zval *tmp;
        MAKE_STD_ZVAL(tmp);
        array_init(tmp);
        ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", tmp);

        zend_hash_find(EG(active_symbol_table),
                       "http_response_header", sizeof("http_response_header"), (void **) &response_header);
    }


    if (!php_stream_eof(stream)) {
        size_t tmp_line_len;
        /* get response header */

        if (_php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len TSRMLS_CC) != NULL) {
            zval *http_response;
            int response_code;

            MAKE_STD_ZVAL(http_response);
            ZVAL_NULL(http_response);

            if (tmp_line_len > 9) {
                response_code = atoi(tmp_line + 9);
            } else {
                response_code = 0;
            }
            switch(response_code) {
            case 200:
            case 302:
            case 301:
                reqok = 1;
                break;
            case 403:
                php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT,
                                        tmp_line, response_code);
                break;
            default:
                /* safety net in the event tmp_line == NULL */
                if (!tmp_line_len) {
                    tmp_line[0] = '\0';
                }
                php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE,
                                        tmp_line, response_code);
            }

            Z_STRLEN_P(http_response) = tmp_line_len;
            Z_STRVAL_P(http_response) = estrndup(tmp_line, Z_STRLEN_P(http_response));
            if (Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=='\n') {
                Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=0;
                Z_STRLEN_P(http_response)--;
                if (Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=='\r') {
                    Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=0;
                    Z_STRLEN_P(http_response)--;
                }
            }
            Z_TYPE_P(http_response) = IS_STRING;
            zend_hash_next_index_insert(Z_ARRVAL_PP(response_header), &http_response, sizeof(zval *), NULL);
        }
    } else {
        php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!");
        goto out;
    }

    /* read past HTTP headers */

    http_header_line = (char *)emalloc(HTTP_HEADER_BLOCK_SIZE);

    while (!body && !php_stream_eof(stream))	{

        if (php_stream_gets(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL)	{
            char *p;
            int found_eol = 0;
            int http_header_line_length;

            http_header_line[HTTP_HEADER_BLOCK_SIZE-1] = '\0';

            p = http_header_line;
            while(*p) {
                while(*p == '\n' || *p == '\r')	{
                    *p = '\0';
                    p--;
                    found_eol = 1;
                }
                if (found_eol)
                    break;
                p++;
            }
            http_header_line_length = p-http_header_line+1;

            if (!strncasecmp(http_header_line, "Location: ", 10)) {
                strlcpy(location, http_header_line + 10, sizeof(location));
            } else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) {
                php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0);
            } else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) {
                file_size = atoi(http_header_line + 16);
                php_stream_notify_file_size(context, file_size, http_header_line, 0);
            }

            if (http_header_line[0] == '\0') {
                body = 1;
            } else {
                zval *http_header;

                MAKE_STD_ZVAL(http_header);

                ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1);

                zend_hash_next_index_insert(Z_ARRVAL_PP(response_header), &http_header, sizeof(zval *), NULL);
            }
        } else {
            break;
        }
    }

    if (!reqok || location[0] != '\0')	{
        if (location[0] != '\0')
            php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);

        php_stream_close(stream);
        stream = NULL;

        if (location[0] != '\0')	{

            zval *entry, **entryp;
            char new_path[HTTP_HEADER_BLOCK_SIZE];
            char loc_path[HTTP_HEADER_BLOCK_SIZE];

            *new_path='\0';
            if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) &&
                                       strncasecmp(location, "https://", sizeof("https://")-1) &&
                                       strncasecmp(location, "ftp://", sizeof("ftp://")-1) &&
                                       strncasecmp(location, "ftps://", sizeof("ftps://")-1)))
            {
                if (*location != '/') {
                    if (*(location+1) != '\0' && resource->path) {
                        char *s = strrchr(resource->path, '/');
                        if (!s) {
                            s = resource->path;
                            if (!s[0]) {
                                efree(s);
                                s = resource->path = estrdup("/");
                            } else {
                                *s = '/';
                            }
                        }
                        s[1] = '\0';
                        if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') {
                            snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location);
                        } else {
                            snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location);
                        }
                    } else {
                        snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location);
                    }
                } else {
                    strlcpy(loc_path, location, sizeof(loc_path));
                }
                if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {
                    snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path);
                } else {
                    snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path);
                }
            } else {
                strlcpy(new_path, location, sizeof(new_path));
            }
            stream = php_stream_url_wrap_http_ex(NULL, new_path, mode, options, opened_path, context, --redirect_max, 0 STREAMS_CC TSRMLS_CC);
            if (stream && stream->wrapperdata)	{
                entryp = &entry;
                MAKE_STD_ZVAL(entry);
                ZVAL_EMPTY_STRING(entry);
                zend_hash_next_index_insert(Z_ARRVAL_PP(response_header), entryp, sizeof(zval *), NULL);
                zend_hash_internal_pointer_reset(Z_ARRVAL_P(stream->wrapperdata));
                while (zend_hash_get_current_data(Z_ARRVAL_P(stream->wrapperdata), (void **)&entryp) == SUCCESS) {
                    zval_add_ref(entryp);
                    zend_hash_next_index_insert(Z_ARRVAL_PP(response_header), entryp, sizeof(zval *), NULL);
                    zend_hash_move_forward(Z_ARRVAL_P(stream->wrapperdata));
                }
                zval_dtor(stream->wrapperdata);
                FREE_ZVAL(stream->wrapperdata);
            }
        } else {
            php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line);
        }
    }
out:
    if (http_header_line)
        efree(http_header_line);
    if (scratch)
        efree(scratch);
    php_url_free(resource);

    if (stream) {
        if (header_init) {
            stream->wrapperdata = *response_header;
            zval_add_ref(response_header);
        }
        php_stream_notify_progress_init(context, 0, file_size);
        /* Restore original chunk size now that we're done with headers (if applicable) */
        if (options & STREAM_WILL_CAST)
            php_stream_set_chunk_size(stream, chunk_size);

        /* restore the users auto-detect-line-endings setting */
        stream->flags |= eol_detect;

        /* as far as streams are concerned, we are now at the start of
         * the stream */
        stream->position = 0;
    }

    return stream;
}
示例#18
0
void settings_parse(config_t *config)
{

    int i = 0;

    const char ps2[4] = "PS2";

    char section_path[256];
    char setting[256];

    if (config == NULL)
    {
        return;
    }

    /// Home
    strcpy(section_path,ps2);
    strkat(section_path,".Home.");

    sprintf(setting,"%s%s",section_path,"Partition");
    strcpy(settings.home.partition,  cfg_get_string(setting,""));

    sprintf(setting,"%s%s",section_path,"Directory");
    strcpy(settings.home.directory,  cfg_get_string(setting,"mc0:/SYS-CONF"));


    /// Display
    strcpy(section_path,ps2);
    strkat(section_path,".Display.");

    sprintf(setting,"%s%s",section_path,"Mode");
    settings.display.mode = cfg_string_to_int(cfg_get_string(setting,"0"));
    printf("mode = %d\n",settings.display.mode);
    if (settings.display.mode == GRAPH_MODE_AUTO)
    {
        settings.display.mode = graph_get_region();
    }

    sprintf(setting,"%s%s",section_path,"Interlace");
    settings.display.interlace = cfg_get_bool(setting,0);

    sprintf(setting,"%s%s",section_path,"OffsetX");
    settings.display.x = cfg_string_to_int(cfg_get_string(setting,"0"));

    sprintf(setting,"%s%s",section_path,"OffsetY");
    settings.display.y = cfg_string_to_int(cfg_get_string(setting,"0"));

    /// Sound
    strcpy(section_path,ps2);
    strkat(section_path,".Sound.");

    sprintf(setting,"%s%s",section_path,"Stereo");
    settings.sound.stereo = cfg_get_bool(setting,1);

    sprintf(setting,"%s%s",section_path,"Volume");
    settings.sound.volume = cfg_string_to_int(cfg_get_string(setting,"100"));

    /// Font
    strcpy(section_path,ps2);
    strkat(section_path,".Font.");

    sprintf(setting,"%s%s",section_path,"Height");
    settings.font.height = cfg_string_to_int(cfg_get_string(setting,"16"));

    sprintf(setting,"%s%s",section_path,"Color");
    for (i = 0; i < 4; i++)
    {
        settings.font.color[i] = cfg_string_to_int(cfg_get_string_elem(setting,i,"128"));
    }

    sprintf(setting,"%s%s",section_path,"Highlight");
    for (i = 0; i < 4; i++)
    {
        settings.font.highlight[i] = cfg_string_to_int(cfg_get_string_elem(setting,i,"255"));
    }

    /// Input
    strcpy(section_path,ps2);
    strkat(section_path,".Input.");

    sprintf(setting,"%s%s",section_path,"Port");
    settings.input.port = cfg_string_to_int(cfg_get_string(setting,"0"));

    sprintf(setting,"%s%s",section_path,"Slot");
    settings.input.slot = cfg_string_to_int(cfg_get_string(setting,"0"));

    sprintf(setting,"%s%s",section_path,"Confirm");
    if (!strcmp("X",cfg_get_string(setting,"X")))
    {
        settings.input.confirm = PAD_CROSS;
    }
    else
    {
        settings.input.confirm = PAD_CIRCLE;
    }

    /// Devices
    strcpy(section_path,ps2);
    strkat(section_path,".Devices.");

    sprintf(setting,"%s%s",section_path,"Mass");
    settings.devices.mass = cfg_get_bool(setting,0);

    sprintf(setting,"%s%s",section_path,"HDD");
    settings.devices.hdd = cfg_get_bool(setting,0);

}