Example #1
0
void KeyFile::setRoot(KeyPageAddr addr, int delta) {
  KeyFileHeader header;
  readHead(header, false);
  header.m_root      = addr;
  header.m_keyCount += delta;
  writeHead(header);
}
Example #2
0
bool writeJob::initJob()
{
//    qDebug()<<"start init ";
    // 先要知道which file
    if(isFileNameSet==true)
    {
        fileJob.setFileName(jobFileName);
        if(!fileJob.open(QFile::ReadWrite))
            qDebug()<<"can`t open jobFileXML";
        // 先是只读,看看需不需要初始化
        QDomDocument doc;
        if (!doc.setContent(&fileJob))
        {
            qDebug()<<"setContent error or file is not init first, need to be init to a xml file!";

            writeHead(&fileJob);
        }
        else
        {
            qDebug()<<"file alread exist and init, it can be used to add module.";
        }
    }
    fileJob.close();

    if(isFileNameSet==false)
    {
        qDebug()<<"writeJob:: job file name is still not set";
        return false;
    }
    return true;
}
Example #3
0
void DB::create(int head_ptr, byte recsize)
{
  DB_head_ptr = head_ptr;
  DB_head.n_recs   = 0;
  DB_head.rec_size = recsize;
  writeHead();
}
Example #4
0
 /**
  * �ָ���¼
  */
 void CFileQueue::recoverRecord() {
     char tmp[256];
     int fd, size, count = 0;
     for(int i=0; i<TBFQ_MAX_THREAD_COUNT; i++) {
         unsettle *pos = &(m_head.pos[i]);
         if (pos->seqno == 0) continue;
         if (pos->seqno > m_head.read_seqno) continue;
         if (pos->offset >= m_head.read_offset) continue;
         
         sprintf(tmp, "%s/%08u.dat", m_queuePath, pos->seqno);
         fd = open(tmp, O_RDONLY, 0600);
         if (fd == -1) continue;
         lseek(fd, pos->offset, SEEK_SET);
         if (read(fd, &size, sizeof(int)) == sizeof(int) && 
             size >= (int)sizeof(queue_item) && 
             size < (int)TBFQ_MAX_FILE_SIZE) {
             size -= sizeof(int);
             queue_item *item = (queue_item*) malloc(size);
             assert(item != NULL);
             if (read(fd, item, size) == size && item->flag == TBFQ_FILE_QUEUE_FLAG) {
                 push(&(item->data[0]), item->len);
                 count ++;
             }
             free(item);
         }
         close(fd);
     }
     TBSYS_LOG(INFO, "%s: recoverRecord: %d", m_queuePath, count);
     memset(&m_head.pos[0], 0, TBFQ_MAX_THREAD_COUNT*sizeof(unsettle));
     writeHead();
 }
Example #5
0
void KeyFile::truncate() { // remove all data!!! be careful
  KeyFileHeader header;
  readHead(header, false);
  const KeyFileDefinition keydef = header.m_keydef;
  header.init(keydef);
  DbFile::truncate();
  writeHead(header);
}
Example #6
0
// Adds a record to the end of the record set.
// This is the fastest way to add a record.
EDB_Status EDB::appendRec(EDB_Rec rec)
{
  if (EDB_head.n_recs + 1 > limit()) return EDB_TABLE_FULL;
  EDB_head.n_recs++;
  writeRec(EDB_head.n_recs,rec);
  writeHead();
  return EDB_OK;
}
Example #7
0
// creates a new table and sets header values 
EDB_Status EDB::create(unsigned long head_ptr, unsigned long tablesize, unsigned int recsize)
{
  EDB_head_ptr = head_ptr;
  EDB_table_ptr = sizeof(EDB_Header) + EDB_head_ptr;
  EDB_head.n_recs = 0;
  EDB_head.rec_size = recsize;
  EDB_head.table_size = tablesize;
  writeHead();
  return EDB_OK;
}
Example #8
0
 /**
  * д��һ��¼
  */
 int CFileQueue::push(void *data, int len)
 {
     if (m_writeFd == -1) {
         openWriteFile();
         if (m_writeFd == -1) {
             TBSYS_LOG(WARN, "�ļ�û����: %s:%u", m_queuePath, m_head.write_seqno);
             return EXIT_FAILURE;
         }
     }
     if (data == NULL || len == 0) {
         TBSYS_LOG(WARN, "data: %p, len: %d", data, len);
         return EXIT_FAILURE;
     }
     int size = sizeof(int) + sizeof(queue_item) + len;
     if (size > TBFQ_MAX_FILE_SIZE) {
         TBSYS_LOG(WARN, "size: %d", size);
         return EXIT_FAILURE;
     }
     char *buffer = (char*)malloc(size);
     assert(buffer != NULL);
     *((int*)buffer) = size;
     queue_item *item = (queue_item*) (buffer + sizeof(int));
     item->len = len;
     item->flag = TBFQ_FILE_QUEUE_FLAG;
     memcpy(&(item->data[0]), data, len);
     
     // �����ļ����������´���һ��
     if (m_head.write_filesize >= m_maxFileSize) {
         m_head.write_seqno ++;
         m_head.write_filesize = 0;
         openWriteFile();
         writeHead();
     }
     item->pos.seqno = m_head.write_seqno;
     item->pos.offset = m_head.write_filesize;
     int ret = write(m_writeFd, buffer, size);
     if (ret > 0) {
         m_head.write_filesize += size;
     }
     free(buffer);
     if (ret != size) { // дʧ��
         TBSYS_LOG(WARN, "дʧ��: %s, fd: %d, len: %d, %d<>%d", 
             m_queuePath, m_writeFd, len, ret, size);
         ret = size - ret;
         if (ret>0 && ret<=size && size<m_maxFileSize) {
             TBSYS_LOG(WARN, "����%d���ֽ�д", ret);
             lseek(m_writeFd, ret, SEEK_CUR);
         }
         return EXIT_FAILURE;
     }
     m_head.queue_size ++;
     return EXIT_SUCCESS;
 }
Example #9
0
// Deletes a record at a given recno
// Becomes more inefficient as you the record set increases and you delete records 
// early in the record queue.
EDB_Status EDB::deleteRec(unsigned long recno)
{
  if (recno < 0 || recno > EDB_head.n_recs) return  EDB_OUT_OF_RANGE;
  EDB_Rec rec = (byte*)malloc(EDB_head.rec_size);
  for (unsigned long i = recno + 1; i <= EDB_head.n_recs; i++)
  {
    readRec(i, rec);
    writeRec(i - 1, rec);
  }  
  free(rec);
  EDB_head.n_recs--;
  writeHead();
  return EDB_OK;
}
Example #10
0
File: EDB.cpp Project: 4-20ma/EDB
// creates a new table and sets header values 
EDB_Status EDB::create(unsigned long head_ptr, unsigned long tablesize, unsigned int recsize)
{
  EDB_head_ptr = head_ptr;
  EDB_table_ptr = sizeof(EDB_Header) + EDB_head_ptr;
  EDB_head.flag = EDB_FLAG;
  EDB_head.n_recs = 0;
  EDB_head.rec_size = recsize;
  EDB_head.table_size = tablesize;
  writeHead();
  if (EDB_head.flag == EDB_FLAG){
    return EDB_OK;
  } else {
    return EDB_ERROR;
  }
}
Example #11
0
void KeyFile::setFreeList(KeyPageAddr addr, int dsize) {
  KeyFileHeader header;
  readHead(header, true);
  header.m_freeList     =  addr;
  header.m_freeListSize += dsize;
  if(header.m_freeListSize < 0) {
    throwSqlError(SQL_FATAL_ERROR,_T("KeyFile::setFreeList:m_header.m_freeListSize<0. (=%d)"),header.m_freeListSize);
  } else if(header.m_freeListSize == 0 && header.m_freeList != DB_NULLADDR) {
    throwSqlError(SQL_FATAL_ERROR,_T("KeyFile::setFreeList:m_header.m_freeListSize=0 and m_freeList != NULLADDR."));
  } else if(header.m_freeListSize > 0 && header.m_freeList == DB_NULLADDR) {
    throwSqlError(SQL_FATAL_ERROR,_T("KeyFile::setFreeList:m_header.m_freeListSize>0 and m_freeList == NULLADDR."));
  }

  writeHead(header);
}
void 
write_htmlHomePage::writePage(void) 
{
  htmlpage.open (HTMLfilesRegister::homePage);
  pageTitle = "Home Page";
  writeHead();
  writeIndex();

  htmlpage << "In these pages we show the results of the analisys of "
	   << "the NAST (New Abstract Syntax Tree) built by the "
	   << "application XOgastan from the xml file " << xmlFile 
	   << ".<br><br>\n";

  htmlpage << "<ol>";
 
  htmlpage << "\t<li>"
	   << "<a href=\""
	   << HTMLfilesRegister::fnctIndex
	   << "\">Index of the functions</a><br><br>\n\n";
  htmlpage << "\t<ol>";
  htmlpage << "\t\t<li>"
	   << "<a href=\""
	   << HTMLfilesRegister::fnctWithBodyIndex
	   << "\">Functions with body</a><br><br>\n\n";
  htmlpage << "\t\t<li>"
	   << "<a href=\""
	   << HTMLfilesRegister::fnctWithParmIndex
	   << "\">Functions with parameters</a><br><br>\n\n";
  htmlpage << "\t\t<li>"
	   << "<a href=\""
	   << HTMLfilesRegister::fnctIsStdCIndex
	   << "\">List of functions of the C standard library</a><br><br>\n\n";
  htmlpage << "\t</ol>\n\n";

  htmlpage << "\t<li>"
	   << "<a href=\""
	   << HTMLfilesRegister::nastStatistics
	   << "\">Statistics information of the NAST</a><br><br>\n\n";

  htmlpage << "</ol>\n\n";

  writeIndex();
  writeFoot();
  htmlpage.close();

  return;
}
Example #13
0
// Inserts a record at a given recno, increasing all following records' recno by 1.
// This function becomes increasingly inefficient as it's currently implemented and 
// is the slowest way to add a record.
EDB_Status EDB::insertRec(unsigned long recno, EDB_Rec rec)
{
  if (count() == limit()) return EDB_TABLE_FULL;
  if (count() > 0 && (recno < 0 || recno > EDB_head.n_recs)) return EDB_OUT_OF_RANGE;
  if (count() == 0 && recno == 1) return appendRec(rec);

  EDB_Rec buf = (byte*)malloc(EDB_head.rec_size);
  for (unsigned long i = EDB_head.n_recs; i >= recno; i--)
  {
    readRec(i, buf);
    writeRec(i + 1, buf);
  }
  free(buf);
  writeRec(recno, rec);  
  EDB_head.n_recs++;
  writeHead();
  return EDB_OK;
}
void 
write_htmlNastStat::writePage(void) 
{
  pageTitle = "NAST statistics";
  htmlpage.open (HTMLfilesRegister::nastStatistics);
  writeHead();
  writeIndex();

  // Global statistics
  writeSectionTitle("Statistics about all the NAST");
  writeGlobalStatistics();
  
  // Partial statistics
  writeSectionTitle("Statistics about the functions with body");
  writePartialStatistics();

  writeIndex();
  writeFoot();
  htmlpage.close();

  return;
}
Example #15
0
 /**
  * ����
  */
 CFileQueue::~CFileQueue(void)
 {
     m_head.exit_status = 1;
     memset(&m_head.pos[0], 0, TBFQ_MAX_THREAD_COUNT*sizeof(unsettle));
     writeHead();        
     if (m_queuePath) {
         free(m_queuePath);
         m_queuePath = NULL;
     }
     if (m_infoFd != -1) {
         close(m_infoFd);
         m_infoFd = -1;
     }
     if (m_readFd != -1) {
         close(m_readFd);
         m_readFd = -1;
     }
     if (m_writeFd != -1) {
         close(m_writeFd);
         m_writeFd = -1;
     }
 }
Example #16
0
/**
 * 读出一记录, 调用程序要负责释放
 */
queue_item *CFileQueue::pop(uint32_t index)
{
	if (m_readFd == -1) {
		openReadFile();
		if (m_readFd == -1) {
			SYS_LOG(WARN, "open file failed: %s:%d", m_queuePath, m_head.read_seqno);
			return NULL;
		}
	}
	int ret, size = 0;
	queue_item *item = NULL;
	int retryReadCount = 0;
	index %= CTFO_MAX_THREAD_COUNT;

	while(retryReadCount<3) {
		int retSize = read(m_readFd, &size, sizeof(int));
		if (retSize < 0) {
			SYS_LOG(ERROR, "read error, m_readFd:%d, %s(%d)", m_readFd, strerror(errno), errno);
			break;
		}
		if (retSize == sizeof(int)) {
			size -= sizeof(int);
			// 检查size
			if (size < (int)sizeof(queue_item) || size > (int)CTFO_MAX_FILE_SIZE) {
				int curPos = (int)lseek(m_readFd, 0-retSize, SEEK_CUR);
				SYS_LOG(WARN, "read size error:%d,curPos:%d,readOff:%d,retry:%d,seqno:%u,m_readFd:%d",
					size, curPos, m_head.read_offset, retryReadCount, m_head.read_seqno,m_readFd);
				retryReadCount ++;
				if (m_writeFd != -1 && m_head.read_seqno == m_head.write_seqno) {
					fsync(m_writeFd);
				}
				continue;
			}
			// 分配内存
			item = (queue_item*) malloc(size);
			assert(item != NULL);
			if ((ret = read(m_readFd, item, size)) != size) {
				// 重新读
				int64_t curPos = lseek(m_readFd, 0-ret-retSize, SEEK_CUR);
				SYS_LOG(WARN, "read file error:%d<>%d,curPos:%d,readOff:%d,retry:%d,seqno:%u,m_readFd:%d",
					ret, size, (int)curPos, m_head.read_offset, retryReadCount, m_head.read_seqno,m_readFd);
				retryReadCount ++;
				free(item);
				item = NULL;
				if (m_writeFd != -1 && m_head.read_seqno == m_head.write_seqno) {
					fsync(m_writeFd);
				}
				continue;
			}
			// 检查flag
			if (item->flag != CTFO_FILE_QUEUE_FLAG) {
				 // 重新读
				int64_t curPos = lseek(m_readFd, 0-ret-retSize, SEEK_CUR);
				SYS_LOG(WARN, "flag error:item->flag(%d)<>FLAG(%d),curPos:%d,readOff:%d,retry:%d,seqno:%u,m_readFd:%d",
					item->flag, CTFO_FILE_QUEUE_FLAG, (int)curPos, m_head.read_offset,
					retryReadCount, m_head.read_seqno,m_readFd);
				retryReadCount ++;
				free(item);
				item = NULL;
				if (m_writeFd != -1 && m_head.read_seqno == m_head.write_seqno) {
					fsync(m_writeFd);
				}
				continue;
			}
			// 检查len
			if (item->len + (int)sizeof(queue_item) != size) {
				// 重新读
				int64_t curPos = lseek(m_readFd, 0-ret-retSize, SEEK_CUR);
				SYS_LOG(WARN, "read len error:%d<>%d,curPos:%d,readOff:%d,retry:%d,seqno:%u,m_readFd:%d",
					(int)(item->len + sizeof(queue_item)), size, (int)curPos, m_head.read_offset,
					retryReadCount, m_head.read_seqno,m_readFd);
				retryReadCount ++;
				free(item);
				item = NULL;
				if (m_writeFd != -1 && m_head.read_seqno == m_head.write_seqno) {
					fsync(m_writeFd);
				}
				continue;
			}

			retryReadCount = 0;
			m_head.pos[index].seqno = m_head.read_seqno;
			m_head.pos[index].offset = m_head.read_offset;
			m_head.read_offset += (size + sizeof(int));
			break;
		} else if (m_head.write_seqno > m_head.read_seqno) {
			// 删除处理完的文件
			deleteReadFile();
			m_head.read_seqno ++;
			m_head.read_offset = 0;
			openReadFile();
			if (m_readFd == -1) {
				m_head.queue_size = 0;
				break;
			}
		} else {
			if (retSize > 0) {
				SYS_LOG(WARN, "IO busy,retSize:%d,seqno:%u", retSize, m_head.read_seqno);
				lseek(m_readFd, 0-retSize, SEEK_CUR);
			}
			m_head.queue_size = 0;
			break;
		}
	}
	if (retryReadCount>=3) { // 连接失败了三次,移到最后
		backup(index);
		if (m_head.write_seqno > m_head.read_seqno)
		{
			deleteReadFile();
			m_head.read_seqno ++;
			m_head.read_offset = 0;
			openReadFile();
		} else {
			clear();
		}
	}
	writeHead();
	return item;
}
Example #17
0
bool HttpServerResponse::writeHead(HttpResponseStatus statusCode,
                                   const QByteArray &reasonPhrase)
{
    return writeHead(int(statusCode), reasonPhrase);
}
Example #18
0
 /**
  * ����һ��¼, ���ó���Ҫ�����ͷ�
  */
 queue_item *CFileQueue::pop(uint32_t index)
 {
     if (m_readFd == -1) {
         openReadFile();
         if (m_readFd == -1) {
             TBSYS_LOG(WARN, "�ļ�û����: %s:%d", m_queuePath, m_head.read_seqno);
             return NULL;
         }
     }
     int ret, size = 0;
     queue_item *item = NULL;
     int retryReadCount = 0;
     index %= TBFQ_MAX_THREAD_COUNT;
     
     while(retryReadCount<3) {
         int retSize = read(m_readFd, &size, sizeof(int));
         if (retSize < 0) {
             TBSYS_LOG(ERROR, "������, m_readFd:%d, %s(%d)", m_readFd, strerror(errno), errno);
             break;
         }
         if (retSize == sizeof(int)) {
             size -= sizeof(int);
             // ����size
             if (size < (int)sizeof(queue_item) || size > (int)TBFQ_MAX_FILE_SIZE) {
                 int curPos = (int)lseek(m_readFd, 0-retSize, SEEK_CUR);
                 TBSYS_LOG(WARN, "������size����ȷ:%d,curPos:%d,readOff:%d,retry:%d,seqno:%u,m_readFd:%d", 
                     size, curPos, m_head.read_offset, retryReadCount, m_head.read_seqno,m_readFd);
                 retryReadCount ++;
                 if (m_writeFd != -1 && m_head.read_seqno == m_head.write_seqno) {
                     fsync(m_writeFd);
                 }
                 continue;
             }
             // �����ڴ�
             item = (queue_item*) malloc(size);
             assert(item != NULL);
             if ((ret = read(m_readFd, item, size)) != size) {
                 // ���¶�
                 int64_t curPos = lseek(m_readFd, 0-ret-retSize, SEEK_CUR);
                 TBSYS_LOG(WARN, "���ļ�����ȷ:%d<>%d,curPos:%ld,readOff:%d,retry:%d,seqno:%u,m_readFd:%d", 
                     ret, size, curPos, m_head.read_offset, retryReadCount, m_head.read_seqno,m_readFd);
                 retryReadCount ++;
                 free(item);
                 item = NULL;
                 if (m_writeFd != -1 && m_head.read_seqno == m_head.write_seqno) {
                     fsync(m_writeFd);
                 }
                 continue;
             }
             // ����flag
             if (item->flag != TBFQ_FILE_QUEUE_FLAG) {
                  // ���¶�
                 int64_t curPos = lseek(m_readFd, 0-ret-retSize, SEEK_CUR);
                 TBSYS_LOG(WARN, "flag����ȷ:item->flag(%d)<>FLAG(%d),curPos:%ld,readOff:%d,retry:%d,seqno:%u,m_readFd:%d", 
                     item->flag, TBFQ_FILE_QUEUE_FLAG, curPos, m_head.read_offset, 
                     retryReadCount, m_head.read_seqno,m_readFd);
                 retryReadCount ++;
                 free(item);
                 item = NULL;                    
                 if (m_writeFd != -1 && m_head.read_seqno == m_head.write_seqno) {
                     fsync(m_writeFd);
                 }
                 continue;
             }
             // ����len
             if (item->len + (int)sizeof(queue_item) != size) {
                 // ���¶�
                 int64_t curPos = lseek(m_readFd, 0-ret-retSize, SEEK_CUR);
                 TBSYS_LOG(WARN, "������len����ȷ:%ld<>%d,curPos:%ld,readOff:%d,retry:%d,seqno:%u,m_readFd:%d", 
                     item->len + sizeof(queue_item), size, curPos, m_head.read_offset, 
                     retryReadCount, m_head.read_seqno,m_readFd);
                 retryReadCount ++;
                 free(item);
                 item = NULL;
                 if (m_writeFd != -1 && m_head.read_seqno == m_head.write_seqno) {
                     fsync(m_writeFd);
                 }
                 continue;
             }
             
             retryReadCount = 0;
             m_head.pos[index].seqno = m_head.read_seqno;
             m_head.pos[index].offset = m_head.read_offset;
             m_head.read_offset += (size + sizeof(int));
             break;
         } else if (m_head.write_seqno > m_head.read_seqno) {
             // ɾ�����������ļ�
             deleteReadFile();
             m_head.read_seqno ++;
             m_head.read_offset = 0;
             openReadFile();
             if (m_readFd == -1) {
                 m_head.queue_size = 0;
                 break;
             }
         } else {
             if (retSize > 0) {
                 TBSYS_LOG(WARN, "IOæ,retSize:%d,seqno:%u", retSize, m_head.read_seqno);
                 lseek(m_readFd, 0-retSize, SEEK_CUR); 
             }
             m_head.queue_size = 0;
             break;
         }
     }
     if (retryReadCount>=3) { // ����ʧ��������,�Ƶ�����
         backup(index);
         if (m_head.write_seqno > m_head.read_seqno)
         {
             deleteReadFile();
             m_head.read_seqno ++;
             m_head.read_offset = 0;
             openReadFile();
         } else {
             clear();
         }
     }
     writeHead();
     return item;
 }
void 
write_htmlFnctPages::writePage(void) 
{
  // most of the informations can be write only if the function has a body !

  dataDrawerListIterator   p;         // browse the list
  string                fnctName;     // name of the function

  
  // Browse list one function for time
  p = dataBL->begin();
  while (p != dataBL->end()) {
    dataB = *p;
    p++;
    
    fData = dataB->getFnctData();
    
    cout << "Generating html page for function " 
	 << (fnctName = fData->getName()) << "...\n";

    htmlpage.open((HTMLfilesRegister::htmlFile(*fData)).c_str());

    // begin of the page
    pageTitle = fnctName ;
    writeHead();
    writeIndex();
    
    htmlpage << "<br><br>\n";
    if (fnctName != "")
      htmlpage << "This is the page of the function " 
	       << fnctName << ".<br><br>\n";

    htmlpage << *fData
	     << "<br><l><br>\n\n";
    
    if (fData->hasBody()) {
      
      writePageIndex();
      
      // write body graph
      if (!noBodyGraph) {
	htmlpage << "<A name=\"bodyGraph\">\n";
	writeSectionTitle("Graph of the body");
	writeBodyGraph();
      }
      
      // write CFG
      if (!noCFG) {
	htmlpage << "<A name=\"CFG\">\n";
	writeSectionTitle("Control flow graph");
	writeCFG();
      }

      // write stmt stat
      if (!noStmtStat) {
	htmlpage << "<A name=\"stmtStatistics\">\n";
	writeSectionTitle("Statements statistics");
	htmlpage << *(dataB->getStmtNumData());
      }
      
      // write decl list
      if ( (!noDeclsList) && (dataB->hasDeclsList()) ) {
	htmlpage << "<A name=\"declsList\">\n";
	writeSectionTitle("Declarations into the function");
	htmlpage << *(dataB->getDeclsList());
      }
      
      // write var used
      if ( (!noVarUsed) && (dataB->hasVarUsedList()) ) {
	htmlpage << "<A name=\"varUsedList\">\n";
	writeSectionTitle("Variables used by the function");
	htmlpage << *(dataB->getVarUsedList());
      }

      // write exprs list
      if ( (!noExprsList) && (dataB->hasExprsList()) ) {
	htmlpage << "<A name=\"exprsList\">\n";
	writeSectionTitle("List of the expressions");
	htmlpage << *(dataB->getExprsList());
      }
      
      // write expr stat
      if (!noExprStat) {
	htmlpage << "<A name=\"exprStatistics\">\n";
	writeSectionTitle("Expression statistics");
	htmlpage << *(dataB->getExprNumData());
      }
      
      // write call graph
      if (!noCallGraph) {
	htmlpage << "<A name=\"callGraph\">\n";
	writeSectionTitle("Call graph");
	writeCallGraph();
      }

    }   

    // end of the page
    writeIndex();
    writeFoot();
    htmlpage.close();
  }

  return;
}
Example #20
0
// received a character from UART
void GSwifi::parseByte(uint8_t dat) {
    static uint8_t  next_token; // split each byte into tokens (cid,ip,port,length,data)
    static bool     escape = false;
    char temp[GS_MAX_PATH_LENGTH+1];

    if (dat == ESCAPE) {
        // 0x1B : Escape
        GSLOG_PRINT("e< ");
    }
    else { // if (next_token != NEXT_TOKEN_DATA) {
        GSLOG_WRITE(dat);
    }

    if (gs_mode_ == GSMODE_COMMAND) {
        if (escape) {
            // esc
            switch (dat) {
            case 'O':
            case 'F':
                // ignore
                break;
            case 'Z':
            case 'H':
                gs_mode_   = GSMODE_DATA_RX_BULK;
                next_token = NEXT_TOKEN_CID;
                break;
            default:
                // GSLOG_PRINT("!E1 "); GSLOG_PRINTLN2(dat,HEX);
                break;
            }
            escape = false;
        }
        else {
            if (dat == ESCAPE) {
                escape = true;
            }
            else if (dat == '\n') {
                // end of line
                parseLine();
            }
            else if (dat != '\r') {
                if ( ! ring_isfull(_buf_cmd) ) {
                    ring_put(_buf_cmd, dat);
                }
                else {
                    GSLOG_PRINTLN("!E2");
                }
            }
        }
        return;
    }
    else if (gs_mode_ != GSMODE_DATA_RX_BULK) {
        return;
    }

    static uint16_t       len;
    static char           len_chars[5];
    static int8_t         current_cid;
    static GSREQUESTSTATE request_state;

    if (next_token == NEXT_TOKEN_CID) {
        // dat is cid
        current_cid = x2i(dat);
        ASSERT((0 <= current_cid) && (current_cid <= 16));

        next_token  = NEXT_TOKEN_LENGTH;
        len         = 0;
    }
    else if (next_token == NEXT_TOKEN_LENGTH) {
        // Data Length is 4 ascii char represents decimal value i.e. 1400 byte (0x31 0x34 0x30 0x30)
        len_chars[ len ++ ] = dat;
        if (len >= 4) {
            len_chars[ len ] = 0;
            len        = atoi(len_chars); // length of data
            next_token = NEXT_TOKEN_DATA;

            if (content_lengths_[ current_cid ] > 0) {
                // this is our 2nd bulk message from GS for this response
                // we already swallowed HTTP response headers,
                // following should be body
                request_state = GSREQUESTSTATE_BODY;
            }
            else {
                request_state = GSREQUESTSTATE_HEAD1;
            }
            ring_clear( _buf_cmd ); // reuse _buf_cmd to store HTTP request
        }
    }
    else if (next_token == NEXT_TOKEN_DATA) {
        len --;

        if (cidIsRequest(current_cid)) { // request against us
            static uint16_t error_code;
            static int8_t   routeid;

            switch (request_state) {
            case GSREQUESTSTATE_HEAD1:
                if (dat != '\n') {
                    if ( ! ring_isfull(_buf_cmd) ) {
                        ring_put( _buf_cmd, dat );
                    }
                    // ignore overflowed
                }
                else {
                    // end of request line

                    // reuse "temp" buffer to parse method and path
                    int8_t  result  = parseRequestLine((char*)temp, 7);
                    GSMETHOD method = GSMETHOD_UNKNOWN;
                    if ( result == 0 ) {
                        method = x2method(temp);
                        result = parseRequestLine((char*)temp, GS_MAX_PATH_LENGTH);
                    }
                    if ( result != 0 ) {
                        // couldn't detect method or path
                        request_state = GSREQUESTSTATE_ERROR;
                        error_code    = 400;
                        ring_clear(_buf_cmd);
                        break;
                    }

                    routeid = router(method, temp);
                    if ( routeid < 0 ) {
                        request_state = GSREQUESTSTATE_ERROR;
                        error_code    = 404;
                        ring_clear(_buf_cmd);
                        break;
                    }
                    request_state                   = GSREQUESTSTATE_HEAD2;
                    continuous_newlines_            = 0;
                    content_lengths_[ current_cid ] = 0;
                    has_requested_with_             = false;
                    ring_clear(_buf_cmd);
                }
                break;
            case GSREQUESTSTATE_HEAD2:
                if(0 == parseHead2(dat, current_cid)) {
                    request_state = GSREQUESTSTATE_BODY;
                    // dispatched once, at start of body
                    dispatchRequestHandler(current_cid, routeid, GSREQUESTSTATE_BODY_START);
                }
                break;
            case GSREQUESTSTATE_BODY:
                if (content_lengths_[ current_cid ] > 0) {
                    content_lengths_[ current_cid ] --;
                }
                if (ring_isfull(_buf_cmd)) {
                    dispatchRequestHandler(current_cid, routeid, request_state); // POST, user callback should write()
                }
                ring_put(_buf_cmd, dat);
                break;
            case GSREQUESTSTATE_ERROR:
                // skip until received whole request
                break;
            case GSREQUESTSTATE_RECEIVED:
            default:
                break;
            }

            // end of bulk transfered data
            if (len == 0) {
                gs_mode_ = GSMODE_COMMAND;

                if ( request_state == GSREQUESTSTATE_ERROR ) {
                    writeHead( current_cid, error_code );
                    writeEnd();
                    ring_put( &commands, COMMAND_CLOSE );
                    ring_put( &commands, current_cid );
                }
                else {
                    if (content_lengths_[ current_cid ] == 0) {
                        // if Content-Length header was longer than <ESC>Z length,
                        // we wait til next bulk transfer
                        request_state = GSREQUESTSTATE_RECEIVED;
                    }
                    // user callback should write(), writeEnd() and close()
                    dispatchRequestHandler(current_cid, routeid, request_state);
                }
                ring_clear(_buf_cmd);
            }
        }
        else {
            // is request from us
            static uint16_t status_code;

            switch (request_state) {
            case GSREQUESTSTATE_HEAD1:
                if (dat != '\n') {
                    if ( ! ring_isfull(_buf_cmd) ) {
                        // ignore if overflowed
                        ring_put( _buf_cmd, dat );
                    }
                }
                else {
                    uint8_t i=0;

                    // skip 9 characters "HTTP/1.1 "
                    while (i++ < 9) {
                        ring_get( _buf_cmd, &temp[0], 1 );
                    }

                    // copy 3 numbers representing status code into temp buffer
                    temp[ 3 ] = 0;
                    int8_t count = ring_get( _buf_cmd, temp, 3 );
                    if (count != 3) {
                        // protocol error
                        // we should receive something like: "200 OK", "401 Unauthorized"
                        status_code   = 999;
                        request_state = GSREQUESTSTATE_ERROR;
                        break;
                    }
                    status_code                     = atoi(temp);
                    request_state                   = GSREQUESTSTATE_HEAD2;
                    continuous_newlines_            = 0;
                    content_lengths_[ current_cid ] = 0;
                    ring_clear(_buf_cmd);
                }
                break;
            case GSREQUESTSTATE_HEAD2:
                if(0 == parseHead2(dat, current_cid)) {
                    request_state = GSREQUESTSTATE_BODY;
                    // dispatched once, at start of body
                    dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY_START);
                }
                break;
            case GSREQUESTSTATE_BODY:
                if (content_lengths_[ current_cid ] > 0) {
                    content_lengths_[ current_cid ] --;
                }
                if (ring_isfull(_buf_cmd)) {
                    dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY);
                }
                ring_put(_buf_cmd, dat);
                break;
            case GSREQUESTSTATE_ERROR:
            case GSREQUESTSTATE_RECEIVED:
            default:
                break;
            }

            if (len == 0) {
                gs_mode_ = GSMODE_COMMAND;

                if ( request_state == GSREQUESTSTATE_ERROR ) {
                    dispatchResponseHandler(current_cid, status_code, request_state);
                }
                else {
                    if (content_lengths_[ current_cid ] == 0) {
                        // if Content-Length header was longer than <ESC>Z length,
                        // we wait til all response body received.
                        // we need to close our clientRequest before handling it.
                        // GS often locks when closing 2 connections in a row
                        // ex: POST /keys from iPhone (cid:1) -> POST /keys to server (cid:2)
                        //     response from server arrives -> close(1) -> close(2) -> lock!!
                        // the other way around: close(2) -> close(1) doesn't lock :(
                        request_state = GSREQUESTSTATE_RECEIVED;
                    }
                    dispatchResponseHandler(current_cid, status_code, request_state);
                }
                ring_clear( _buf_cmd );
            }
        } // is response
    } // (next_token == NEXT_TOKEN_DATA)
}
Example #21
0
void QHttpResponse::writeHead(StatusCode statusCode)
{
    writeHead(static_cast<int>(statusCode));
}
Example #22
0
void KeyFile::setLast(KeyPageAddr addr) {
  KeyFileHeader header;
  readHead(header, true);
  header.m_last = addr;
  writeHead(header);
}