Exemple #1
0
/*
=====================
 转发教师端数据到所有学生端
=====================
*/
bool CHandleMessage::postTeacherToAllStudent (Buf* p, enum CommandType iCommandType)
{
#if 0
    cout << "postTeacherToAllStudent ------------------------ " <<endl;
    if (p == NULL)
        return false;

    int iLen = ((MSG_HEAD*)p->ptr())->cLen;
    int iHeadLen = sizeof (MSG_HEAD);
    Buf* pbuf = NULL;

    CRoom* pc = ROOMMANAGER->get_room_by_fd (p->getfd());
    if (pc != NULL) {

        int i = 0;
        CRoom::STUDENTMAP::iterator it;
        for (it = pc->m_student_map.begin(); \
             it != pc->m_student_map.end (); ++it)
        {
            i++;
            pbuf = SINGLE->bufpool.malloc ();
            if (pbuf != NULL) {
                MSG_HEAD* head = (MSG_HEAD*)pbuf->ptr();
                head->cLen = iLen;
                head->cType = iCommandType;
                if (iLen > iHeadLen) {
                    memcpy (head->cData(), (char*)p->ptr() + iHeadLen, iLen - iHeadLen);
                }
                pbuf->setsize (head->cLen);
                pbuf->setfd (it->first);
                SINGLE->sendqueue.enqueue (pbuf);
            }
            else {
                cout << "Error: out of memory" << endl;
                p->reset();
                pbuf->reset();
                SINGLE->bufpool.free(p);
                SINGLE->bufpool.free(pbuf);
                return false;
            }
        }
        if ( 0 == i ) {
            printf("send to %d students!\n", i);
        }
    }
    else {
        cout << __FILE__ << ":" <<__FUNCTION__<< ":" << __LINE__<<"Error: not found 'teacher_fd' in Room" << endl;
        //p->reset();
        SINGLE->bufpool.free(p);
        return false;
    }

    p->reset();
    SINGLE->bufpool.free(p);
#endif
    return true;
}
Exemple #2
0
//
// Works like _getenv(), but uses win32 functions instead.
//
void GetEnv(LPTSTR lpszEnvVar, Buf &buf) {

    DWORD dwLen = 0;

    if ( lpszEnvVar ) {
        dwLen = GetEnvironmentVariable(lpszEnvVar, NULL, 0);
    }

    if ( dwLen == 0 )
        buf.Clear();
    else {
        buf.AllocExact(dwLen+1);
        GetEnvironmentVariable(lpszEnvVar, buf.Get(), dwLen);
        buf.SetLength();
    }
}
Exemple #3
0
bool
epClass::sendtoAllStudent(Buf* pBuf) {
        EPSTUDENT_MAP::iterator it = studentMap_.begin();
        EPSTUDENT_MAP::const_iterator cie = studentMap_.end();
        Buf* p = NULL;
        for (; cie!=it; ++it) {
                if (pBuf->getfd() == it->first) { // not send to self.
                        continue;
                }
                p = pBuf;
                p->setfd(it->first);
                SINGLE->sendqueue.enqueue(p);
        }

        SINGLE->bufpool.free(pBuf);
        return true;
}
        int init_trace_key(Buf & buf, CryptoContext * ctx, const char * filename, mode_t mode, unsigned char * trace_key)
        {
            unsigned char derivator[DERIVATOR_LENGTH];
            get_derivator(filename, derivator, DERIVATOR_LENGTH);
            if (-1 == compute_hmac(trace_key, ctx->crypto_key, derivator)) {
                return -1;
            }

            return buf.open(filename, mode);
        }
Exemple #5
0
bool Signature::verify(Buf &_sig) {
  Pcpstream *p = ps_new_inbuffer(_sig.get_buffer());

  /* 
     we need to exclude current public key from free'ing
     because it's used as a hash in ed.c:276.
   */
  P.is_stored(true);

  pcp_pubkey_t *pub = pcp_ed_verify_buffered(PTX->ptx, p, P.K);

  ps_close(p);

  if(pub != NULL) {
    Signedby = new PubKey(PTX, pub);
    return true;
  }
  else {
    throw exception(PTX);
  }
}
Exemple #6
0
int SendTask::work() {
    while(true){
        Buf* p = NULL;
        if (0 != SINGLE->sendqueue.dequeue(p, 3)) {
            continue;
        }

        int fd = p->getfd();

        if (0 == fd) {
            printf(" fd = 0 !\n");
            continue;
        }

#if 0
        MSG_HEAD* pp = (MSG_HEAD*)p->ptr();
        if ( pp->cType > 9999 ) {
            struct sGetAllStudentInfo* xxx = (struct sGetAllStudentInfo*)pp->cData();
            printf("id %d pic %s  --  len:=%d\n", xxx->iStudentId, xxx->sPicName, pp->cLen);

        }

        unsigned int len = 0;
        int cnt;
        while (len < p->size()) {
            cnt = send(fd, (char *)p->ptr() + len, p->size() - len, 0);
            if (cnt == -1) {
                cout << "send erroooooooooooooooooooooor" << endl;
                break;
            }
            len += cnt;
        }

        printf ("ERRNO: %d, message:%s len = %d, p->size() = %ld\n", errno, strerror (errno), len ,p->size());
#else
        int bytes_left = p->size ();
        int written_bytes;
        char* ptr = (char*) p->ptr();
        while (bytes_left > 0)
        {
            written_bytes = send (fd, ptr, bytes_left, 0);
            if (written_bytes <= 0) {
                if (errno == EINTR) {
                    if (written_bytes < 0) written_bytes = 0;
                    continue;
                }
                else if (errno == EAGAIN) {
                    if (written_bytes < 0) written_bytes = 0;
                    sleep (1);
                    continue;
                }
                else
                    break;
            }
            bytes_left -= written_bytes;
            ptr += written_bytes;
        }
#endif
        printf("Send data...finished. packetLength=%ld, from FD=[%d]\n", p->size(), fd);

        p->reset();
        SINGLE->bufpool.free(p);
    }
    return 0;
}
 void flush(void) {
   _buf.flush();
 }
Exemple #8
0
void getContentType (COMMON_DATA & CommonData, Buf & sDestBuffer, LPTSTR foundType, LPTSTR defaultType, LPTSTR sFileName)
{
    // Toby Korn ([email protected])
    // SetFileType examines the file name sFileName for known file extensions and sets
    // the content type line appropriately.  This is returned in sDestBuffer.
    // sDestBuffer must have it's own memory (I don't alloc any here).

    FUNCTION_ENTRY();
#define CONTENT_TYPE_LENGTH 80
    _TCHAR        sType [CONTENT_TYPE_LENGTH];
    _TCHAR        sExt [_MAX_PATH];
    LONG          lResult;
    HKEY          key = NULL;
    unsigned long lTypeSize;
    unsigned long lStringType = REG_SZ;
    LPTSTR        tmpStr;
    Buf           tempstring;
    unsigned      ix;
    Buf           shortNameBuf;

    lResult = ~ERROR_SUCCESS;

    // Find the last '.' in the filename
    tmpStr = _tcsrchr( sFileName, __T('.'));
    if ( tmpStr ) {
        // Found the extension type.
        _tcscpy(sExt, tmpStr);
        lResult = RegOpenKeyEx(HKEY_CLASSES_ROOT, (LPCTSTR) sExt, 0, KEY_READ, &key);
        if ( lResult == ERROR_SUCCESS ) {
            lTypeSize = CONTENT_TYPE_LENGTH;
            lResult = RegQueryValueEx(key, __T("Content Type"), NULL, &lStringType, (BYTE *)sType,
                                      &lTypeSize);
            RegCloseKey (key);
            tmpStr = sType;
        }
    }
    // keep a couple of hard coded ones in case the registry is missing something.
    if ( lResult != ERROR_SUCCESS ) {
        for ( ix = 0; ; ix++ ) {
            if ( !defaultContentTypes[ix].extension ) {
                if ( defaultType && *defaultType )
                    tmpStr = defaultType;
                else
                    tmpStr = __T("application/octet-stream");

                break;
            }
            if ( _tcsicmp(sExt, defaultContentTypes[ix].extension) == 0 ) {
                tmpStr = defaultContentTypes[ix].contentType;
                break;
            }
        }
    }

    fixupFileName( CommonData, sFileName, shortNameBuf, 7, TRUE );
    sDestBuffer    = __T("Content-Type: ");
    sDestBuffer.Add( tmpStr );
    sDestBuffer.Add( __T(";\r\n name=\"") );
    sDestBuffer.Add( shortNameBuf );
    sDestBuffer.Add( __T("\"\r\n") );

    if ( foundType )
        _tcscpy( foundType, tmpStr );

    FUNCTION_EXIT();
}
Exemple #9
0
BOOL DoCgiWork(int & argc, LPTSTR*  &argv, Buf &lpszMessage,
                    Buf & lpszCgiSuccessUrl, Buf &lpszCgiFailureUrl,
                    Buf & lpszFirstReceivedData, Buf &lpszOtherHeader)
{
    Buf lpszMethod;
    Buf lpszPost;
    Buf lpszParamCgi;
    Buf lpszQueryString;
    Buf lpszPathTranslated;
    Buf lpszCmdBlat;

    lpszMessage.Clear();
    lpszFirstReceivedData.Clear();
    lpszOtherHeader.Clear();

    GetEnv(__T("REQUEST_METHOD"), lpszMethod);
    lpszPost=__T("");
    if ( lstrcmpi(lpszMethod.Get(),__T("POST")) == 0)
        ReadPostData(lpszPost);

    GetEnv(__T("QUERY_STRING"), lpszQueryString);
//    lpszParamCgi.AllocExact(lpszQueryString.Length()+lpszPost.Length()+10);

    lpszParamCgi.Add( lpszQueryString );
    if (lpszQueryString.Length() && lpszPost.Length())
        lpszParamCgi.Add( __T('&') );

    lpszParamCgi.Add( lpszPost );
    GetEnv(__T("PATH_TRANSLATED"), lpszPathTranslated);

    BuildMessageAndCmdLine(lpszParamCgi,lpszPathTranslated.Get(),lpszCmdBlat,lpszMessage);

    SearchVar(lpszParamCgi, __T("BLAT_SUCCESS"), TRUE, lpszCgiSuccessUrl);
    SearchVar(lpszParamCgi, __T("BLAT_FAILURE"), TRUE, lpszCgiFailureUrl);

    // now replace %__% by var

    DWORD dwPos     = 0;
    DWORD dwLineLen = (DWORD)lpszCmdBlat.Length();

    while ( dwPos < dwLineLen ) {
        if ( *(lpszCmdBlat.Get()+dwPos) == __T('%') ) {
            Buf   lpVarNameForSearch;
            Buf   lpContentVar;
            DWORD dwEnd;

            dwEnd = (SearchNextPercent(lpszCmdBlat.Get()+dwPos+1));
            if ( *(lpszCmdBlat.Get()+dwPos+1+dwEnd) == __T('\0') ) {
                lpContentVar.Free();
                break;
            }

            lpVarNameForSearch.Alloc(dwEnd+0x10);
            lpVarNameForSearch.Clear();
            memcpy(lpVarNameForSearch.Get(),lpszCmdBlat.Get()+dwPos+1,dwEnd*sizeof(_TCHAR));
            lpVarNameForSearch.SetLength(dwEnd);
            *lpVarNameForSearch.GetTail() = __T('\0');

            SearchVar(lpszParamCgi, lpVarNameForSearch.Get(), TRUE, lpContentVar);
            if ( lpContentVar.Length() ) {
                DWORD dwLenContentVar;

                dwLenContentVar = (DWORD)lpContentVar.Length();
                lpszCmdBlat.Alloc(dwLineLen+dwLenContentVar+0x10);
                memmove(lpszCmdBlat.Get()+dwPos+dwLenContentVar,lpszCmdBlat.Get()+dwPos+dwEnd+2,(dwLineLen-(dwPos+dwEnd+1))*sizeof(_TCHAR));
                memcpy(lpszCmdBlat.Get()+dwPos,lpContentVar.Get(),dwLenContentVar*sizeof(_TCHAR));
                lpszCmdBlat.SetLength();
                dwLineLen = (DWORD)lpszCmdBlat.Length();

                dwPos += dwLenContentVar;
            } else
                dwPos += dwEnd + 1;

            lpVarNameForSearch.Free();
            lpContentVar.Free();
        } else
            dwPos++;
    }

    ReadCommandLine(lpszCmdBlat.Get(),argc,argv);
    lpszCmdBlat.Clear();
    lpszParamCgi.Clear();

    //LPTSTR lpszRemoteHost=GetEnv(__T("REMOTE_HOST"));
    Buf    lpszRemoteAddr;       GetEnv(__T("REMOTE_ADDR"),          lpszRemoteAddr);
    Buf    lpszServerName;       GetEnv(__T("SERVER_NAME"),          lpszServerName);
    Buf    lpszHttpVia;          GetEnv(__T("HTTP_VIA"),             lpszHttpVia);
    Buf    lpszHttpForwarded;    GetEnv(__T("HTTP_FORWARDED"),       lpszHttpForwarded);
    Buf    lpszHttpForwardedFor; GetEnv(__T("HTTP_X_FORWARDED_FOR"), lpszHttpForwardedFor);
    Buf    lpszHttpUserAgent;    GetEnv(__T("HTTP_USER_AGENT"),      lpszHttpUserAgent);
    Buf    lpszHttpReferer;      GetEnv(__T("HTTP_REFERER"),         lpszHttpReferer);
    _TCHAR tmpBuf[0x2000];

    if ( *lpszHttpUserAgent.Get() ) {
        _stprintf(tmpBuf, __T("X-Web-Browser: Send using %s\r\n"), lpszHttpUserAgent.Get());
        lpszOtherHeader.Add(tmpBuf);
    }

    if ( *lpszHttpForwarded.Get() ) {
        _stprintf(tmpBuf, __T("X-Forwarded: %s\r\n"), lpszHttpForwarded.Get());
        lpszOtherHeader.Add(tmpBuf);
    }

    if ( *lpszHttpForwardedFor.Get() ) {
        _stprintf(tmpBuf, __T("X-X-Forwarded-For: %s\r\n"), lpszHttpForwardedFor.Get());
        lpszOtherHeader.Add(tmpBuf);
    }

    if ( *lpszHttpVia.Get() ) {
        _stprintf(tmpBuf, __T("X-Via: %s\r\n"), lpszHttpVia.Get());
        lpszOtherHeader.Add(tmpBuf);
    }

    if ( *lpszHttpReferer.Get() ) {
        _stprintf(tmpBuf, __T("X-Referer: %s\r\n"), lpszHttpReferer.Get());
        lpszOtherHeader.Add(tmpBuf);
    }

    _stprintf(tmpBuf, __T("Received: from %s by %s with HTTP; "),
              lpszRemoteAddr.Get(), lpszServerName.Get());
    lpszFirstReceivedData.Add(tmpBuf);

    lpszRemoteAddr.Free();
    lpszServerName.Free();
    lpszHttpVia.Free();
    lpszHttpForwarded.Free();
    lpszHttpForwardedFor.Free();
    lpszHttpUserAgent.Free();
    lpszHttpReferer.Free();

    lpszMethod.Free();
    lpszPost.Free();
    lpszParamCgi.Free();
    lpszQueryString.Free();
    lpszPathTranslated.Free();
    lpszCmdBlat.Free();

    return TRUE;
}
Exemple #10
0
void AutoUpdaterImpl::init() {
  time_t now(time(NULL));
  char st[256];

  msgbox("update: init called.\n");

  if(now < config.info3.last_update + mindelay) {
    now = config.info3.last_update + mindelay;
    msgbox("update: updated too recently, not before %s", ctime(&now));
    ret();
    return;
  }

  buf.resize(0);
  buf.append("GET "UPDATE_PATH" HTTP/1.0\r\n");
  buf.append("Host: "UPDATE_HOST"\r\n");
  buf.append("Connection: close\r\n");
  snprintf(st, sizeof(st), "User-Agent: Quadra/%s\r\n", VERSION_STRING);
  buf.append(st);
  if(*config.info3.last_modified) {
    msgbox("update: setting If-Modified-Since to %s\n",
	   config.info3.last_modified);
    buf.append("If-Modified-Since: ");
    buf.append(config.info3.last_modified);
    buf.append("\r\n");
  } else
    msgbox("update: not setting If-Modified-Since\n");
  buf.append("\r\n");
  req = new Http_request(UPDATE_HOST, UPDATE_PORT, buf.get(), buf.size());
}
Exemple #11
0
void SearchVar(Buf &lpszParamCgi,LPCTSTR lpszVarName,BOOL fMimeDecode, Buf &ret)
{
    Buf    lpAlloc;
    LPTSTR lpszProvCmp,lpszVarForCmp;
    DWORD  dwVarNameLen=(DWORD)_tcslen(lpszVarName);
    DWORD  dwLineLen=(DWORD)lpszParamCgi.Length();
    DWORD  dwPos=0;

    ret.Clear();

    lpAlloc.AllocExact((dwVarNameLen+0x10)*2);
    lpszProvCmp=lpAlloc.Get();
    lpszVarForCmp=lpAlloc.Get()+(((dwVarNameLen+7)/4)*4);

    _tcscpy(lpszVarForCmp,lpszVarName);
    _tcscat(lpszVarForCmp,__T("="));
    *(lpszProvCmp+dwVarNameLen+1) = __T('\0');

    while ( dwPos < dwLineLen ) {
        DWORD dwNextPos = SearchNextPos(lpszParamCgi.Get()+dwPos,FALSE);
        if ( dwPos+dwVarNameLen >= dwLineLen )
            break;

        memcpy(lpszProvCmp,lpszParamCgi.Get()+dwPos,(dwVarNameLen+1)*sizeof(_TCHAR));
        if ( _tcsicmp(lpszProvCmp,lpszVarForCmp) == 0 ) {
            DWORD dwLenContent = dwNextPos-(dwVarNameLen+1);
            ret.Alloc(dwLenContent+0x10);
            ret.Add(lpszParamCgi.Get()+dwPos+dwVarNameLen+1,dwLenContent);
            if ( fMimeDecode ) {
                url_decode(ret.Get());
                ret.SetLength();
            }
            break;
        }
        dwPos += dwNextPos+1;
    }
    lpAlloc.Free();
}
Exemple #12
0
void ReadPostData(Buf &buf)
{
    DWORD dwStep=4096;
    DWORD dwReadThis;
    DWORD dwThisStep;
    DWORD dwTotalBytes;
    Buf   lpszContentLength;

    GetEnv(__T("CONTENT_LENGTH"), lpszContentLength);
    dwTotalBytes = (DWORD)_tstol(lpszContentLength.Get());
    buf.AllocExact(dwTotalBytes + 1);
    buf.Clear();

    do {
        dwThisStep = (DWORD) min(dwTotalBytes-buf.Length(),dwStep);
        dwReadThis = dwThisStep;
        if ( dwThisStep > 0 ) {
            dwReadThis = 0;
            if ( !ReadFile(GetStdHandle(STD_INPUT_HANDLE),buf.GetTail(),dwReadThis,
                                        &dwReadThis,NULL) )
                dwReadThis = 0;
        }
        buf.SetLength(buf.Length() + dwReadThis);

    } while ( (dwReadThis==dwThisStep) && (buf.Length()<dwTotalBytes) );

    *buf.GetTail() = __T('\0');
    lpszContentLength.Free();
}
 // FIXME: not reentrant
 static_buf() { buf.clear(); }
Exemple #14
0
int SendTask::work ()
{
    while (true)
    {
        Buf* p = NULL;
        if (SINGLE->sendqueue.dequeue (p, 3) != 0)
        {
            continue;
        }

        int fd = p->getfd ();

        if (fd <= 0)
        {
            cout << "[SEND] -- fd of buffer <= 0" << endl;
            SINGLE->bufpool.free (p);
            continue;
        }

        //
#if 0
        cout << "Send cType: " << ((MSG_HEAD*)p->ptr())->cType <<endl;
        printf ("address: %p\n", p);
        if (((MSG_HEAD*)p->ptr())->cType == 187) {
        cout << "-----------------------BEGIN-------------------------------------" << endl;
        cout << "CTYPE: " << ((MSG_HEAD*) (p->ptr()))->cType << endl;
        cout << "LEN: " << *(unsigned int*) ((char*)p->ptr() + MSG_HEAD_LEN) << endl;
        cout << "STUDENT_ID: " << *(unsigned int*) ((char*)p->ptr() + MSG_HEAD_LEN + sizeof (unsigned int)) << endl;
        cout << "STATUS: " << *(unsigned int*) ((char*)p->ptr() + MSG_HEAD_LEN + sizeof (int) + sizeof (int)) << endl;
        cout << "STUDENT_ID: " << *(unsigned int*) ((char*)p->ptr() + MSG_HEAD_LEN + sizeof (int) + sizeof (int) + sizeof (int)) << endl;
        cout << "STATUS: " << *(unsigned int*) ((char*)p->ptr() + MSG_HEAD_LEN + sizeof (int) + sizeof (int)+ sizeof (int) + sizeof (int)) << endl;

        cout << "-------------------------END-----------------------------------" << endl;
        }
#endif

        // send fck message to clients
        // must be need written bytes data finished
        debugProtocol (p);
        int bytes_left = p->size ();
        int written_bytes;
        char* ptr = (char*) p->ptr();
        while (bytes_left > 0)
        {
            written_bytes = send (fd, ptr, bytes_left, 0);
            if (written_bytes <= 0) {
                if (errno == EINTR) {
                    if (written_bytes < 0) {
                        written_bytes = 0;
                        cout << "EINTR......" << endl;
                        continue;
                    }
                }
                else if (errno == EAGAIN) {
                    if (written_bytes < 0) {
                        written_bytes = 0;
                        usleep (50);
                        cout << "EAGAIN......" << endl;
                        continue;
                    }
                }
                else {
                    break;
                }
            }
            bytes_left -= written_bytes;
            ptr += written_bytes;
        }

        //printf("Send data...finished. packetLength=%ld, from FD=[%d]\n", p->size(), fd);
        LOG(INFO) << "Send data ... finished. packet len=" << p->size() << ", from FD=" << fd << endl;

        p->reset ();
        SINGLE->bufpool.free (p);
    }
    return 0;
}
Exemple #15
0
int ReliSock::RcvMsg::rcv_packet( char const *peer_description, SOCKET _sock, int _timeout)
{
	Buf		*tmp;
	char	        hdr[MAX_HEADER_SIZE];
	int		end;
	int		len, len_t, header_size;
	int		tmp_len;

	header_size = (mode_ != MD_OFF) ? MAX_HEADER_SIZE : NORMAL_HEADER_SIZE;

	int retval = condor_read(peer_description,_sock,hdr,header_size,_timeout);
	if ( retval < 0 && 
		 retval != -2 ) // -2 means peer just closed the socket
	{
		dprintf(D_ALWAYS,"IO: Failed to read packet header\n");
		return FALSE;
	}
	if ( retval == -2 ) {	// -2 means peer just closed the socket
		dprintf(D_FULLDEBUG,"IO: EOF reading packet header\n");
		return FALSE;
	}
	end = (int) ((char *)hdr)[0];
	memcpy(&len_t,  &hdr[1], 4);
	len = (int) ntohl(len_t);

	if (end < 0 || end > 10) {
		dprintf(D_ALWAYS,"IO: Incoming packet header unrecognized\n");
		return FALSE;
	}
        
	if (!(tmp = new Buf)){
		dprintf(D_ALWAYS, "IO: Out of memory\n");
		return FALSE;
	}
	if (len > tmp->max_size()){
		delete tmp;
		dprintf(D_ALWAYS, "IO: Incoming packet is too big\n");
		return FALSE;
	}
	if (len <= 0)
	{
		delete tmp;
		dprintf(D_ALWAYS, 
			"IO: Incoming packet improperly sized (len=%d,end=%d)\n",
			len,end);
		return FALSE;
	}
	if ((tmp_len = tmp->read(peer_description, _sock, len, _timeout)) != len){
		delete tmp;
		dprintf(D_ALWAYS, "IO: Packet read failed: read %d of %d\n",
				tmp_len, len);
		return FALSE;
	}

        // Now, check MD
        if (mode_ != MD_OFF) {
            if (!tmp->verifyMD(&hdr[5], mdChecker_)) {
                delete tmp;
                dprintf(D_ALWAYS, "IO: Message Digest/MAC verification failed!\n");
                return FALSE;  // or something other than this
            }
        }
        
	if (!buf.put(tmp)) {
		delete tmp;
		dprintf(D_ALWAYS, "IO: Packet storing failed\n");
		return FALSE;
	}
		
	if (end) {
		ready = TRUE;
	}
	return TRUE;
}
Exemple #16
0
/*
=====================
 获得数据库表纪录
=====================
*/
bool CHandleMessage::postDBRecord (Buf* buf, int iCase)
{
#if 0
    if (NULL == buf) {
        printf("null buf\n");
        return false;
    }

    MSG_HEAD head;

    try {
        MutexLockGuard guard(DATABASE->m_mutex);
        PreparedStatement* pstmt = NULL;

        if (iCase == 1)
            pstmt = DATABASE->preStatement (SQL_SELECT_COURSE_DB);
        else if (iCase == 2)
            pstmt = DATABASE->preStatement (SQL_SELECT_GRADE_DB);
        else if (iCase == 3)
            pstmt = DATABASE->preStatement (SQL_SELECT_CLASS_DB);
        else if (iCase == 4)
            pstmt = DATABASE->preStatement (SQL_SELECT_CLASSROOM_DB);
        else if (iCase == 5)
            pstmt = DATABASE->preStatement (SQL_SELECT_STUDENT_DB);
        else if (iCase == 6) {
            pstmt = DATABASE->preStatement (SQL_SELECT_COURSEITEM_DB);
#if 1   // send count of all selected course by teacher
            #ifdef _TEACHER_NOLOGIN
            // only for h**king test............
            pstmt->setString (1, "拼图");
            pstmt->setString (2, "造房子");
            pstmt->setString (3, "暖身操");
            pstmt->setString (4, "动画片");
            #else
            CRoom* room = ROOMMANAGER->get_room_by_fd (buf->getfd());
            if (room != NULL)
            {
                CRoom::COURSELIST::iterator it;
                int ii = 1;
                for (it = room->m_course_list.begin (); it != room->m_course_list.end (); ++it)
                    pstmt->setString (ii++, (*it)->getName());
            }
            #endif
#else
            sGetCourseItem* ci = (sGetCourseItem *) ((char*)((MSG_HEAD*)buf->ptr()) + sizeof (MSG_HEAD));
            pstmt->setString (1, ci->sCourseName);
#endif
        }
        else {
            cout << "error: index" << endl;
            return false;
        }

        ResultSet* prst = pstmt->executeQuery();
        unsigned int index = 0, type = 0;
        while(prst->next()) {
            //printf ("index = %d------------------------------------------------------\n", index);
            if (iCase == 1) {
                memset (&head, 0x00, sizeof (head));
                //head.cType = CT_GetCourseDB * 100 + index++;
                type = 5000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                head.cLen = sizeof(MSG_HEAD) + sizeof(struct sGetCourseDB);
                struct sGetCourseDB course_info;
                (void) memset (&course_info, 0x00, sizeof (sGetCourseDB));

                strcpy(course_info.sGradeName, prst->getString ("grade_name").c_str());
                strcpy(course_info.sGroupName, prst->getString ("group_name").c_str());
                strcpy(course_info.sCourseName, prst->getString("course_name").c_str());

                course_info.iLanguage   = prst->getInt ("language");
                course_info.iArt        = prst->getInt ("art");
                course_info.iCommunity  = prst->getInt ("community");
                course_info.iHealth     = prst->getInt ("health");
                course_info.iScience    = prst->getInt ("science");

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy(p->ptr(), &head, sizeof(MSG_HEAD));
                memcpy((char*)p->ptr() + sizeof(MSG_HEAD), &course_info, sizeof(struct sGetCourseDB));
                p->setfd(buf->getfd());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue(p);
            }

            else if (iCase == 2) {
                memset (&head, 0x00, sizeof (head));
                type = 3000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                //head.cType = CT_GetGradeDB;
                head.cLen = sizeof (MSG_HEAD)+ sizeof (struct sGetGradeDB);
                struct sGetGradeDB grade_info;
                (void) memset (&grade_info, 0x00, sizeof (grade_info));

                strcpy (grade_info.sGradeName, prst->getString ("grade_name").c_str());

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof(MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof(MSG_HEAD), &grade_info, sizeof(struct sGetGradeDB));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
            }

            else if (iCase == 3) {
                memset (&head, 0x00, sizeof (head));
                type = 4000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                //head.cType = CT_GetClassDB;
                head.cLen = sizeof(MSG_HEAD)+ sizeof (struct sGetClassDB);
                struct sGetClassDB class_info;
                (void) memset (&class_info, 0x00, sizeof (class_info));

                strcpy (class_info.sClassName, prst->getString ("class_name").c_str());

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof (MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof (MSG_HEAD), &class_info, sizeof (struct sGetClassDB));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
            }

            else if (iCase == 4) {
                memset (&head, 0x00, sizeof (head));
                //head.cType = CT_GetClassRoomDB;
                type = 6000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                head.cLen = sizeof(MSG_HEAD) + sizeof (struct sGetClassRoomDB);
                struct sGetClassRoomDB room_info;
                (void) memset (&room_info, 0x00, sizeof (room_info));

                strcpy (room_info.sClassRoomName, prst->getString ("classroom_name").c_str());

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof (MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof (MSG_HEAD), &room_info, sizeof (struct sGetClassRoomDB));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
            }

            else if (iCase == 5) {
                memset (&head, 0x00, sizeof (MSG_HEAD));
                type = 10000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                /// cout << "begin:-head.cType = " << head.cType << endl;
                head.cLen = sizeof (MSG_HEAD) + sizeof (struct sGetAllStudentInfo);
                struct sGetAllStudentInfo stu_info;
                (void) memset (&stu_info, 0x00, sizeof (stu_info));

                strcpy (stu_info.sPicName, prst->getString ("picture_name").c_str());
                strcpy (stu_info.sStudentName, prst->getString ("student_name").c_str());
                stu_info.iStudentId= prst->getInt ("student_id");

                /// cout << "stu_info.iStudentId:" << stu_info.iStudentId << endl;
                /// cout << "stu_info.sPicName:" << stu_info.sPicName << endl;
                /// cout << "stu_info.sStudentName:" << stu_info.sStudentName << endl;

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof (MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof (MSG_HEAD), &stu_info, sizeof (struct sGetAllStudentInfo));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
                /// cout << "address = " << p << endl;
                /// cout << "ended:-head.cLen = " << head.cLen << endl;
                /// cout << "ended:-head.cType = " << head.cType << endl;
            }

            else if (iCase == 6) {
                memset (&head, 0x00, sizeof (head));
                type = 7000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                //head.cType = CT_GetCourseItem;
                head.cLen = sizeof(MSG_HEAD) + sizeof (struct sCourseItem);
                struct sCourseItem course_item;
                (void) memset (&course_item, 0x00, sizeof (sCourseItem));

                strcpy (course_item.sCourseName, prst->getString ("course_name").c_str());
                strcpy (course_item.sItemName, prst->getString ("item_name").c_str());
                strcpy (course_item.sDesc, prst->getString ("fck_desc").c_str());

                cout << "courseName: " << course_item.sCourseName << endl;
                cout << "itemName: " << course_item.sItemName << endl;
                cout << "Desc: " << course_item.sDesc << endl;
                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof(MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof(MSG_HEAD), &course_item, sizeof (struct sCourseItem));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
            }
            else {
                cout << "error: index" << endl;
                return false;
            }

        }
#if 1   // send finished flags
        do {
            sleep (1);
            //cout << "send finished flags -----------" << endl;
            Buf* p = SINGLE->bufpool.malloc ();
            MSG_HEAD* phead = (MSG_HEAD*)p->ptr();
            struct sDBRecordFinished finished;
            memset (&finished, 0x00, sizeof (sDBRecordFinished));
            if (iCase == 5)
                finished.iFlagFinished = 10000;
            else
                finished.iFlagFinished = 1;

            phead->cLen = sizeof (MSG_HEAD) + sizeof (struct sDBRecordFinished);
            phead->cType = ST_GetDBRecordFinished;
            memcpy (((char*)p->ptr()) + MSG_HEAD_LEN, &finished, sizeof (struct sDBRecordFinished));
            p->setfd (buf->getfd());
            p->setsize (phead->cLen);
            SINGLE->sendqueue.enqueue (p);
        } while (0);
#endif
    }
    catch(SQLException e){
        LOG(ERROR) << e.what() << std::endl;
    }

    buf->reset();
    SINGLE->bufpool.free(buf);
#endif
    return true;
}
Exemple #17
0
BOOL BuildMessageAndCmdLine(Buf &lpszParamCgi, LPCTSTR lpszPathTranslated, Buf &lpszCmdBlat, Buf &lpszMessage)
{
    DWORD dwSize=0;
    Buf   lpszParamFile;
    Buf   lpszValue;

    lpszMessage.Clear();
    lpszParamFile.Clear();
    lpszValue.Clear();

    if ( _tcslen(lpszPathTranslated) > 0 )
        if ( getFileSize(lpszPathTranslated,dwSize) )
            if ( dwSize > 0 ) {
                WinFile hf;
                if ( hf.OpenThisFile(lpszPathTranslated) ) {
                    DWORD dwSizeRead = 0;
                    lpszParamFile.Alloc(dwSize+10);
                    hf.ReadThisFile(lpszParamFile.Get(),dwSize,&dwSizeRead,NULL);
                    lpszParamFile.SetLength(dwSizeRead);
                    *lpszParamFile.GetTail() = __T('\0');
                    hf.Close();
                }
            }

    if ( !lpszParamFile.Length() ) {
        Buf lpszNewParamFile;

        lpszNewParamFile.Add(__T("-"));
        _BLATOPTIONS * pbvo = blatOptionsList;

        for ( ; ; pbvo++ ) {
            if ( !pbvo->optionString &&
                 !pbvo->preprocess   &&
                 !pbvo->additionArgC &&
                 !pbvo->initFunction &&
                 !pbvo->usageText    )
                break;

/*
 * If .szCgiEntry == NULL (0), there is no alternate CGI option to match.
 * If .szCgiEntry == 1, then the option is blocked from CGI access.
 */
            if ( pbvo->szCgiEntry == (LPTSTR)1 )
                continue;

            _TCHAR szVarNamePrefixed[128];

            lpszValue.Clear();
            if ( pbvo->szCgiEntry ) {
                SearchVar(lpszParamCgi, pbvo->szCgiEntry, TRUE, lpszValue);
                if ( !lpszValue.Length() ) {
                    _stprintf(szVarNamePrefixed, __T("Blat_%s"), pbvo->szCgiEntry);
                    SearchVar(lpszParamCgi, szVarNamePrefixed, TRUE, lpszValue);
                }
            }

            if ( !lpszValue.Length() ) {
                if ( !pbvo->optionString )
                    continue;

                SearchVar(lpszParamCgi, &pbvo->optionString[1], TRUE, lpszValue);
                if ( !lpszValue.Length() ) {
                    _stprintf(szVarNamePrefixed, __T("Blat_%s"), &pbvo->optionString[1]);
                    SearchVar(lpszParamCgi, szVarNamePrefixed, TRUE, lpszValue);
                }
            }

            if ( lpszValue.Length() ) {
                DWORD dwLen = (DWORD)lpszValue.Length();
                DWORD i;

                for ( i = 0; i < dwLen; i++ )
                    if ( (*(lpszValue.Get()+i)) == __T('"') )
                        (*(lpszValue.Get()+i)) = __T('\'');  // to avoid security problem, like including other parameter like -attach

                if ( pbvo->additionArgC ) {
                    lpszNewParamFile.Add(__T(" "));
                    lpszNewParamFile.Add(pbvo->optionString);
                    lpszNewParamFile.Add(__T(" \""));
                    lpszNewParamFile.Add(lpszValue.Get());
                    lpszNewParamFile.Add(__T("\""));
                } else {
                    if ( dwLen > 0 )
                        /*
                         * Assume that by finding the boolean option specified, the site developer wants to use the option.
                         * Therefore, unless we find the developer specifically tells us 'N', we will presume the developer
                         * goofed and forgot to mention 'Y'.
                         */
                        if ( ((*lpszValue.Get()) != __T('N')) && ((*lpszValue.Get()) != __T('n')) && ((*lpszValue.Get()) != __T('0')) ) {
                            lpszNewParamFile.Add(__T(" "));
                            lpszNewParamFile.Add(pbvo->optionString);
                        }
                }
                lpszValue.Clear();
            }
        }
        lpszParamFile.Move(lpszNewParamFile);
        lpszNewParamFile.Free();
    }
    lpszCmdBlat.Move(lpszParamFile);

    //tprintf(__T("command : \"%s\"\n"),lpszCmdBlat);

    lpszMessage.Add(__T(""));

    DWORD dwPos     = 0;
    DWORD dwLineLen = (DWORD)lpszParamCgi.Length();

    while ( dwPos < dwLineLen ) {
        _TCHAR szNameForCmp[7];
        DWORD  dwEndVar;
        DWORD  dwEndVarName;
        BOOL   fCopyCurrentVar;

        dwEndVar        = SearchNextPos(lpszParamCgi.Get()+dwPos,FALSE);
        dwEndVarName    = SearchNextPos(lpszParamCgi.Get()+dwPos,TRUE);
        fCopyCurrentVar = TRUE;

        if ( dwEndVarName > 5 ) {
            memcpy(szNameForCmp,lpszParamCgi.Get()+dwPos,5*sizeof(_TCHAR));
            szNameForCmp[5] = __T('\0');
            fCopyCurrentVar = (lstrcmpi(szNameForCmp,__T("Blat_")) != 0);
        }
        if ( fCopyCurrentVar ) {
            Buf lpCurVar;

            lpCurVar.Alloc(dwEndVar+0x10);
            lpCurVar.Clear();
            memcpy(lpCurVar.Get(),lpszParamCgi.Get()+dwPos,dwEndVar*sizeof(_TCHAR));
            lpCurVar.SetLength(dwEndVar);
            *lpCurVar.GetTail() = __T('\0');
            url_decode(lpCurVar.Get());
            lpszMessage.Add(lpCurVar.Get());
            lpszMessage.Add(__T("\r\n"));
            lpCurVar.Free();
        }
        dwPos += dwEndVar+1;
    }

    lpszValue.Free();
    lpszParamFile.Free();
    return TRUE;
}