Ejemplo n.º 1
0
void ARTSPConnection::onConnect(const sp<AMessage> &msg) {
    ++mConnectionID;

    if (mState != DISCONNECTED) {
        if (mUIDValid) {
            HTTPBase::UnRegisterSocketUserTag(mSocket);
        }
        close(mSocket);
        mSocket = -1;

        flushPendingRequests();
    }

    mState = CONNECTING;

    AString url;
    CHECK(msg->findString("url", &url));

    sp<AMessage> reply;
    CHECK(msg->findMessage("reply", &reply));

    AString host, path;
    unsigned port;
    if (!ParseURL(url.c_str(), &host, &port, &path, &mUser, &mPass)
            || (mUser.size() > 0 && mPass.size() == 0)) {
        // If we have a user name but no password we have to give up
        // right here, since we currently have no way of asking the user
        // for this information.

        LOGE("Malformed rtsp url %s", url.c_str());

        reply->setInt32("result", ERROR_MALFORMED);
        reply->post();

        mState = DISCONNECTED;
        return;
    }

    if (mUser.size() > 0) {
        LOGV("user = '******', pass = '******'", mUser.c_str(), mPass.c_str());
    }

    struct hostent *ent = gethostbyname(host.c_str());
    if (ent == NULL) {
        LOGE("Unknown host %s", host.c_str());

        reply->setInt32("result", -ENOENT);
        reply->post();

        mState = DISCONNECTED;
        return;
    }

    mSocket = socket(AF_INET, SOCK_STREAM, 0);

    if (mUIDValid) {
        HTTPBase::RegisterSocketUserTag(mSocket, mUID,
                                        (uint32_t)*(uint32_t*) "RTSP");
    }

    MakeSocketBlocking(mSocket, false);

    union {
        struct sockaddr_in remote;
        struct sockaddr remote_generic;
    };
    memset(remote.sin_zero, 0, sizeof(remote.sin_zero));
    remote.sin_family = AF_INET;
    remote.sin_addr.s_addr = *(in_addr_t *)ent->h_addr;
    remote.sin_port = htons(port);

    int err = ::connect(
            mSocket, &remote_generic, sizeof(remote));

    reply->setInt32("server-ip", ntohl(remote.sin_addr.s_addr));

    if (err < 0) {
        if (errno == EINPROGRESS) {
            sp<AMessage> msg = new AMessage(kWhatCompleteConnection, id());
            msg->setMessage("reply", reply);
            msg->setInt32("connection-id", mConnectionID);
            msg->post();
            return;
        }

        reply->setInt32("result", -errno);
        mState = DISCONNECTED;

        if (mUIDValid) {
            HTTPBase::UnRegisterSocketUserTag(mSocket);
        }
        close(mSocket);
        mSocket = -1;
    } else {
        reply->setInt32("result", OK);
        mState = CONNECTED;
        mNextCSeq = 1;

        postReceiveReponseEvent();
    }

    reply->post();
}
Ejemplo n.º 2
0
BOOL CHttpSender::_Send(CString sURL, CString sFileName, AssyncNotification* an)
{ 
  BOOL bStatus = FALSE;
	TCHAR* hdrs = _T("Content-Type: application/x-www-form-urlencoded");
	LPCTSTR accept[2]={_T("*/*"), NULL};
  int uFileSize = 0;
  BYTE* uchFileData = NULL;
  HINTERNET hSession = NULL;
  HINTERNET hConnect = NULL;
  HINTERNET hRequest = NULL;
  TCHAR szProtocol[512];
  TCHAR szServer[512];
  TCHAR szURI[1024];
  DWORD dwPort;
  struct _stat st;
  int res = -1;
  FILE* f = NULL;
  BOOL bResult = FALSE;
  char* chPOSTRequest = NULL;
  CStringA sMD5Hash;
  CStringA sPOSTRequest;
  char* szPrefix="crashrpt=\"";
  char* szSuffix="\"";
  CString sErrorMsg;
  CHAR szResponce[1024];
  DWORD dwBufSize = 1024;
  MD5 md5;
  MD5_CTX md5_ctx;
  unsigned char md5_hash[16];
  int i=0;  
  CString msg;

  an->SetProgress(_T("Start sending error report over HTTP"), 0, false);

  an->SetProgress(_T("Creating Internet connection"), 3, false);

  if(an->IsCancelled()){ goto exit; }

  // Create Internet session
	hSession = InternetOpen(_T("CrashRpt"),
		INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(hSession==NULL)
  {
    an->SetProgress(_T("Error creating Internet conection"), 0);
	  goto exit; // Couldn't create internet session
  }
  
  ParseURL(sURL, szProtocol, 512, szServer, 512, dwPort, szURI, 1024);

  an->SetProgress(_T("Connecting to server"), 5, false);

  // Connect to server
	hConnect = InternetConnect(
    hSession, 
    szServer,
		INTERNET_DEFAULT_HTTP_PORT, 
    NULL, 
    NULL, 
    INTERNET_SERVICE_HTTP, 
    0, 
    1);
	
	if(hConnect==NULL)
  {
    an->SetProgress(_T("Error connecting to server"), 0);
	  goto exit; // Couldn't connect
  }
	
  if(an->IsCancelled()){ goto exit; }

  an->SetProgress(_T("Preparing HTTP request data"), 7, false);

  // Load file data into memory
  res = _tstat(sFileName.GetBuffer(0), &st);
  if(res!=0)
  {
    an->SetProgress(_T("Error opening file"), 0);
    goto exit; // File not found
  }
  
  uFileSize = st.st_size;
  uchFileData = new BYTE[uFileSize];
#if _MSC_VER<1400
  f = _tfopen(sFileName.GetBuffer(0), _T("rb"));
#else
  _tfopen_s(&f, sFileName.GetBuffer(0), _T("rb"));
#endif
  if(!f || fread(uchFileData, uFileSize, 1, f)!=1)
  {
    an->SetProgress(_T("Error reading file"), 0);
    goto exit;  
  }
  fclose(f);

  md5.MD5Init(&md5_ctx);
  md5.MD5Update(&md5_ctx, uchFileData, uFileSize);
  md5.MD5Final(md5_hash, &md5_ctx);
  
  sMD5Hash = _T("&md5=");
  for(i=0; i<16; i++)
  {
    CString number;
    number.Format(_T("%02X"), md5_hash[i]);
    sMD5Hash += number;
  }
  
  sPOSTRequest = base64_encode(uchFileData, uFileSize).c_str();
  sPOSTRequest = szPrefix + sPOSTRequest + szSuffix;  
  sPOSTRequest.Replace("+", "%2B");
  sPOSTRequest.Replace("/", "%2F");  

  sPOSTRequest += sMD5Hash;
  
  an->SetProgress(_T("Opening HTTP request"), 10);

  if(an->IsCancelled()){ goto exit; }

  // Send POST request
  hRequest = HttpOpenRequest(hConnect, _T("POST"),
		                         szURI, NULL, NULL, accept, 0, 1);	
	if(hRequest==NULL)
  {
    an->SetProgress(_T("Error opening HTTP request"), 0);
	  goto exit; // Coudn't open request	
  }

  if(an->IsCancelled()){ goto exit; }

  an->SetProgress(_T("Sending HTTP request"), 50);
  bResult = HttpSendRequest(hRequest, hdrs, (int)_tcslen(hdrs), 
    (void*)sPOSTRequest.GetBuffer(), (DWORD)sPOSTRequest.GetLength());
    
  if(bResult == FALSE)
  {
    an->SetProgress(_T("Error sending HTTP request"), 100, false);
		goto exit; // Couldn't send request
  }
	  
  an->SetProgress(_T("Sending error report over HTTP completed OK"), 10, true);
    
  HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE, szResponce, &dwBufSize, NULL); 
  if(atoi(szResponce)!=200)
  {
    CString msg;
    msg.Format(_T("Error! The server returned code %s"), CString(szResponce));
    an->SetProgress(msg, 0);
    goto exit;
  }    

  InternetReadFile(hRequest, szResponce, 1024, &dwBufSize);
  szResponce[dwBufSize] = 0;
  msg = CStringA(szResponce, dwBufSize);
  msg = _T("Server returned:")+msg;
  an->SetProgress(msg, 0);
    
  if(atoi(szResponce)!=200)
  {
    an->SetProgress(_T("Failed"), 100, false);
    goto exit;
  }

  an->SetProgress(_T("Sent OK"), 100, false);
  bStatus = TRUE;

exit:

  // Clean up
	if(hRequest) 
    InternetCloseHandle(hRequest);

	if(hConnect) 
    InternetCloseHandle(hConnect);

	if(hSession) 
    InternetCloseHandle(hSession);

  if(chPOSTRequest)
    delete [] chPOSTRequest;
    
  if(uchFileData)
    delete [] uchFileData;

  if(f)
    fclose(f);

  return bStatus;
}
Ejemplo n.º 3
0
int main(int argc, char **argv)
{
    PRHostEnt hostentry;
    char buf[PR_NETDB_BUF_SIZE];
    PRNetAddr addr;
    PRFileDesc *socket = NULL, *file = NULL;
    PRIntn cmdSize;
    char host[HOST_SIZE];
    char port[PORT_SIZE];
    char path[PATH_SIZE];
    char line[LINE_SIZE];
    int exitStatus = 0;
    PRBool endOfHeader = PR_FALSE;
    char *url;
    char *fileName = NULL;
    PRUint32 fileSize;

    if (argc != 2 && argc != 4) {
	PrintUsage();
	exit(1);
    }

    if (argc == 2) {
	/*
	 * case 1: httpget url
	 */
	url = argv[1];
    } else {
	if (strcmp(argv[1], "-o") == 0) {
	    /*
	     * case 2: httpget -o outputfile url
	     */
	    fileName = argv[2];
	    url = argv[3];
        } else {
	    /*
	     * case 3: httpget url -o outputfile
	     */
	    url = argv[1];
	    if (strcmp(argv[2], "-o") != 0) {
		PrintUsage();
		exit(1);
            }
	    fileName = argv[3];
	}
    }

    if (ParseURL(url, host, sizeof(host), port, sizeof(port),
	    path, sizeof(path)) == PR_FAILURE) {
	exit(1);
    }

    if (PR_GetHostByName(host, buf, sizeof(buf), &hostentry)
	    == PR_FAILURE) {
        fprintf(stderr, "httpget: unknown host name: %s\n", host);
	exit(1);
    }

    addr.inet.family = PR_AF_INET;
    addr.inet.port = PR_htons((short) atoi(port));
    addr.inet.ip = *((PRUint32 *) hostentry.h_addr_list[0]);

    socket = PR_NewTCPSocket();
    if (socket == NULL) {
	fprintf(stderr, "httpget: cannot create new tcp socket\n");
	exit(1);
    }

    if (PR_Connect(socket, &addr, PR_INTERVAL_NO_TIMEOUT) == PR_FAILURE) {
	fprintf(stderr, "httpget: cannot connect to http server\n");
	exitStatus = 1;
	goto done;
    }

    if (fileName == NULL) {
	file = PR_STDOUT;
    } else {
        file = PR_Open(fileName, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE,
		00777);
        if (file == NULL) {
	    fprintf(stderr, "httpget: cannot open file %s: (%d, %d)\n",
		    fileName, PR_GetError(), PR_GetOSError());
	    exitStatus = 1;
	    goto done;
	}
    }

    cmdSize = PR_snprintf(buf, sizeof(buf), "GET %s HTTP/1.0\r\n\r\n", path);
    PR_ASSERT(cmdSize == (PRIntn) strlen("GET  HTTP/1.0\r\n\r\n")
            + (PRIntn) strlen(path));
    if (PR_Write(socket, buf, cmdSize) != cmdSize) {
	fprintf(stderr, "httpget: cannot write to http server\n");
	exitStatus = 1;
	goto done;
    }

    if (ReadLine(socket, line, sizeof(line)) <= 0) {
	fprintf(stderr, "httpget: cannot read line from http server\n");
	exitStatus = 1;
	goto done;
    }

    /* HTTP response: 200 == OK */
    if (strstr(line, "200") == NULL) {
	fprintf(stderr, "httpget: %s\n", line);
	exitStatus = 1;
	goto done;
    }

    while (ReadLine(socket, line, sizeof(line)) > 0) {
	if (line[0] == '\n') {
	    endOfHeader = PR_TRUE;
	    break;
	}
	if (strncmp(line, "Content-Length", 14) == 0
		|| strncmp(line, "Content-length", 14) == 0) {
	    char *p = line + 14;

	    while (*p == ' ' || *p == '\t') {
		p++;
	    }
	    if (*p != ':') {
		continue;
            }
	    p++;
	    while (*p == ' ' || *p == '\t') {
		p++;
	    }
	    fileSize = 0;
	    while ('0' <= *p && *p <= '9') {
		fileSize = 10 * fileSize + (*p - '0');
		p++;
            }
	}
    }
    if (endOfHeader == PR_FALSE) {
	fprintf(stderr, "httpget: cannot read line from http server\n");
	exitStatus = 1;
	goto done;
    }

    if (fileName == NULL || fileSize == 0) {
        FetchFile(socket, file);
    } else {
	FastFetchFile(socket, file, fileSize);
    }

done:
    if (socket) PR_Close(socket);
    if (file) PR_Close(file);
    PR_Cleanup();
    return exitStatus;
}