aboutsummaryrefslogtreecommitdiffstats
path: root/protocols/twitter/twitter_http.c
blob: dbac5461215cdb12aaa104fb3b9a7b0b9669e2ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/***************************************************************************\
*                                                                           *
*  BitlBee - An IRC to IM gateway                                           *
*  Simple module to facilitate twitter functionality.                       *
*                                                                           *
*  Copyright 2009 Geert Mulders <g.c.w.m.mulders@gmail.com>                 *
*                                                                           *
*  This library is free software; you can redistribute it and/or            *
*  modify it under the terms of the GNU Lesser General Public               *
*  License as published by the Free Software Foundation, version            *
*  2.1.                                                                     *
*                                                                           *
*  This library is distributed in the hope that it will be useful,          *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
*  Lesser General Public License for more details.                          *
*                                                                           *
*  You should have received a copy of the GNU Lesser General Public License *
*  along with this library; if not, write to the Free Software Foundation,  *
*  Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA           *
*                                                                           *
****************************************************************************/

/***************************************************************************\
*                                                                           *
*  Some funtions within this file have been copied from other files within  *
*  BitlBee.                                                                 *
*                                                                           *
****************************************************************************/

#include "twitter.h"
#include "bitlbee.h"
#include "url.h"
#include "misc.h"
#include "base64.h"
#include "oauth.h"
#include <ctype.h>
#include <errno.h>

#include "twitter_http.h"


static char *twitter_url_append(char *url, char *key, char *value);

/**
 * Do a request.
 * This is actually pretty generic function... Perhaps it should move to the lib/http_client.c
 */
void *twitter_http(struct im_connection *ic, char *url_string, http_input_function func,
		   gpointer data, int is_post, char **arguments, int arguments_len)
{
	struct twitter_data *td = ic->proto_data;
	char *tmp;
	GString *request = g_string_new("");
	void *ret;
	char *url_arguments;

	url_arguments = g_strdup("");

	// Construct the url arguments.
	if (arguments_len != 0) {
		int i;
		for (i = 0; i < arguments_len; i += 2) {
			tmp = twitter_url_append(url_arguments, arguments[i], arguments[i + 1]);
			g_free(url_arguments);
			url_arguments = tmp;
		}
	}
	// Make the request.
	g_string_printf(request, "%s %s%s%s%s HTTP/1.0\r\n"
			"Host: %s\r\n"
			"User-Agent: BitlBee " BITLBEE_VERSION " " ARCH "/" CPU "\r\n",
			is_post ? "POST" : "GET",
			td->url_path, url_string,
			is_post ? "" : "?", is_post ? "" : url_arguments, td->url_host);

	// If a pass and user are given we append them to the request.
	if (td->oauth_info) {
		char *full_header;
		char *full_url;

		full_url = g_strconcat(set_getstr(&ic->acc->set, "base_url"), url_string, NULL);
		full_header = oauth_http_header(td->oauth_info, is_post ? "POST" : "GET",
						full_url, url_arguments);

		g_string_append_printf(request, "Authorization: %s\r\n", full_header);
		g_free(full_header);
		g_free(full_url);
	} else {
		char userpass[strlen(ic->acc->user) + 2 + strlen(ic->acc->pass)];
		char *userpass_base64;

		g_snprintf(userpass, sizeof(userpass), "%s:%s", ic->acc->user, ic->acc->pass);
		userpass_base64 = base64_encode((unsigned char *) userpass, strlen(userpass));
		g_string_append_printf(request, "Authorization: Basic %s\r\n", userpass_base64);
		g_free(userpass_base64);
	}

	// Do POST stuff..
	if (is_post) {
		// Append the Content-Type and url-encoded arguments.
		g_string_append_printf(request,
				       "Content-Type: application/x-www-form-urlencoded\r\n"
				       "Content-Length: %zd\r\n\r\n%s",
				       strlen(url_arguments), url_arguments);
	} else {
		// Append an extra \r\n to end the request...
		g_string_append(request, "\r\n");
	}

	ret = http_dorequest(td->url_host, td->url_port, td->url_ssl, request->str, func, data);

	g_free(url_arguments);
	g_string_free(request, TRUE);
	return ret;
}

static char *twitter_url_append(char *url, char *key, char *value)
{
	char *key_encoded = g_strndup(key, 3 * strlen(key));
	http_encode(key_encoded);
	char *value_encoded = g_strndup(value, 3 * strlen(value));
	http_encode(value_encoded);

	char *retval;
	if (strlen(url) != 0)
		retval = g_strdup_printf("%s&%s=%s", url, key_encoded, value_encoded);
	else
		retval = g_strdup_printf("%s=%s", key_encoded, value_encoded);

	g_free(key_encoded);
	g_free(value_encoded);

	return retval;
}
} /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
require 'optparse'

require 'rdoc/ri/paths'

##
# RDoc::Options handles the parsing and storage of options

class RDoc::Options

  ##
  # Character-set

  attr_reader :charset

  ##
  # Should diagrams be drawn?

  attr_accessor :diagram

  ##
  # Files matching this pattern will be excluded

  attr_accessor :exclude

  ##
  # Should we draw fileboxes in diagrams?

  attr_reader :fileboxes

  ##
  # The list of files to be processed

  attr_accessor :files

  ##
  # Scan newer sources than the flag file if true.

  attr_reader :force_update

  ##
  # Description of the output generator (set with the <tt>-fmt</tt> option)

  attr_accessor :generator

  ##
  # Formatter to mark up text with

  attr_accessor :formatter

  ##
  # Image format for diagrams

  attr_reader :image_format

  ##
  # Include line numbers in the source listings?

  attr_reader :include_line_numbers

  ##
  # Name of the file, class or module to display in the initial index page (if
  # not specified the first file we encounter is used)

  attr_accessor :main_page

  ##
  # Merge into classes of the same name when generating ri

  attr_reader :merge

  ##
  # The name of the output directory

  attr_accessor :op_dir

  ##
  # Is RDoc in pipe mode?

  attr_accessor :pipe

  ##
  # Array of directories to search for files to satisfy an :include:

  attr_reader :rdoc_include

  ##
  # Include private and protected methods in the output?

  attr_accessor :show_all

  ##
  # Include the '#' at the front of hyperlinked instance method names

  attr_reader :show_hash

  ##
  # The number of columns in a tab

  attr_reader :tab_width

  ##
  # Template to be used when generating output

  attr_reader :template

  ##
  # Number of threads to parse with

  attr_accessor :threads

  ##
  # Documentation title

  attr_reader :title

  ##
  # Verbosity, zero means quiet

  attr_accessor :verbosity

  ##
  # URL of web cvs frontend

  attr_reader :webcvs

  def initialize # :nodoc:
    require 'rdoc/rdoc'
    @op_dir = 'doc'
    @show_all = false
    @main_page = nil
    @merge = false
    @exclude = []
    @generators = RDoc::RDoc::GENERATORS
    @generator = RDoc::Generator::Darkfish
    @generator_name = nil
    @rdoc_include = []
    @title = nil
    @template = nil
    @threads = if RUBY_PLATFORM == 'java' then
                 Java::java::lang::Runtime.getRuntime.availableProcessors * 2
               else
                 2
               end
    @diagram = false
    @fileboxes = false
    @show_hash = false
    @image_format = 'png'
    @tab_width = 8
    @include_line_numbers = false
    @force_update = true
    @verbosity = 1
    @pipe = false

    @webcvs = nil

    @charset = 'utf-8'
  end

  ##
  # Parse command line options.

  def parse(argv)
    opts = OptionParser.new do |opt|
      opt.program_name = File.basename $0
      opt.version = RDoc::VERSION
      opt.release = nil
      opt.summary_indent = ' ' * 4
      opt.banner = <<-EOF
Usage: #{opt.program_name} [options] [names...]

  Files are parsed, and the information they contain collected, before any
  output is produced. This allows cross references between all files to be
  resolved. If a name is a directory, it is traversed. If no names are
  specified, all Ruby files in the current directory (and subdirectories) are
  processed.

  How RDoc generates output depends on the output formatter being used, and on
  the options you give.

  - Darkfish creates frameless HTML output by Michael Granger.

  - ri creates ri data files
      EOF

      opt.separator nil
      opt.separator "Parsing Options:"
      opt.separator nil

      opt.on("--all", "-a",
             "Include all methods (not just public) in",
             "the output.") do |value|
        @show_all = value
      end

      opt.separator nil

      opt.on("--exclude=PATTERN", "-x", Regexp,
             "Do not process files or directories",
             "matching PATTERN.") do |value|
        @exclude << value
      end

      opt.separator nil

      opt.on("--extension=NEW=OLD", "-E",
             "Treat files ending with .new as if they",
             "ended with .old. Using '-E cgi=rb' will",
             "cause xxx.cgi to be parsed as a Ruby file.") do |value|
        new, old = value.split(/=/, 2)

        unless new and old then
          raise OptionParser::InvalidArgument, "Invalid parameter to '-E'"
        end

        unless RDoc::ParserFactory.alias_extension old, new then
          raise OptionParser::InvalidArgument, "Unknown extension .#{old} to -E"
        end
      end

      opt.separator nil

      opt.on("--force-update", "-U",
             "Forces rdoc to scan all sources even if",
             "newer than the flag file.") do |value|
        @force_update = value
      end

      opt.separator nil

      opt.on("--pipe",
             "Convert RDoc on stdin to HTML") do
        @pipe = true
      end

      opt.separator nil

      opt.on("--threads=THREADS", Integer,
             "Number of threads to parse with.") do |threads|
        @threads = threads
      end

      opt.separator nil
      opt.separator "Generator Options:"
      opt.separator nil

      opt.on("--charset=CHARSET", "-c",
             "Specifies the output HTML character-set.") do |value|
        @charset = value
      end

      opt.separator nil

      generator_text = @generators.keys.map { |name| "  #{name}" }.sort

      opt.on("--fmt=FORMAT", "--format=FORMAT", "-f", @generators.keys,
             "Set the output formatter.  One of:", *generator_text) do |value|
        @generator_name = value.downcase
        setup_generator
      end

      opt.separator nil

      opt.on("--include=DIRECTORIES", "-i", Array,
             "Set (or add to) the list of directories to",
             "be searched when satisfying :include:",
             "requests. Can be used more than once.") do |value|
        @rdoc_include.concat value.map { |dir| dir.strip }
      end

      opt.separator nil

      opt.on("--line-numbers", "-N",
             "Include line numbers in the source code.") do |value|
        @include_line_numbers = value
      end

      opt.separator nil

      opt.on("--main=NAME", "-m",
             "NAME will be the initial page displayed.") do |value|
        @main_page = value
      end

      opt.separator nil

      opt.on("--output=DIR", "--op", "-o",
             "Set the output directory.") do |value|
        @op_dir = value
      end

      opt.separator nil

      opt.on("--show-hash", "-H",
             "A name of the form #name in a comment is a",
             "possible hyperlink to an instance method",
             "name. When displayed, the '#' is removed",
             "unless this option is specified.") do |value|
        @show_hash = value
      end

      opt.separator nil

      opt.on("--tab-width=WIDTH", "-w", OptionParser::DecimalInteger,
             "Set the width of tab characters.") do |value|
        @tab_width = value
      end

      opt.separator nil

      opt.on("--template=NAME", "-T",
             "Set the template used when generating",
             "output.") do |value|
        @template = value
      end

      opt.separator nil

      opt.on("--title=TITLE", "-t",
             "Set TITLE as the title for HTML output.") do |value|
        @title = value
      end

      opt.separator nil

      opt.on("--webcvs=URL", "-W",
             "Specify a URL for linking to a web frontend",
             "to CVS. If the URL contains a '\%s', the",
             "name of the current file will be",
             "substituted; if the URL doesn't contain a",
             "'\%s', the filename will be appended to it.") do |value|
        @webcvs = value
      end

      opt.separator nil
      opt.separator "Diagram Options:"
      opt.separator nil

      image_formats = %w[gif png jpg jpeg]
      opt.on("--image-format=FORMAT", "-I", image_formats,
             "Sets output image format for diagrams. Can",
             "be #{image_formats.join ', '}. If this option",
             "is omitted, png is used. Requires",
             "diagrams.") do |value|
        @image_format = value
      end

      opt.separator nil

      opt.on("--diagram", "-d",
             "Generate diagrams showing modules and",
             "classes. You need dot V1.8.6 or later to",
             "use the --diagram option correctly. Dot is",
             "available from http://graphviz.org") do |value|
        check_diagram
        @diagram = true
      end

      opt.separator nil

      opt.on("--fileboxes", "-F",
             "Classes are put in boxes which represents",
             "files, where these classes reside. Classes",
             "shared between more than one file are",
             "shown with list of files that are sharing",
             "them. Silently discarded if --diagram is",
             "not given.") do |value|
        @fileboxes = value
      end

      opt.separator nil
      opt.separator "ri Generator Options:"
      opt.separator nil

      opt.on("--ri", "-r",
             "Generate output for use by `ri`. The files",
             "are stored in the '.rdoc' directory under",
             "your home directory unless overridden by a",
             "subsequent --op parameter, so no special",
             "privileges are needed.") do |value|
        @generator_name = "ri"
        @op_dir = RDoc::RI::Paths::HOMEDIR
        setup_generator
      end

      opt.separator nil

      opt.on("--ri-site", "-R",
             "Generate output for use by `ri`. The files",
             "are stored in a site-wide directory,",
             "making them accessible to others, so",
             "special privileges are needed.") do |value|
        @generator_name = "ri"
        @op_dir = RDoc::RI::Paths::SITEDIR
        setup_generator
      end

      opt.separator nil

      opt.on("--merge", "-M",
             "When creating ri output, merge previously",
             "processed classes into previously",
             "documented classes of the same name.") do |value|
        @merge = value
      end

      opt.separator nil
      opt.separator "Generic Options:"
      opt.separator nil

      opt.on("--debug", "-D",
             "Displays lots on internal stuff.") do |value|
        $DEBUG_RDOC = value
      end

      opt.on("--quiet", "-q",
             "Don't show progress as we parse.") do |value|
        @verbosity = 0
      end

      opt.on("--verbose", "-v",
             "Display extra progress as we parse.") do |value|
        @verbosity = 2
      end

      opt.separator nil
      opt.separator 'Deprecated options - these warn when set'
      opt.separator nil

      opt.on("--inline-source", "-S") do |value|
        warn "--inline-source will be removed from RDoc on or after August 2009"
      end

      opt.on("--promiscuous", "-p") do |value|
        warn "--promiscuous will be removed from RDoc on or after August 2009"
      end

      opt.separator nil
    end

    argv.insert(0, *ENV['RDOCOPT'].split) if ENV['RDOCOPT']

    opts.parse! argv

    @files = argv.dup

    @rdoc_include << "." if @rdoc_include.empty?

    if @exclude.empty? then
      @exclude = nil
    else
      @exclude = Regexp.new(@exclude.join("|"))
    end

    check_files

    # If no template was specified, use the default template for the output
    # formatter

    @template ||= @generator_name

  rescue OptionParser::InvalidArgument, OptionParser::InvalidOption => e
    puts opts
    puts
    puts e
    exit 1
  end

  ##
  # Set the title, but only if not already set. This means that a title set
  # from the command line trumps one set in a source file

  def title=(string)
    @title ||= string
  end

  ##
  # Don't display progress as we process the files

  def quiet
    @verbosity.zero?
  end

  def quiet=(bool)
    @verbosity = bool ? 0 : 1
  end

  private

  ##
  # Set up an output generator for the format in @generator_name

  def setup_generator
    @generator = @generators[@generator_name]

    unless @generator then
      raise OptionParser::InvalidArgument, "Invalid output formatter"
    end
  end

  # Check that the right version of 'dot' is available.  Unfortunately this
  # doesn't work correctly under Windows NT, so we'll bypass the test under
  # Windows.

  def check_diagram
    return if RUBY_PLATFORM =~ /mswin|cygwin|mingw|bccwin/

    ok = false
    ver = nil

    IO.popen "dot -V 2>&1" do |io|
      ver = io.read
      if ver =~ /dot.+version(?:\s+gviz)?\s+(\d+)\.(\d+)/ then
        ok = ($1.to_i > 1) || ($1.to_i == 1 && $2.to_i >= 8)
      end
    end

    unless ok then
      if ver =~ /^dot.+version/ then
        $stderr.puts "Warning: You may need dot V1.8.6 or later to use\n",
          "the --diagram option correctly. You have:\n\n   ",
          ver,
          "\nDiagrams might have strange background colors.\n\n"
      else
        $stderr.puts "You need the 'dot' program to produce diagrams.",
          "(see http://www.research.att.com/sw/tools/graphviz/)\n\n"
        exit
      end
    end
  end

  ##
  # Check that the files on the command line exist

  def check_files
    @files.each do |f|
      stat = File.stat f rescue next
      raise RDoc::Error, "file '#{f}' not readable" unless stat.readable?
    end
  end

end