Use libcurl to interact with the transmission server API
330129
private function hit_api()
    {
        if (!$this->_url) {
            Errors::add('transmission extension', 'Config option transmission_api_url not specified');
            return;
        }

        if (!extension_loaded('curl')) {
            Errors::add('transmission extension', 'Curl PHP extension not installed');
            return;
        }

        // See https://trac.transmissionbt.com/browser/trunk/extras/rpc-spec.txt for docs here
        // 1) Hit the API and get back a 409 with a token in the X-Transmission-Session-Id header
        // 2) Pass that token in as a header in the next request which will get our list of torrents

        $curl = curl_init();

        if (!$curl) {
            Errors::add('transmission extension', 'failed initializing curl');
            return;
        }

        $url = $this->_url . '/transmission/rpc';

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_HEADER  => true,
            CURLOPT_RETURNTRANSFER  => true,
        ]);

        $result = curl_exec($curl);

        if (!$result) {
            Errors::add('transmission extension', 'failed running curl to get token');
            return;
        }

        if(!preg_match('/X-Transmission-Session-Id: (\S+)/', $result, $m)) {
            Errors::add('transmission extension', 'Failed parsing token');
            return;
        }

        $token = $m[1];

        $postdata = json_encode([
            'method' => 'torrent-get',
            'arguments' => [
                'fields'=> [
                    'name',
                    'percentDone',
                    'rateDownload',
                    'rateUpload',
                    'leftUntilDone',
                    'eta',
                    'status',
                    'uploadRatio',
                    'downloadedEver',
                    'uploadedEver',
                ]
            ]
        ]);


        curl_setopt_array($curl, [
            CURLOPT_HTTPHEADER => ['X-Transmission-Session-Id: '.$token],
            CURLOPT_URL => $url,
            CURLOPT_POSTFIELDS => $postdata,
            CURLOPT_HEADER  => false,
        ]);

        $result = curl_exec($curl);

        curl_close($curl);

        if (!$result) {
            Errors::add('transmission extension', 'failed running curl to get data');
            return;
        }

        $response = json_decode($result, true);

        if (!$response) {
            Errors::add('transmission extension', 'failed decoding transmission response as json');
            return;
        }

        if ($response['result'] != 'success') {
            Errors::add('transmission extension', 'transmission API call was not successful: '.$response['result']);
            return;
        }

        return $response['arguments']['torrents'];

    }
936231
def api_server(connection, server_class):
    

    # run api server on connection
    return server_class(
        link=xbahn.connection.link.Link(
            # use the connection to receive messages
            receive=connection,
            # use the connection to respond to received messages
            respond=connection
        )
    )
1196184
def send(transport, time, state, host, description, service, tag, attribute,
         ttl, metric_f, echo):
    """"""
    client = CommandLineClient(transport)
    event = client.create_event({
        'time': time,
        'state': state,
        'host': host,
        'description': description,
        'service': service,
        'tags': tag,
        'attributes': dict(attribute),
        'ttl': ttl,
        'metric_f': metric_f
    })

    with client:
        client.send_event(event)
    if echo:
        echo_event(client.create_dict(event))
55018
function Server(transport, keyFilePath, crtFilePath) {
	X224.call(this, transport);
	this.keyFilePath = keyFilePath;
	this.crtFilePath = crtFilePath;
	var self = this;
	this.transport.once('data', function (s) {
		self.recvConnectionRequest(s);
	});
}
848338
def url(proto, server, port=None, uri=None):
        """"""
        url_parts = [proto, '://', server]
        if port:
            port = int(port)
            if port < 1 or port > 65535:
                raise ValueError('invalid port value')
            if not ((proto == 'http' and port == 80) or
                    (proto == 'https' and port == 443)):
                url_parts.append(':')
                url_parts.append(str(port))

        if uri:
            url_parts.append('/')
            url_parts.append(requests.utils.quote(uri.strip('/')))

        url_parts.append('/')
        return ''.join(url_parts)
47258
def urljoin(netloc, port, ssl):
    

    rv = ("https" if ssl else "http") + "://" + netloc
    if ssl and port != 443 or not ssl and port != 80:
        rv += ":%i" % port
    return rv
969814
def _call_api(self, api_url, err_env):
        
        while True:  # may retry on error
            api_request = urllib2.Request(
                api_url, headers={"Accept-Encoding": "gzip"})

            log.debug("Amazon URL: %s" % api_url)

            try:
                if self.Timeout and sys.version[:3] in ["2.4", "2.5"]:
                    # urllib2.urlopen() doesn't accept timeout until 2.6
                    old_timeout = socket.getdefaulttimeout()
                    try:
                        socket.setdefaulttimeout(self.Timeout)
                        return urllib2.urlopen(api_request)
                    finally:
                        socket.setdefaulttimeout(old_timeout)
                else:
                    # the simple way
                    return urllib2.urlopen(api_request, timeout=self.Timeout)
            except:
                if not self.ErrorHandler:
                    raise

                exception = sys.exc_info()[1]  # works in Python 2 and 3
                err = {'exception': exception}
                err.update(err_env)
                if not self.ErrorHandler(err):
                    raise
28600
def send_and_receive_raw(self, target, lun, netfn, raw_bytes):
        
        return self._send_and_receive(target=target,
                                      lun=lun,
                                      netfn=netfn,
                                      cmdid=array('B', raw_bytes)[0],
                                      payload=raw_bytes[1:])
643138
function startServer(argv, httpPort, httpsPort, certs) {
  console.log('Launching proxy server...');
  console.log('   http: ' + httpPort);
  console.log('  https: ' + httpsPort);

  // Injects a node stream by buffering all data, transforming it, and writing
  // it back out.
  // Module IDs are assigned on demand and rotate 0-126.
  var nextModuleId = 0;
  function injectStream(url, source, target) {
    var moduleId = nextModuleId++;
    if (nextModuleId >= 127) {
      nextModuleId = 0;
    }
    var sourceCode = '';
    source.on('data', function(chunk) {
      sourceCode += chunk;
    });
    source.on('end', function() {
      try {
        var targetCode = transformCode(moduleId, url, sourceCode, argv);
        target.end(targetCode);
      } catch (e) {
        console.log('Error during transformation, writing through.');
        console.log(e);
        target.end(sourceCode);
      }
    });
  };

  // Handles both HTTP and HTTPS requests.
  function handler(req, res) {
    // Support both the ?url= mode and the X-WTF-URL header.
    var targetUrl;
    if (req.headers['x-wtf-url']) {
      targetUrl = req.headers['x-wtf-url'];
    } else {
      var parsedUrl = url.parse(req.url, true);
      var query = parsedUrl.query;
      targetUrl = query.url;
    }
    if (!targetUrl || targetUrl.indexOf('http') != 0) {
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end();
      return;
    }

    res.on('error', function(e) {
      console.log('ERROR (source): ' + e);
    });

    var targetModule = targetUrl.indexOf('https') == 0 ? https : http;
    targetModule.get(targetUrl, function(originalRes) {
      // Eat errors, otherwise the app will die.
      originalRes.on('error', function(e) {
        console.log('ERROR (target): ' + e);
      });

      // Pull out content type to see if we are interested in it.
      var supportedContentType = false;
      var contentType = originalRes.headers['content-type'];
      if (contentType && contentType.indexOf(';') != 0) {
        contentType = contentType.substr(0, contentType.indexOf(';'));
      }
      switch (contentType) {
        case 'text/javascript':
        case 'application/javascript':
          supportedContentType = true;
          break;
      }

      // Also parse the URL - some servers don't return content type for some
      // reason.
      var supportedPath = false;
      var contentUrl = url.parse(targetUrl);
      if (path.extname(contentUrl.pathname) == '.js') {
        supportedPath = true;
      }

      if (supportedContentType || supportedPath) {
        var headers = [];
        for (var key in originalRes.headers) {
          if (key == 'content-length') {
            continue;
          }
          headers.push([key, originalRes.headers[key]]);
        }
        res.writeHead(originalRes.statusCode, headers);
        injectStream(targetUrl, originalRes, res);
      } else {
        console.log('Pass-through: ' + targetUrl, contentType);
        res.writeHead(originalRes.statusCode, originalRes.headers);
        originalRes.pipe(res);
      }
    }).on('error', function(e) {
      console.log(e);
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end(e.message);
    });
  };

  // HTTP server.
  var httpServer = http.createServer(handler);
  httpServer.listen(httpPort);

  // HTTPS server.
  var httpsServer = https.createServer({
    key: certs.privateKey,
    cert: certs.certificate
  }, handler);
  httpsServer.listen(httpsPort);

  console.log('Server ready, use ctrl-c to exit...');
  console.log('');
}
995473
function Client(transport, fastPathTransport) {
	Sec.call(this, transport, fastPathTransport);
	// for basic RDP layer (in futur)
	this.enableSecureCheckSum = false;
	var self = this;
	this.transport.on('connect', function(gccClient, gccServer, userId, channels) {
		self.connect(gccClient, gccServer, userId, channels);
	}).on('close', function() {
		self.emit('close');
	}).on('error', function (err) {
		self.emit('error', err);
	});
}
612945
def url_to_host_port(url, port=None):
    
    if not url.startswith('http://') and not url.startswith('https://'):
        url = 'http://' + url

    if not port:
        port = RPC_SERVER_PORT

    urlinfo = urllib2.urlparse.urlparse(url)
    hostport = urlinfo.netloc

    parts = hostport.split('@')
    if len(parts) > 2:
        return None, None

    if len(parts) == 2:
        hostport = parts[1]

    parts = hostport.split(':')
    if len(parts) > 2:
        return None, None

    if len(parts) == 2:
        try:
            port = int(parts[1])
            assert 0 < port and port < 65535, 'Invalid port'
        except TypeError:
            return None, None

    return parts[0], port
423017
def connect(self, addr):
        """"""
        # Here we assume that the socket is client-side, and not
        # connected at the time of the call.  We connect it, then wrap it.
        if self._sslobj:
            raise ValueError("attempt to connect already-connected SSLSocket!")
        socket.connect(self, addr)
        if six.PY3:
            self._sslobj = self.context._wrap_socket(self._sock, False, self.server_hostname)
        else:
            if self.ciphers is None:
                self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
                                            self.cert_reqs, self.ssl_version,
                                            self.ca_certs)
            else:
                self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
                                            self.cert_reqs, self.ssl_version,
                                            self.ca_certs, self.ciphers)
        if self.do_handshake_on_connect:
            self.do_handshake()
1019571
def _send(self):
        

        while len(self.queue) > 0:
            metric = self.queue.popleft()

            path = '%s.%s.%s' % (
                metric.getPathPrefix(),
                metric.getCollectorPath(),
                metric.getMetricPath()
            )

            topic, value, timestamp = str(metric).split()
            logging.debug(
                "Sending.. topic[%s], value[%s], timestamp[%s]",
                path,
                value,
                timestamp
            )

            self.api.metric(path, (timestamp, value), host=metric.host)
691965
def connectionMade(self):
        """"""

        self.factory.request_xml = str(self.factory.payload)

        self.sendCommand('POST', '/cimom')

        self.sendHeader('Host', '%s:%d' %
                        (self.transport.addr[0], self.transport.addr[1]))
        self.sendHeader('User-Agent', 'pywbem/twisted')
        self.sendHeader('Content-length', len(self.factory.payload))
        self.sendHeader('Content-type', 'application/xml')

        if self.factory.creds:
            auth = base64.b64encode('%s:%s' % (self.factory.creds[0],
                                               self.factory.creds[1]))

            self.sendHeader('Authorization', 'Basic %s' % auth)

        self.sendHeader('CIMOperation', str(self.factory.operation))
        self.sendHeader('CIMMethod', str(self.factory.method))
        self.sendHeader('CIMObject', str(self.factory.object))

        self.endHeaders()

        # TODO: Figure out why twisted doesn't support unicode.  An
        # exception should be thrown by the str() call if the payload
        # can't be converted to the current codepage.

        self.transport.write(str(self.factory.payload))
427800
def _get_http_request(netloc, path="/", headers=None, ssl=False):
    
    if ssl:
        port = 443
    else:
        port = 80

    host = netloc

    if len(netloc.split(":")) == 2:
        host, port = netloc.split(":")

    request = {"host": host,
               "port": port,
               "path": path,
               "ssl": ssl,
               "method": "GET"}
    if headers:
        request["headers"] = headers

    response = {}

    try:
        conn = ICHTTPConnection(host=host, port=port, timeout=10)

        conn.request(path, headers, ssl, timeout=10)
        response["status"] = conn.status
        response["reason"] = conn.reason
        response["headers"] = conn.headers
        body = conn.body

        try:
            response["body"] = body.encode('utf-8')
        except UnicodeDecodeError:
            # if utf-8 fails to encode, just use base64
            response["body.b64"] = body.encode('base64')

    except Exception as err:
        response["failure"] = str(err)

    result = {"response": response,
              "request": request}

    return result
1063097
def build_api_url(host=REMOTES['default']['ip'],
                  port=REMOTES['default']['port'],
                  path=REMOTES['default']['path'],
                  username=None,
                  password=None,
                  ssl=False):
    """"""
    credentials = make_http_credentials(username, password)
    scheme = 'http'
    if not path:
        path = ''
    if path and not path.startswith('/'):
        path = "/%s" % path
    if ssl:
        scheme += 's'
    return "%s://%s%s:%i%s" % (scheme, credentials, host, port, path)
836400
def api(name, url, token, **kwargs):
    """"""
    return Client(token).api(name, url, **kwargs)