Example #1
0
function sms_custom_handle($sms_datetime, $sms_sender, $custom_keyword, $custom_param = '')
{
    global $datetime_now;
    $ok = false;
    $db_query = "SELECT custom_url FROM " . _DB_PREF_ . "_featureCustom WHERE custom_keyword='{$custom_keyword}'";
    $db_result = dba_query($db_query);
    $db_row = dba_fetch_array($db_result);
    $custom_url = $db_row['custom_url'];
    $sms_datetime = core_display_datetime($sms_datetime);
    $custom_url = str_replace("{SMSDATETIME}", urlencode($sms_datetime), $custom_url);
    $custom_url = str_replace("{SMSSENDER}", urlencode($sms_sender), $custom_url);
    $custom_url = str_replace("{CUSTOMKEYWORD}", urlencode($custom_keyword), $custom_url);
    $custom_url = str_replace("{CUSTOMPARAM}", urlencode($custom_param), $custom_url);
    $url = parse_url($custom_url);
    if (!$url['port']) {
        $url['port'] = 80;
    }
    // fixme anton -deprecated when using PHP5
    //$connection = fsockopen($url['host'],$url['port'],&$error_number,&$error_description,60);
    $connection = fsockopen($url['host'], $url['port'], $error_number, $error_description, 60);
    if ($connection) {
        socket_set_blocking($connection, false);
        fputs($connection, "GET {$custom_url} HTTP/1.0\r\n\r\n");
        $db_query = "\n\t    INSERT INTO " . _DB_PREF_ . "_featureCustom_log\n\t    (sms_sender,custom_log_datetime,custom_log_keyword,custom_log_url) \n\t    VALUES\n\t    ('{$sms_sender}','{$datetime_now}','{$custom_keyword}','{$custom_url}')\n\t";
        if ($new_id = @dba_insert_id($db_query)) {
            $ok = true;
        }
    }
    return $ok;
}
Example #2
0
function IMAP_connect($s, $p = '143')
{
    global $_IMAP_KEY;
    $c = fsockopen($s, $p);
    socket_set_blocking($c, FALSE);
    return array('conn' => $c, 'key' => $_IMAP_KEY++, 'callbacks' => array(), 'cbdata' => array(), 'state' => 'UNAUTHENTICATED');
}
 function Connect2ICQServer()
 {
     $this->fp = @fsockopen($this->ICQServer, 80, $errno, $errstr, 90);
     if (!$this->fp) {
         return;
     }
     socket_set_blocking($this->fp, 1);
 }
Example #4
0
 function openSocket($server, $port)
 {
     if ($this->activeSocket = fsockopen($server, $port)) {
         socket_set_blocking($this->activeSocket, 0);
         socket_set_timeout($this->activeSocket, 31536000);
         return true;
     }
     return false;
 }
function multiHTTP($urlArr)
{
    $sockets = array();
    $urlInfo = array();
    $retDone = array();
    $retData = array();
    $errno = array();
    $errstr = array();
    $user_agent = "Castcloud crawler; +https://github.com/castcloud/castcloud (PHP " . phpversion() . ")";
    for ($x = 0; $x < count($urlArr); $x++) {
        try {
            $urlInfo[$x] = parse_url($urlArr[$x]);
            $urlInfo[$x]["port"] = array_key_exists("port", $urlInfo[$x]) ? $urlInfo[$x]["port"] : 80;
            $urlInfo[$x]["path"] = array_key_exists("path", $urlInfo[$x]) ? $urlInfo[$x]["path"] : "/";
            $sockets[$x] = fsockopen($urlInfo[$x]["host"], $urlInfo[$x]["port"], $errno[$x], $errstr[$x], 1);
            if ($sockets[$x]) {
                socket_set_blocking($sockets[$x], FALSE);
                $query = array_key_exists("query", $urlInfo[$x]) ? "?" . $urlInfo[$x]["query"] : "";
                $req = "GET " . $urlInfo[$x]["path"] . "{$query} HTTP/1.0\r\nHost: " . $urlInfo[$x]["host"] . "\r\nUser-Agent: " . $user_agent . "\r\n";
                if (array_key_exists("etag", $GLOBALS['casts'][$x])) {
                    $req .= "If-None-Match: " . $GLOBALS['casts'][$x]['etag'] . "\r\n";
                }
                $req .= "\r\n";
                fputs($sockets[$x], $req);
            }
        } catch (Exception $e) {
            echo $urlArr[$x] . " failed :(\n";
        }
    }
    echo "Done opening " . sizeof($sockets) . " sockets!\n\n";
    $done = false;
    while (!$done) {
        for ($x = 0; $x < count($urlArr); $x++) {
            if ($sockets[$x]) {
                if (!feof($sockets[$x])) {
                    if (array_key_exists($x, $retData)) {
                        $retData[$x] .= fgets($sockets[$x], 512);
                    } else {
                        $retData[$x] = fgets($sockets[$x], 512);
                    }
                } else {
                    if (!array_key_exists($x, $retData)) {
                        $retData[$x] = null;
                    }
                    $retDone[$x] = 1;
                }
            } else {
                $retData[$x] = null;
                $retDone[$x] = 1;
            }
        }
        usleep(1);
        $done = array_sum($retDone) == count($urlArr);
    }
    return $retData;
}
 /**
  * Connect to the stratum server.
  * @param string $host
  * @param string $port
  * @return array stdResult
  */
 public function connect($host, $port = "3333")
 {
     $connect_string = "tcp://{$host}:{$port}";
     if (($this->conn = stream_socket_client($connect_string, $errno, $errstr)) === false) {
         return array(false, "Unable to connect to {$host}:{$port} [{$errstr}]");
     }
     $this->connected = true;
     socket_set_blocking($this->conn, false);
     return array(true, "Connected to {$host}:{$port}");
 }
Example #7
0
function gw_send_sms($mobile_sender, $sms_to, $sms_msg, $gp_code = "", $uid = "", $smslog_id = "", $flash = false)
{
    //error_log("gw_send_sms: $mobile_sender, $sms_to, $sms_msg \n");
    global $kannel_param;
    global $gateway_number;
    $ok = false;
    if ($gateway_number) {
        $sms_from = $gateway_number;
    } else {
        $sms_from = $mobile_sender;
    }
    if ($flash) {
        $sms_type = KANNEL_SMSTYPE_FLASH;
    } else {
        $sms_type = KANNEL_SMSTYPE_TEXT;
    }
    // we can give kannel a callback url where it
    // will give us the dlr of the sms we're sending
    // (%d is where kannel will put the status, the rest of
    // the params are for us)
    //
    $dlr_url = urlencode($kannel_param['playsms_web'] . "/plugin/gateway/kannel/dlr.php?dlr=%d&smslog_id={$smslog_id}&uid={$uid}");
    $dlr_mask = "31";
    // now build the url to send
    // this sms to kannel
    //
    $URL = "/cgi-bin/sendsms?";
    $URL .= "username="******"&password="******"&from=" . urlencode($sms_from) . "&to=" . urlencode($sms_to) . "&text=" . urlencode($sms_msg);
    $URL .= "&mclass={$sms_type}";
    $URL .= "&dlr-mask={$dlr_mask}&dlr-url={$dlr_url}";
    // TODO: replace the fsockopen stuff with php's file_get_contents()
    // but for some reason it doesn't seem to work with kannel!
    //
    //$server= 'http://' . $kannel_param['bearerbox_host'] . ':' . $kannel_param['sendsms_port'];
    //$URL= $server . $URL;
    //$response= file_get_contents($URL);
    //if ($response == KANNEL_MSG_ACCEPTED) {
    //    $ok = true;
    //}
    $connection = fsockopen($kannel_param['bearerbox_host'], $kannel_param['sendsms_port'], $error_number, $error_description, 60);
    if ($connection) {
        socket_set_blocking($connection, false);
        fputs($connection, "GET {$URL} HTTP/1.0\r\n\r\n");
        while (!feof($connection)) {
            $myline = fgets($connection, 128);
            if ($myline == KANNEL_MSG_ACCEPTED) {
                $ok = true;
            }
        }
    }
    fclose($connection);
    return $ok;
}
 function socket_open($hostname, $port, $timeout)
 {
     if ($this->socket = @fsockopen($hostname, $port, $errno, $errstr, $timeout)) {
         socket_set_blocking($this->socket, 0);
         socket_set_timeout($this->socket, 31536000);
         return true;
     } else {
         $this->error = "{$errstr} (#{$errno}, " . __FILE__ . ", " . __LINE__ . ")";
         return false;
     }
 }
 function socket_open($hostname, $port, $timeout)
 {
     if ($this->socket = @fsockopen($hostname, $port, $errno, $errstr, $timeout)) {
         socket_set_blocking($this->socket, 0);
         socket_set_timeout($this->socket, 60);
         return true;
     } else {
         $this->error = "{$errstr} (#{$errno})";
         return false;
     }
 }
Example #10
0
 private function connect()
 {
     if (!isset($this->jid)) {
         return $this->connection = false;
     }
     if (!isset($this->idle)) {
         $this->idle = true;
     }
     if (!isset($this->resource)) {
         $this->resource = 'caldav' . getmypid();
     }
     if (!preg_match('/^\\//', $this->resource)) {
         $this->resource = '/' . $this->resource;
     }
     $temp = explode('@', $this->jid);
     $this->username = $temp[0];
     if (!isset($this->server)) {
         $this->server = $temp[1];
     }
     $r = dns_get_record("_xmpp-client._tcp." . $this->server, DNS_SRV);
     if (0 < count($r)) {
         $this->original_server = $this->server;
         $this->server = $r[0]['target'];
         $this->original_port = $this->port;
         $this->port = $r[0]['port'];
     }
     if (!isset($this->port)) {
         $this->port = 5222;
     }
     if ('ssl' == $this->tls || !isset($this->tls) && 5223 == $this->port) {
         $url = 'ssl://' . $this->server;
     } elseif ('tls' == $this->tls || !isset($this->tls) && 5222 == $this->port) {
         $url = 'tcp://' . $this->server;
     } else {
         $url = 'tcp://' . $this->server;
     }
     if (isset($this->original_server)) {
         $this->server = $this->original_server;
     }
     $this->connection = stream_socket_client($url . ':' . $this->port, $errno, $errstring, 10, STREAM_CLIENT_ASYNC_CONNECT);
     if (false === $this->connection) {
         if ($errno != 0) {
             $log = $errstring;
         }
         return false;
     }
     $this->initializeQueue();
     socket_set_blocking($this->connection, false);
     return true;
 }
Example #11
0
 function connect($server, $port = 110)
 {
     //  Opens a socket to the specified server. Unless overridden,
     //  port defaults to 110. Returns true on success, false on fail
     // If MAILSERVER is set, override $server with it's value
     if (!empty($this->MAILSERVER)) {
         $server = $this->MAILSERVER;
     }
     if (empty($server)) {
         $this->ERROR = "POP3 connect:" . ' ' . "No server specified";
         unset($this->FP);
         return false;
     }
     $fp = fsockopen("{$server}", $port, $errno, $errstr);
     if (!$fp) {
         $this->ERROR = "POP3 connect:" . ' ' . "Error " . "[{$errno}] [{$errstr}]";
         unset($this->FP);
         return false;
     }
     socket_set_blocking($fp, -1);
     $this->update_timer();
     $reply = fgets($fp, $this->BUFFER);
     $reply = $this->strip_clf($reply);
     if ($this->DEBUG) {
         error_log("POP3 SEND [connect: {$server}] GOT [{$reply}]", 0);
     }
     if (!$this->is_ok($reply)) {
         $this->ERROR = "POP3 connect:" . ' ' . "Error " . "[{$reply}]";
         unset($this->FP);
         return false;
     }
     $this->FP = $fp;
     $this->BANNER = $this->parse_banner($reply);
     //		if(get_settings('shot_rfc_check')) {
     $this->RFC1939 = $this->noop();
     if ($this->RFC1939) {
         $this->ERROR = "POP3: premature NOOP OK, NOT an RFC 1939 Compliant server";
         $this->quit();
         return false;
     } else {
         return true;
     }
     //		} else {
     //			return true;
     //		}
 }
Example #12
0
function jab_connect($server, $port)
{
    global $errfile;
    if (!isset($errfile)) {
        $errfile = "/tmp/php_error.log";
    }
    $fd = fsockopen($server, $port, $errno, $errstr, 30);
    if (!$fd) {
        $errmsg = "Error: {$errno} - {$errstr}\n";
        error_log($errmsg, 3, $errfile);
        return FALSE;
    }
    $fdp = socket_set_blocking($fd, 0);
    $stream = "<stream:stream to='{$server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>";
    fputs($fd, $stream);
    return $fd;
}
Example #13
0
 private function sendViaFileHandle($message)
 {
     try {
         // Open the UDP socket to send the data.
         $socket = @fsockopen("udp://" . $this->destHost, $this->destPort);
         if (!$socket) {
             // TODO: Log.warn: "Socket failed to open"
             // TODO: Use a finally block instead (PHP 5.5).
             throw new Exception("Cancelling send.");
         }
         @socket_set_blocking($socket, FALSE);
         // Send the header.
         $header = $message->getHeader();
         $bytesWritten = @fwrite($socket, $header);
         if ($bytesWritten < strlen($header)) {
             // TODO: Log.warn "Only wrote $bytesWritten bytes of the header."
             // TODO: Use a finally block instead (PHP 5.5).
             throw new Exception("Cancelling send.");
         }
         // Send the payload.
         $payload = $message->getPayload();
         $bytesWritten = @fwrite($socket, $payload);
         if ($bytesWritten < strlen($payload)) {
             // TODO: Log.warn "Only wrote $bytesWritten bytes of the payload."
             // TODO: Use a finally block instead (PHP 5.5).
             throw new Exception("Cancelling send.");
         }
         // Close the socket.
         @fclose($socket);
         // dereference the handles.
         $socket = null;
         $header = null;
         $payload = null;
     } catch (Exception $e) {
         // TODO: Move this to a finally block (PHP 5.5).
         if ($socket) {
             try {
                 @fclose($socket);
             } catch (Exception $e2) {
             }
         }
         $socket = null;
         return;
     }
 }
Example #14
0
 /**
  * 데이타 전송함수
  *
  * @param string $mode : POST, GET 중 하나를 입력한다.
  * @return string
  */
 function send($mode = "GET")
 {
     // 웹서버에 접속한다.
     $fp = fsockopen($this->host, $this->port, $errno, $errstr, 10);
     if (!$fp) {
         return $this->setError($this->host . "로의 접속에 실패했습니다.");
     }
     // GET, POST 방식에 따라 헤더를 다르게 구성한다.
     if (strtoupper($mode) == "POST") {
         $this->query = $this->postMethod();
     } else {
         $this->query = $this->getMethod();
     }
     fputs($fp, $this->query);
     socket_set_blocking($fp, FALSE);
     $this->handles[] = $fp;
     $this->yuser[$fp] = $this->_user;
     return $fp;
 }
Example #15
0
function gw_send_sms($mobile_sender, $sms_sender, $sms_to, $sms_msg, $gp_code = "", $uid = "", $smslog_id = "", $flash = false)
{
    global $kannel_param;
    global $gateway_number;
    $ok = false;
    if ($gateway_number) {
        $sms_from = $gateway_number;
    } else {
        $sms_from = $mobile_sender;
    }
    if ($sms_sender) {
        $sms_msg = $sms_msg . $sms_sender;
    }
    // set failed first
    $p_status = 2;
    setsmsdeliverystatus($smslog_id, $uid, $p_status);
    $sms_type = 2;
    // text
    if ($flash) {
        $sms_type = 1;
        //flash
    }
    $URL = "/cgi-bin/sendsms?username="******"&password="******"&from=" . urlencode($sms_from) . "&to=" . urlencode($sms_to) . "&text=" . urlencode($sms_msg);
    $URL .= "&dlr-mask=31&dlr-url=" . urlencode($kannel_param['phpgwsms_web'] . "/plugin/gateway/kannel/dlr.php?type=%d&slid={$smslog_id}&uid={$uid}");
    $URL .= "&mclass={$sms_type}";
    $connection = fsockopen($kannel_param['bearerbox_host'], $kannel_param['sendsms_port'], &$error_number, &$error_description, 60);
    if ($connection) {
        socket_set_blocking($connection, false);
        fputs($connection, "GET {$URL} HTTP/1.0\r\n\r\n");
        while (!feof($connection)) {
            $myline = fgets($connection, 128);
            if ($myline == "Sent.") {
                $ok = true;
                // set pending
                $p_status = 0;
                setsmsdeliverystatus($smslog_id, $uid, $p_status);
            }
        }
    }
    fclose($connection);
    return $ok;
}
Example #16
0
 /**
  * Connect to the newsserver
  *
  * @param string $nntpserver The adress of the NNTP-server to connect to.
  * @param int $port (optional) the port-number to connect to, defaults to 119.
  * @param string $user (optional) The user name to authenticate with
  * @param string $pass (optional) The password
  * @param string $authmode (optional) The authentication mode
  * @return mixed True on success or Pear Error object on failure
  * @see Net_Nntp::authenticate()
  * @access public
  */
 function connect($nntpserver, $port = 119, $user = null, $pass = null, $authmode = PEAR_NNTP_AUTHORIGINAL)
 {
     $fp = @fsockopen($nntpserver, $port, $errno, $errstr, 15);
     if (!is_resource($fp)) {
         return $this->raiseError("Could not connect to NNTP-server {$nntpserver}");
     }
     socket_set_blocking($fp, true);
     if (!$fp) {
         return $this->raiseError('Not connected');
     }
     $response = fgets($fp, 128);
     if ($this->_debug) {
         print "<< {$response}\n";
     }
     $this->fp = $fp;
     $this->user = $user;
     $this->pass = $pass;
     $this->authmode = $authmode;
     return true;
 }
Example #17
0
	function event_socket_create($ESL_host, $ESL_port, $ESL_password) {
		$fp = fsockopen($ESL_host, $ESL_port, $errno, $errdesc) 
			or die("Connection to $ESL_host failed");
		socket_set_blocking($fp,false);

		if ($fp) {
			while (!feof($fp)) {
				$buffer = fgets($fp, 1024);
				usleep(100); //allow time for reponse
				if (trim($buffer) == "Content-Type: auth/request") {
					fputs($fp, "auth $ESL_password\n\n");
					break;
				}
			}
			return $fp;
		}
		else {
			return false;
		}           
	}
Example #18
0
 /**
  * Parse a file containing CSV formatted data.
  *
  * @access    public
  * @param    string
  * @param    boolean
  * @return    array
  */
 function parse_csv($docs_url, $p_NamedFields = true)
 {
     $url_info = parse_url($docs_url);
     $host = $url_info['host'];
     if (empty($url_info['port'])) {
         if ($url_info['scheme'] == 'https') {
             $port = 443;
         } else {
             $port = 80;
         }
     } else {
         $port = $url_info['port'];
     }
     $socket = fsockopen($host, $port, $errno, $errstr, 30);
     socket_set_blocking($socket, false);
     $query = $url_info['query'] ? "?" . $url_info['query'] : "";
     fputs($socket, "GET " . $url_info['path'] . $query . " HTTP/1.0\r\nHost: " . $host . "\r\n\r\n");
     $content = array();
     if ($p_NamedFields) {
         $this->fields = fgetcsv($socket, $this->max_row_size, $this->separator, $this->enclosure);
     }
     while (($row = fgetcsv($socket, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
         if ($row[0] != null) {
             // skip empty lines
             if ($p_NamedFields) {
                 $items = array();
                 // I prefer to fill the array with values of defined fields
                 foreach ($this->fields as $id => $field) {
                     if (isset($row[$id])) {
                         $items[$field] = $row[$id];
                     }
                 }
                 $content[] = $items;
             } else {
                 $content[] = $row;
             }
         }
     }
     fclose($socket);
     return $content;
 }
Example #19
0
 /**
  * Sends the request to the webserver but don't wait for the response.
  */
 static function touch($url)
 {
     $url = Patchwork::base($url, true);
     if (!preg_match("'^http(s?)://([^:/]*)((?::[0-9]+)?)(/.*)\$'", $url, $h)) {
         throw new Exception('Illegal URL');
     }
     $url = "GET {$h[4]} HTTP/1.0\r\n";
     $url .= "Host: {$h[2]}\r\n";
     $url .= "Connection: close\r\n\r\n";
     try {
         $h = patchwork_http_socket($h[2], substr($h[3], 1), $h[1], 5);
         socket_set_blocking($h, 0);
         do {
             $len = fwrite($h, $url);
             $url = substr($url, $len);
         } while (false !== $len && false !== $url);
         fclose($h);
     } catch (Exception $h) {
         user_error($h->getMessage());
     }
 }
Example #20
0
 protected function connectionLoop()
 {
     $socket = $this->getSocket();
     if (!$socket) {
         $this->socket = $socket = fsockopen($this->server, $this->port);
         $this->manager->handleConnect($this);
         socket_set_blocking($this->socket, false);
     }
     while ($this->isConnected() && !feof($socket)) {
         $raw = fgets($socket);
         if ($raw) {
             $this->handleRaw($raw);
         }
         $this->handleTick();
         if ($raw === false) {
             // no data, slow down so we don't burn cpu cycles
             usleep(10000);
         }
     }
     $this->disconnect();
 }
 function check_email($email)
 {
     $result = false;
     #-- email-Adresse in $user und $domain aufsplitten
     list($user, $domain) = explode('@', $email);
     #-- die MX-Server für $domain bestimmen
     getmxrr($domain, $mx_servers);
     $mx_servers[] = $domain;
     foreach ($mx_servers as $smtp_server) {
         #-- mit SMTP-Server verbinden
         if (!$result) {
             if ($socket = fsockopen($smtp_server, 25)) {
                 #-- warten auf SMTP ready
                 socket_set_blocking($socket, false);
                 $loop = 0;
                 while (!preg_match('/^220[ ]/', fgets($socket, 2048))) {
                     #-- Schleife, weil anfangs SMTP-Datemmüll kommen kann
                     if ($loop++ > 19999) {
                         fclose($socket);
                         break 2;
                     }
                 }
                 #-- Proto
                 socket_set_blocking($socket, true);
                 $this->socket_command($socket, "HELO www.erphesfurt.de\r\n");
                 if (!($result = preg_match('/^25/', $this->socket_command($socket, "VRFY {$user}\r\n")))) {
                     $this->socket_command($socket, "MAIL FROM:<*****@*****.**>\r\n");
                     $result = preg_match('/^25/', $this->socket_command($socket, "RCPT TO:<{$email}>\r\n"));
                 }
                 #-- SMTP-Verbindung beenden
                 fputs($socket, "QUIT\r\n");
                 fclose($socket);
             }
         }
         #if($socket)
     }
     #foreach($mx_servers)
     ##if(getmxrr)
     return $result;
 }
Example #22
0
function http_get($url)
{
    $parseUrl = parse_url($url);
    if (!isset($parseUrl['port'])) {
        $parseUrl['port'] = 80;
    }
    $path = $parseUrl['path'];
    if (isset($parseUrl['query'])) {
        $path .= '?' . $parseUrl['query'];
    }
    if (isset($parseUrl['fragment'])) {
        $path .= '#' . $parseUrl['fragment'];
    }
    $fp = fsockopen($parseUrl['host'], $parseUrl['port'], $errno, $errstr, 5);
    if (!$fp) {
        echo "Error: {$errstr} ({$errno})<br>\n";
    } else {
        fputs($fp, "GET " . $path . " HTTP/1.0\r\n\r\n");
        socket_set_blocking($fp, false);
    }
    return $fp;
}
Example #23
0
 function ftp_connect($server, $port = 21, $proxy_server = NULL, $proxy_port = 21)
 {
     $fc = array();
     #-- proxy or direct connection
     if ($proxy_server) {
         $f = fsockopen($proxy_server, $proxy_port, $errno, $errstr, 15);
         $fc["proxy"] = 1;
     } else {
         if (strpos($server, ":")) {
             $server = strtok($server, ":");
             $port = strtok(":");
         }
         $f = fsockopen($server, (int) $port, $errno, $errstr, 15);
     }
     #-- socket connection established
     if ($f) {
         #-- socket connection settings
         socket_set_blocking($f, 1);
         #-- mk connection data hash
         $fc["host"] = $server;
         $fc["port"] = $port;
         $fc["f"] = $f;
         $fc["d"] = false;
         $fc["dport"] = false;
         $fc["pasv"] = FTP_PASV;
         #-- read greeting
         ftp_send($fc, "", 1);
         if (!$fc["err"] == 220) {
             ftp_err("server rejected further communication (after successful TCP/IP connection)");
             return false;
         }
         #-- ret handle
         return $fc;
     } else {
         ftp_err("connecting to {$server}:{$port}{$add_err} failed [err{$errno}: \"{$errstr}\"]");
         return false;
     }
 }
 /**
  * Sends a packet via UDP to the list of name servers.
  *
  * This function sends a packet to a nameserver.  It is called by
  * send_udp if the sockets PHP extension is not compiled into PHP.
  *
  * @param string $packet    A packet object to send to the NS list
  * @param string $packet_data   The data in the packet as returned by
  *                              the Net_DNS_Packet::data() method
  * @return object Net_DNS_Packet Returns an answer packet object
  * @see Net_DNS_Resolver::send_tcp(), Net_DNS_Resolver::send(),
  *      Net_DNS_Resolver::send_udp(), Net_DNS_Resolver::send_udp_with_sock_lib()
  */
 function send_udp_no_sock_lib($packet, $packet_data)
 {
     $retrans = $this->retrans;
     $timeout = $retrans;
     /*
      * PHP doesn't have excellent socket support as of this writing.
      * This needs to be rewritten when PHP POSIX socket support is
      * complete.
      * Obviously, this code is MUCH different than the PERL implementation
      */
     $w = error_reporting(0);
     $ctr = 0;
     // Create a socket handle for each nameserver
     foreach ($this->nameservers as $nameserver) {
         if ($sock[$ctr++] = fsockopen("udp://{$nameserver}", $this->port)) {
             $peerhost[$ctr - 1] = $nameserver;
             $peerport[$ctr - 1] = $this->port;
             socket_set_blocking($sock, FALSE);
         } else {
             $ctr--;
         }
     }
     error_reporting($w);
     if ($ctr == 0) {
         $this->errorstring = 'no nameservers';
         return NULL;
     }
     for ($i = 0; $i < $this->retry; $i++, $retrans *= 2, $timeout = (int) ($retrans / (count($ns) + 1))) {
         if ($timeout < 1) {
             $timeout = 1;
         }
         foreach ($sock as $k => $s) {
             if ($this->debug) {
                 echo ';; send_udp(' . $peerhost[$k] . ':' . $peerport[$k] . '): sending ' . strlen($packet_data) . " bytes\n";
             }
             if (!fwrite($s, $packet_data)) {
                 if ($this->debug) {
                     echo ";; send error\n";
                 }
             }
             /*
              *  Here's where it get's really nasty.  We don't have a select()
              *  function here, so we have to poll for a response... UGH!
              */
             $timetoTO = time() + (double) microtime() + $timeout;
             /*
              * let's sleep for a few hundred microseconds to let the
              * data come in from the network...
              */
             usleep(500);
             $buf = '';
             while (!strlen($buf) && $timetoTO > time() + (double) microtime()) {
                 socket_set_blocking($s, FALSE);
                 if ($buf = fread($s, 512)) {
                     $this->answerfrom = $peerhost[$k];
                     $this->answersize = strlen($buf);
                     if ($this->debug) {
                         echo ';; answer from ' . $peerhost[$k] . ':' . $peerport[$k] . ': ' . strlen($buf) . " bytes\n";
                     }
                     $ans = new Net_DNS_Packet($this->debug);
                     if ($ans->parse($buf)) {
                         if ($ans->header->qr != '1') {
                             continue;
                         }
                         if ($ans->header->id != $packet->header->id) {
                             continue;
                         }
                         $this->errorstring = $ans->header->rcode;
                         $ans->answerfrom = $this->answerfrom;
                         $ans->answersize = $this->answersize;
                         return $ans;
                     }
                 }
                 // Sleep another 1/100th of a second... this sucks...
                 usleep(1000);
             }
             $this->errorstring = 'query timed out';
             return NULL;
         }
     }
 }
Example #25
0
 /**
  * Sets whether the socket connection should be blocking or
  * not. A read call to a non-blocking socket will return immediately
  * if there is no data available, whereas it will block until there
  * is data for blocking sockets.
  *
  * @param boolean $mode  True for blocking sockets, false for nonblocking.
  * @access public
  * @return mixed true on success or an error object otherwise
  */
 function setBlocking($mode)
 {
     if (!is_resource($this->fp)) {
         return $this->raiseError('not connected');
     }
     $this->blocking = $mode;
     socket_set_blocking($this->fp, $this->blocking);
     return true;
 }
Example #26
0
 /**
  * - $server ( Server IP or DNS )
  * - $port ( Server port default is "110" )
  * - $timeout ( Connection timeout for connect to server )
  * - $sock_timeout ( Socket timeout for all actions   (10 sec 500 msec) = (10,500))
  * 
  * If all right you get true, when not you get false and on $this->error = msg
  * 
  * @access public
  * @param string $server
  * @param string $port[optional] = 110
  * @param string $timeout[optional] = 20
  * @param string $sock_timeout[optional] = '10,500'
  * @return bool
  */
 function connect($server, $port = 110, $timeout = 20, $sock_timeout = '10,500')
 {
     if ($this->socket) {
         $this->error = 'POP3 connect() - Error: Connection also avalible!';
         $this->setGlobalErrorAndWriteLog();
         return false;
     }
     if (!trim($server)) {
         $this->error = 'POP3 connect() - Error: Please give a server address.';
         $this->setGlobalErrorAndWriteLog();
         return false;
     }
     if ($port < 1 && $port > 65535 || !trim($port)) {
         $this->error = 'POP3 connect() - Error: Port not set or out of range (1 - 65535)';
         $this->setGlobalErrorAndWriteLog();
         return false;
     }
     if ($timeout < 0 && $timeout > 25 || !trim($timeout)) {
         $this->error = 'POP3 connect() - Error: Connection Timeout not set or out of range (0 - 25)';
         $this->setGlobalErrorAndWriteLog();
         return false;
     }
     $sock_timeout = explode(',', $sock_timeout);
     if (!trim($sock_timeout[0]) || $sock_timeout[0] < 0 && $sock_timeout[0] > 25) {
         $this->error = 'POP3 connect() - Error: Socket Timeout not set or out of range (0 - 25)';
         $this->setGlobalErrorAndWriteLog();
         return false;
     }
     if (!$this->_checkstate('connect')) {
         return false;
     }
     $isSsl = strlen($server) > 6 && strtolower(substr($server, 0, 6)) == 'ssl://';
     if (function_exists('openssl_open') && ($isSsl || $port == 995)) {
         if (!$isSsl) {
             $server = 'ssl://' . $server;
         }
     } else {
         if ($isSsl) {
             $server = substr($server, 6);
         }
     }
     $errno = $errstr = null;
     CAdminPanel::Log('POP3 > Start connect to ' . $server . ':' . $port);
     $this->socket = @fsockopen($server, $port, $errno, $errstr, $timeout);
     if (!$this->socket) {
         $this->error = 'POP3 connect() - Error: Can\'t connect to Server. Error: ' . $errno . ' -- ' . $errstr;
         $this->setGlobalErrorAndWriteLog();
         return false;
     }
     // set socket timeout
     // it is valid for all other functions!
     socket_set_timeout($this->socket, $sock_timeout[0], $sock_timeout[1]);
     socket_set_blocking($this->socket, true);
     $response = $this->_getnextstring();
     if (substr($response, 0, 1) != '+') {
         $this->_cleanup();
         $this->error = 'POP3 connect() - Error: ' . $response;
         $this->setGlobalErrorAndWriteLog();
         return false;
     }
     // get the server banner for APOP
     $this->apop_banner = $this->_parse_banner($response);
     $this->state = 'AUTHORIZATION';
     return true;
 }
Example #27
0
 /**
  * Establishs the connection to the server. If no arguments passed, will use the defaults.
  * @return boolean|null True or false, depending on whether the connection succeeded.
  */
 public function connect()
 {
     // Open a connection.
     $this->socket = stream_socket_client($this->server . ':' . $this->port, $errno, $errstr);
     if (!$this->isConnected()) {
         throw new ConnectionException('Unable to connect to server via fsockopen with server: "' . $this->server . '" and port: "' . $this->port . '" (' . $errno . ': ' . $errstr . ')');
     }
     socket_set_blocking($this->socket, 0);
     if (!empty($this->password)) {
         $this->sendData('PASS ' . $this->password);
     }
     $this->sendData('USER ' . $this->nick . ' Layne-Obserdia.de ' . $this->nick . ' :' . $this->name);
     $this->sendData('NICK ' . $this->nick);
     $this->log('Connection to server {server}:{port} set up with nick {nick}; ready to use.', array('server' => $this->server, 'port' => $this->port, 'nick' => $this->nick), LogLevels::INFO);
     // And fire the onConnect event.
     $this->bot->getEventManager()->getEvent('Connect')->trigger(new ConnectEvent());
 }
Example #28
0
 protected function _authenticate($command, $xml)
 {
     //response switch
     switch ($command) {
         case self::AUTH_TYPE_STREAM:
             // Connection initialized (or after authentication). Not much to do here...
             if (isset($xml['stream:stream'][0]['#']['stream:features'])) {
                 // we already got all info we need
                 $features = $xml['stream:stream'][0]['#'];
             } else {
                 $features = $this->wait();
             }
             $second_time = isset($this->_streamId);
             $this->_streamId = $xml['stream:stream'][0]['@']['id'];
             if ($second_time) {
                 // If we are here for the second time after TLS, we need to continue logging in
                 //if there are no features
                 if (!sizeof($features)) {
                     //throw exception
                     Eden_Jabber_Error::i(Eden_Jabber_Error::NO_FEATURES)->trigger();
                 }
                 return $this->_response($features);
             }
             //we are on the first step
             $this->_negotiation = self::AUTH_STARTED;
             // go on with authentication?
             if (isset($features['stream:features'][0]['#']['mechanisms']) || $this->_negotiation == self::AUTH_PROCEED) {
                 return $this->_response($features);
             }
             break;
         case self::AUTH_TYPE_FEATURES:
             // Resource binding after successful authentication
             if ($this->_negotiation == self::AUTH_SUCCESS) {
                 // session required?
                 $this->_session = isset($xml['stream:features'][0]['#']['session']);
                 $this->send("<iq type='set' id='bind_1'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'>" . "<resource>" . htmlspecialchars($this->_resource) . '</resource></bind></iq>');
                 return $this->_response($this->wait());
             }
             // Let's use TLS if SSL is not enabled and we can actually use it
             if (!$this->_ssl && $this->_tls && $this->_canUseSSL() && isset($xml['stream:features'][0]['#']['starttls'])) {
                 $this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n");
                 return $this->_response($this->wait());
             }
             // Does the server support SASL authentication?
             // I hope so, because we do (and no other method).
             if (isset($xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns']) && $xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns'] == 'urn:ietf:params:xml:ns:xmpp-sasl') {
                 // Now decide on method
                 $methods = array();
                 foreach ($xml['stream:features'][0]['#']['mechanisms'][0]['#']['mechanism'] as $value) {
                     $methods[] = $value['#'];
                 }
                 // we prefer DIGEST-MD5
                 // we don't want to use plain authentication (neither does the server usually) if no encryption is in place
                 // http://www.xmpp.org/extensions/attic/jep-0078-1.7.html
                 // The plaintext mechanism SHOULD NOT be used unless the underlying stream is encrypted (using SSL or TLS)
                 // and the client has verified that the server certificate is signed by a trusted certificate authority.
                 if (in_array('DIGEST-MD5', $methods)) {
                     $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>");
                 } else {
                     if (in_array('PLAIN', $methods) && ($this->_ssl || $this->_negotiation == self::AUTH_PROCEED)) {
                         $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode(chr(0) . $this->_user . '@' . $this->_domain . chr(0) . $this->_pass) . '</auth>');
                     } else {
                         if (in_array('ANONYMOUS', $methods)) {
                             $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
                         } else {
                             // not good...
                             //disconnect
                             $this->disconnect();
                             //throw an exception
                             Eden_Jabber_Error::i(Eden_Jabber_Error::NO_AUTH_METHOD)->trigger();
                         }
                     }
                 }
                 return $this->_response($this->wait());
             }
             // ok, this is it. bye.
             //disconnect
             $this->disconnect();
             //throw an exception
             Eden_Jabber_Error::i(Eden_Jabber_Error::NO_SASL)->trigger();
             break;
         case self::AUTH_TYPE_CHALLENGE:
             // continue with authentication...a challenge literally -_-
             $this->_negotiation = self::AUTH_CHALLENGE;
             $decoded = base64_decode($xml['challenge'][0]['#']);
             $decoded = $this->_parseData($decoded);
             if (!isset($decoded['digest-uri'])) {
                 $decoded['digest-uri'] = 'xmpp/' . $this->_host;
             }
             // better generate a cnonce, maybe it's needed
             $decoded['cnonce'] = base64_encode(md5(uniqid(mt_rand(), true)));
             // second challenge?
             if (isset($decoded['rspauth'])) {
                 $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
             } else {
                 // Make sure we only use 'auth' for qop (relevant for $this->_encryptPass())
                 // If the <response> is choking up on the changed parameter we may need to adjust _encryptPass() directly
                 if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false) {
                     $decoded['qop'] = 'auth';
                 }
                 $response = array('username' => $this->_user, 'response' => $this->_encryptPass(array_merge($decoded, array('nc' => '00000001'))), 'charset' => 'utf-8', 'nc' => '00000001', 'qop' => 'auth');
                 // only auth being supported
                 foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key) {
                     if (isset($decoded[$key])) {
                         $response[$key] = $decoded[$key];
                     }
                 }
                 $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" . base64_encode($this->_implodeData($response)) . '</response>');
             }
             return $this->_response($this->wait());
         case self::AUTH_TYPE_FAILURE:
             $this->_negotiation = self::AUTH_FAILIURE;
             $this->trigger('failiure');
             //disconnect
             $this->disconnect();
             //throw an exception
             Eden_Jabber_Error::i(Eden_Jabber_Error::SERVER_FAILED)->trigger();
         case self::AUTH_TYPE_PROCEED:
             // continue switching to TLS
             $meta = stream_get_meta_data($this->_connection);
             socket_set_blocking($this->_connection, 1);
             if (!stream_socket_enable_crypto($this->_connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                 //'Error: TLS mode change failed.'
                 Eden_Jabber_Error::i(Eden_Jabber_Error::SERVER_FAILED)->trigger();
             }
             socket_set_blocking($this->_connection, $meta['blocked']);
             $this->_negotiation = self::AUTH_PROCEED;
             // new stream
             $this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
             $this->send("<stream:stream to='" . $this->_host . "' xmlns='jabber:client' " . "xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
             return $this->_response($this->wait());
         case self::AUTH_TYPE_SUCCESS:
             // Yay, authentication successful.
             $this->send("<stream:stream to='" . $this->_host . "' xmlns='jabber:client' " . "xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
             $this->_negotiation = self::AUTH_SUCCESS;
             // we have to wait for another response
             return $this->_response($this->wait());
     }
     return $this;
 }
Example #29
0
	function connect($server = '', $port = 995)
	{
		$port = ($port) ? $port : 995;
		if (!empty($this->MAILSERVER))
		{
			$server = $this->MAILSERVER;
		}
		
		if (empty($server))
		{
			$this->ERROR = 'POP3 connect: No server specified';
			unset($this->FP);
			
			return false;
		}
		
		$fp = @fsockopen($server, $port, $errno, $errstr);
		if (!$fp)
		{
			$this->ERROR = 'POP3 connect: Error [' . $errno . '] [' . $errstr . ']';
			unset($this->FP);
			
			return false;
		}
		
		socket_set_blocking($fp, -1);
		$this->update_timer();
		
		$reply = fgets($fp, $this->BUFFER);
		$reply = $this->strip_clf($reply);
		if ($this->DEBUG)
		{
			error_log("POP3 SEND [connect: $server] GOT [$reply]", 0);
		}
		
		if (!$this->is_ok($reply))
		{
			$this->ERROR = 'POP3 connect: Error [' . $reply . ']';
			unset($this->FP);
			
			return false;
		}
		
		$this->FP = $fp;
		$this->BANNER = $this->parse_banner($reply);
		return true;
	}
Example #30
0
 public function Connect()
 {
     if ($this->connected) {
         return true;
     }
     $requestScheme = $this->scheme;
     $requestServer = $this->server;
     $requestPort = $this->port;
     if ($this->proxyUsed) {
         $requestScheme = $this->proxySchemes;
         $requestServer = $this->proxyServer;
         $requestPort = $this->proxyPort;
     }
     switch ($requestScheme) {
         case 'https':
             if (!function_exists("openssl_verify")) {
                 $this->arError[] = array("EC0", "OpenSSL PHP extention required");
                 $this->connected = false;
                 return false;
             }
             $requestScheme = 'ssl://';
             $requestPort = $requestPort === null ? 443 : $requestPort;
             break;
         case 'http':
             $requestScheme = '';
             $requestPort = $requestPort === null ? 80 : $requestPort;
             break;
         default:
             $this->arError[] = array("EC1", "Invalid protocol");
             $this->connected = false;
             return false;
     }
     $this->fp = @fsockopen($requestScheme . $requestServer, $requestPort, $errno, $errstr, $this->socketTimeout);
     if (!$this->fp) {
         $this->arError[] = array($errno, $errstr);
         $this->connected = false;
         return false;
     } else {
         socket_set_blocking($this->fp, 1);
         $this->connected = true;
         return true;
     }
 }