Ejemplo n.º 1
0
long TimeAbs2Int(char *s)
{
    time_t cftime;
    int i;
    char mon[4], h[3], m[3];
    long month = 0, day = 0, hour = 0, min = 0, year = 0;
    static long days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    if (s == NULL)
    {
        return CF_NOINT;
    }

    year = Str2Int(VYEAR);

    if (year % 4 == 0)          /* leap years */
    {
        days[1] = 29;
    }

    if (strstr(s, ":"))         /* Hr:Min */
    {
        sscanf(s, "%2[^:]:%2[^:]:", h, m);
        month = Month2Int(VMONTH);
        day = Str2Int(VDAY);
        hour = Str2Int(h);
        min = Str2Int(m);
    }
    else                        /* date Month */
    {
        sscanf(s, "%3[a-zA-Z] %ld", mon, &day);

        month = Month2Int(mon);

        if (Month2Int(VMONTH) < month)
        {
            /* Wrapped around */
            year--;
        }
    }

    CfDebug("(%s)\n%ld=%s,%ld=%s,%ld,%ld,%ld\n", s, year, VYEAR, month, VMONTH, day, hour, min);

    cftime = 0;
    cftime += min * 60;
    cftime += hour * 3600;
    cftime += (day - 1) * 24 * 3600;
    cftime += 24 * 3600 * ((year - 1970) / 4);  /* Leap years */

    for (i = 0; i < month - 1; i++)
    {
        cftime += days[i] * 24 * 3600;
    }

    cftime += (year - 1970) * 365 * 24 * 3600;

    CfDebug("Time %s CORRESPONDS %s\n", s, cf_ctime(&cftime));
    return (long) cftime;
}
Ejemplo n.º 2
0
void Str2Int_Test(){
    int result;
    u8 str1[]="123.4d";
    u8 str2[]=" 1251 ";
    u8 str3[]="123c";
    
    	Str2Int(&result,str1);
        printf("str:\"%s\" int:%d\n",str1,result);
    	Str2Int(&result,str2);
        printf("str:\"%s\" int:%d\n",str2,result);
	Str2Int(&result,str3);
        printf("str:\"%s\" int:%d\n",str3,result);
}
Ejemplo n.º 3
0
void sys_init()
{
	PORTA=0x00;
	DDRA=0x0F;
	PORTB=0x00;
	DDRB=0xFF;
	PORTC=0xFF;
	DDRC=0xFF;

	PORTD=0x0F;
	DDRD=0xF0; //PD0-PD3输入 PD4-PD7输出

	// Timer/Counter 0 initialization
	// Clock source: System Clock
	// Clock value: 8000.000 kHz
	// Mode: CTC top=OCR0
	// OC0 output: Disconnected
	TCCR0=0x0d; //1024分频
	//TCNT0=0x00;
	OCR0=0x4D; //10ms
 
    // Timer/Counter 1 initialization
    TCCR1A=0x00;
    TCCR1B=0x0b;  //64分频
    OCR1AH=0x00;
    OCR1AL=0x00;

    
	// Timer/Counter 2 initialization  //1ms  
	TCCR2=0x0B;  //32分频
	OCR2=0xF9;

	TIMSK |= (1<<OCIE0)|(1<<OCIE2); //使能T0中断 
    
    mEN = 1;
    mCWW = 0; 

	work_mode = 0;
    
    Int_step = Str2Int(step);
    subdiv = Str2Int(divid);
    int_speed = Str2Int(str_speed); 
    delay_value = Str2Int(interval);
    
    exp_photos = Str2Int(images);
    photo_taken = 0;
    photo_left = exp_photos;
    
    run_type = Horizon;//水平运行
}
Ejemplo n.º 4
0
static int SelectProcRangeMatch(char *name1, char *name2, int min, int max, char **names, char **line)
{
    int i;
    long value;

    if (min == CF_NOINT || max == CF_NOINT)
    {
        return false;
    }

    if ((i = GetProcColumnIndex(name1, name2, names)) != -1)
    {
        value = Str2Int(line[i]);

        if (value == CF_NOINT)
        {
            CfOut(cf_inform, "", "Failed to extract a valid integer from %s => \"%s\" in process list\n", names[i],
                  line[i]);
            return false;
        }

        if (min <= value && value <= max)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    return false;
}
Ejemplo n.º 5
0
static TBuf<20> ExtractInt(const TDesC& aBuf, TInt& aExtractedInt)
	{
	TBuf<20> buf = aBuf.Right(aBuf.Length() - aBuf.Locate(':')-1);
	TBuf<5> handle;
	handle.FillZ();
	handle = buf.Left(buf.Locate(':'));
	aExtractedInt = Str2Int(handle);
	return buf;
	}
Ejemplo n.º 6
0
CAnonyTest::CAnonyTest():nNum(0), nStep(0), strTxHash(""), strAppRegId(""),regId("") {
	for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i) {
		string strArgv = boost::unit_test::framework::master_test_suite().argv[i];
		string::size_type pos = strArgv.find("-number=");
		if (string::npos != pos) {
			string strNum = strArgv.substr(pos + strlen("-number="), string::npos);
			nNum = Str2Int(strNum);
			break;
		}
	}
}
Ejemplo n.º 7
0
// return prop value in "read" json object if read success, else return err code in "err" object.
// NOTE: val is not used now.
OSStatus _property_read_create_response(struct mico_service_t *service_table, 
                                   const char *key, int val,
                                   json_object *out_read_obj, json_object *out_err_prop_obj)
{
  OSStatus err = kUnknownErr;
  int service_index = 0; 
  int property_index = 0;
  int iid = 0;
  int tmp_iid = 0;
  char iid_str[16] = {0};
  const char* pProertyType = NULL;
  
  require_action( service_table, exit, err = kParamErr);
  require_action( out_read_obj, exit, err = kParamErr);
  require_action( out_err_prop_obj, exit, err = kParamErr);
  
  Str2Int((uint8_t*)key, &iid);
  err = getIndexByIID(service_table, iid, &service_index, &property_index);
  require_noerr(err, exit);
  
  if( -1 == property_index){  // is a service
    tmp_iid = iid + 1;
    for(property_index = 0, pProertyType = service_table[service_index].properties[0].type; NULL != pProertyType;){
      // iid as response key
      memset(iid_str, '\0', sizeof(iid_str));
      Int2Str((uint8_t*)iid_str, tmp_iid);
      
      err = _property_read_create_response_by_index(service_table, iid_str, tmp_iid, 
                                               service_index, property_index, 
                                               out_read_obj, out_err_prop_obj);
      tmp_iid++;
      property_index++;
      pProertyType = service_table[service_index].properties[property_index].type;
    }
  }
  else{  // is a property
    err = _property_read_create_response_by_index(service_table, key, iid, 
                                             service_index, property_index, 
                                             out_read_obj, out_err_prop_obj);
  }
  
exit:
  if(kNotFoundErr == err){
    json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_NOT_FOUND));
  }
  if(kParamErr == err){
    json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_DATA_FORMAT_ERR));
  }
  return err;
}
Ejemplo n.º 8
0
	void VariableData::FromString(std::string const& str, Type type)
	{
		_type = type;
		switch (_type)
		{
		case VariableData::OBJTYPE_INTEGER:
			_i = Str2Int(str);
			break;
		case VariableData::OBJTYPE_REAL:
		case VariableData::OBJTYPE_UNREAL:
			_f = Str2Float(str);
			break;
		case VariableData::OBJTYPE_STRING:
			_s = str;
			break;
		default:
			break;
		}
	}
Ejemplo n.º 9
0
/*******************************************************************************
* Function Name  : GetIntegerInput
* Description    : Get an integer from the HyperTerminal
* Input          : - num: The inetger
* Output         : None
* Return         : 1: Correct
*                  0: Error
*******************************************************************************/
u32 GetIntegerInput(s32 * num)
{
  u8 inputstr[16];

  while (1)
  {
    GetInputString(inputstr);
    if (inputstr[0] == '\0') continue;
    if ((inputstr[0] == 'a' || inputstr[0] == 'A') && inputstr[1] == '\0'){
      SerialPutString("User Cancelled \r\n");
      return 0;
    }

    if (Str2Int(inputstr, num) == 0){
      SerialPutString("Error, Input again: \r\n");
    }else{
      return 1;
    }
  }
}
Ejemplo n.º 10
0
long Months2Seconds(int m)
{
    static long days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    long tot_days = 0;
    int this_month, i, month, year;

    if (m == 0)
    {
        return 0;
    }

    this_month = Month2Int(VMONTH);
    year = Str2Int(VYEAR);

    for (i = 0; i < m; i++)
    {
        month = (this_month - i) % 12;

        while (month < 0)
        {
            month += 12;
            year--;
        }

        if ((year % 4) && (month == 1))
        {
            tot_days += 29;
        }
        else
        {
            tot_days += days[month];
        }
    }

    return (long) tot_days *3600 * 24;
}
Ejemplo n.º 11
0
/**
  * @brief  Receive a file using the ymodem protocol.
  * @param  buf: Address of the first byte.
  * @retval The size of the file.
  */
int32_t Ymodem_Receive (uint8_t *buf)
{
    uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD], file_size[FILE_SIZE_LENGTH], *file_ptr, *buf_ptr;
    int32_t i, packet_length, session_done, file_done, packets_received, errors, session_begin, size = 0;
    uint32_t flashdestination, ramsource;

    /* Initialize flashdestination variable */
    flashdestination = APPLICATION_ADDRESS;

    for (session_done = 0, errors = 0, session_begin = 0; ;)
    {
        for (packets_received = 0, file_done = 0, buf_ptr = buf; ;)
        {
            switch (Receive_Packet(packet_data, &packet_length, NAK_TIMEOUT))
            {
            case 0:
                errors = 0;
                switch (packet_length)
                {
                /* Abort by sender */
                case - 1:
                    Send_Byte(ACK);
                    return 0;
                /* End of transmission */
                case 0:
                    Send_Byte(ACK);
                    file_done = 1;
                    break;
                /* Normal packet */
                default:
                    if ((packet_data[PACKET_SEQNO_INDEX] & 0xff) != (packets_received & 0xff))
                    {
                        Send_Byte(NAK);
                    }
                    else
                    {
                        if (packets_received == 0)
                        {
                            /* Filename packet */
                            if (packet_data[PACKET_HEADER] != 0)
                            {
                                /* Filename packet has valid data */
                                for (i = 0, file_ptr = packet_data + PACKET_HEADER; (*file_ptr != 0) && (i < FILE_NAME_LENGTH);)
                                {
                                    FileName[i++] = *file_ptr++;
                                }
                                FileName[i++] = '\0';
                                for (i = 0, file_ptr ++; (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH);)
                                {
                                    file_size[i++] = *file_ptr++;
                                }
                                file_size[i++] = '\0';
                                Str2Int(file_size, &size);

                                /* Test the size of the image to be sent */
                                /* Image size is greater than Flash size */
                                if (size > (USER_FLASH_SIZE + 1))
                                {
                                    /* End session */
                                    Send_Byte(CA);
                                    Send_Byte(CA);
                                    return -1;
                                }
                                /* erase user application area */
                                FLASH_If_Erase(APPLICATION_ADDRESS);
                                Send_Byte(ACK);
                                Send_Byte(CRC16);
                            }
                            /* Filename packet is empty, end session */
                            else
                            {
                                Send_Byte(ACK);
                                file_done = 1;
                                session_done = 1;
                                break;
                            }
                        }
                        /* Data packet */
                        else
                        {
                            memcpy(buf_ptr, packet_data + PACKET_HEADER, packet_length);
                            ramsource = (uint32_t)buf;

                            /* Write received data in Flash */
                            if (FLASH_If_Write(&flashdestination, (uint32_t*) ramsource, (uint16_t) packet_length/4)  == 0)
                            {
                                Send_Byte(ACK);
                            }
                            else /* An error occurred while writing to Flash memory */
                            {
                                /* End session */
                                Send_Byte(CA);
                                Send_Byte(CA);
                                return -2;
                            }
                        }
                        packets_received ++;
                        session_begin = 1;
                    }
                }
                break;
            case 1:
                Send_Byte(CA);
                Send_Byte(CA);
                return -3;
            default:
                if (session_begin > 0)
                {
                    errors ++;
                }
                if (errors > MAX_ERRORS)
                {
                    Send_Byte(CA);
                    Send_Byte(CA);
                    return 0;
                }
                Send_Byte(CRC16);
                break;
            }
            if (file_done != 0)
            {
                break;
            }
        }
        if (session_done != 0)
        {
            break;
        }
    }
    return (int32_t)size;
}
Ejemplo n.º 12
0
/**
  * @brief  Receive a file using the ymodem protocol
  * @param  buf: Address of the first byte
  * @retval The size of the file
  */
int32_t Ymodem_Receive (uint8_t *buf)
{
  uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD], file_size[FILE_SIZE_LENGTH], *file_ptr, *buf_ptr;
  int32_t i, j, packet_length, session_done, file_done, packets_received, errors, session_begin, size = 0;

  /* Initialize FlashDestination variable */
  FlashDestination = ApplicationAddress;

  for (session_done = 0, errors = 0, session_begin = 0; ;)
  {
    for (packets_received = 0, file_done = 0, buf_ptr = buf; ;)
    {
      switch (Receive_Packet(packet_data, &packet_length, NAK_TIMEOUT))
      {
        case 0:
          errors = 0;
          switch (packet_length)
          {
            /* Abort by sender */
            case - 1:
              Send_Byte(ACK);
              return 0;
            /* End of transmission */
            case 0:
              Send_Byte(ACK);
              file_done = 1;
              break;
            /* Normal packet */
            default:
              if ((packet_data[PACKET_SEQNO_INDEX] & 0xff) != (packets_received & 0xff))
              {
                Send_Byte(NAK);
              }
              else
              {
                if (packets_received == 0)
                {
                  /* Filename packet */
                  if (packet_data[PACKET_HEADER] != 0)
                  {
                    /* Filename packet has valid data */
                    for (i = 0, file_ptr = packet_data + PACKET_HEADER; (*file_ptr != 0) && (i < FILE_NAME_LENGTH);)
                    {
                      file_name[i++] = *file_ptr++;
                    }
                    file_name[i++] = '\0';
                    for (i = 0, file_ptr ++; (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH);)
                    {
                      file_size[i++] = *file_ptr++;
                    }
                    file_size[i++] = '\0';
                    Str2Int(file_size, &size);

                    /* Test the size of the image to be sent */
                    /* Image size is greater than Flash size */
                    if (size > (FLASH_SIZE - 1))
                    {
                      /* End session */
                      Send_Byte(CA);
                      Send_Byte(CA);
                      return -1;
                    }

                    /* Erase the needed pages where the user application will be loaded */
                    /* Define the number of page to be erased */
                    NbrOfPage = FLASH_PagesMask(size);

                    /* Erase the FLASH pages */
                    for (EraseCounter = 0; (EraseCounter < NbrOfPage) && (FLASHStatus == FLASH_COMPLETE); EraseCounter++)
                    {
                      FLASHStatus = FLASH_ErasePage(FlashDestination + (PageSize * EraseCounter));
                    }
                    Send_Byte(ACK);
                    Send_Byte(CRC16);
                  }
                  /* Filename packet is empty, end session */
                  else
                  {
                    Send_Byte(ACK);
                    file_done = 1;
                    session_done = 1;
                    break;
                  }
                }
                /* Data packet */
                else
                {
                  memcpy(buf_ptr, packet_data + PACKET_HEADER, packet_length);
                  RamSource = (uint32_t)buf;
                  for (j = 0;(j < packet_length) && (FlashDestination <  ApplicationAddress + size);j += 4)
                  {
                    /* Program the data received into STM32F10x Flash */
                    FLASH_ProgramWord(FlashDestination, *(uint32_t*)RamSource);

                    if (*(uint32_t*)FlashDestination != *(uint32_t*)RamSource)
                    {
                      /* End session */
                      Send_Byte(CA);
                      Send_Byte(CA);
                      return -2;
                    }
                    FlashDestination += 4;
                    RamSource += 4;
                  }
                  Send_Byte(ACK);
                }
                packets_received ++;
                session_begin = 1;
              }
          }
          break;
        case 1:
          Send_Byte(CA);
          Send_Byte(CA);
          return -3;
        default:
          if (session_begin > 0)
          {
            errors ++;
          }
          if (errors > MAX_ERRORS)
          {
            Send_Byte(CA);
            Send_Byte(CA);
            return 0;
          }
          Send_Byte(CRC16);
          break;
      }
      if (file_done != 0)
      {
        break;
      }
    }
    if (session_done != 0)
    {
      break;
    }
  }
  return (int32_t)size;
}
Ejemplo n.º 13
0
Archivo: syntax.c Proyecto: dnaeon/core
static void CheckParseIntRange(char *lval, char *s, const char *range)
{
    Item *split, *ip, *rangep;
    int n;
    long max = CF_LOWINIT, min = CF_HIGHINIT, val;
    char output[CF_BUFSIZE];

    if (s == NULL)
    {
        return;
    }

/* Numeric types are registered by range separated by comma str "min,max" */
    CfDebug("\nCheckParseIntRange(%s => %s/%s)\n", lval, s, range);

    if (*s == '[' || *s == '(')
    {
        ReportError("Range specification should not be enclosed in brackets - just \"a,b\"");
        return;
    }

    split = SplitString(range, ',');

    if ((n = ListLen(split)) != 2)
    {
        FatalError("INTERN:format specifier %s for irange rvalues is not ok for lval %s - got %d items", range, lval,
                   n);
    }

    sscanf(split->name, "%ld", &min);

    if (strcmp(split->next->name, "inf") == 0)
    {
        max = CF_INFINITY;
    }
    else
    {
        sscanf(split->next->name, "%ld", &max);
    }

    DeleteItemList(split);

    if (min == CF_HIGHINIT || max == CF_LOWINIT)
    {
        FatalError("INTERN: could not parse irange format specifier for int rvalues for lval %s", lval);
    }

    if (IsCf3VarString(s))
    {
        CfDebug("Validation: Unable to verify syntax of int \'%s\' due to variable expansion at this stage\n", s);
        return;
    }

    rangep = SplitString(s, ',');

    if ((n = ListLen(rangep)) != 2)
    {
        snprintf(output, CF_BUFSIZE,
                 "Int range format specifier for lval %s should be of form \"a,b\" but got %d items", lval, n);
        ReportError(output);
        DeleteItemList(rangep);
        return;
    }

    for (ip = rangep; ip != NULL; ip = ip->next)
    {
        val = Str2Int(ip->name);

        if (val > max || val < min)
        {
            snprintf(output, CF_BUFSIZE,
                     "Int range item on rhs of lval \'%s\' given as {%s => %ld} is out of bounds (should be in [%s])",
                     lval, s, val, range);
            ReportError(output);
            DeleteItemList(rangep);
            return;
        }
    }

    DeleteItemList(rangep);

    CfDebug("CheckParseIntRange - syntax verified\n\n");
}
Ejemplo n.º 14
0
Archivo: syntax.c Proyecto: dnaeon/core
static void CheckParseInt(char *lval, char *s, const char *range)
{
    Item *split;
    int n;
    long max = CF_LOWINIT, min = CF_HIGHINIT, val;
    char output[CF_BUFSIZE];

/* Numeric types are registered by range separated by comma str "min,max" */
    CfDebug("\nCheckParseInt(%s => %s/%s)\n", lval, s, range);

    if (s == NULL)
    {
        return;
    }

    split = SplitString(range, ',');

    if ((n = ListLen(split)) != 2)
    {
        FatalError("INTERN: format specifier for int rvalues is not ok for lval %s - got %d items", lval, n);
    }

    sscanf(split->name, "%ld", &min);

    if (strcmp(split->next->name, "inf") == 0)
    {
        max = CF_INFINITY;
    }
    else
    {
        sscanf(split->next->name, "%ld", &max);
    }

    DeleteItemList(split);

    if (min == CF_HIGHINIT || max == CF_LOWINIT)
    {
        FatalError("INTERN: could not parse format specifier for int rvalues for lval %s", lval);
    }

    if (IsCf3VarString(s))
    {
        CfDebug("Validation: Unable to verify syntax of int \'%s\' due to variable expansion at this stage\n", s);
        return;
    }

    val = Str2Int(s);

    if (val == CF_NOINT)
    {
        snprintf(output, CF_BUFSIZE, "Int item on rhs of lval \'%s\' given as \'%s\' could not be parsed", lval, s);
        ReportError(output);
        return;
    }

    if (val > max || val < min)
    {
        snprintf(output, CF_BUFSIZE,
                 "Int item on rhs of lval \'%s\' given as {%s => %ld} is out of bounds (should be in [%s])", lval, s,
                 val, range);
        ReportError(output);
        return;
    }

    CfDebug("CheckParseInt - syntax verified\n\n");
}
Ejemplo n.º 15
0
static int NewSQLColumns(char *table, Rlist *columns, char ***name_table, char ***type_table, int **size_table,
                         int **done)
{
    int i, no_of_cols = RlistLen(columns);
    Rlist *cols, *rp;

    *name_table = (char **) xmalloc(sizeof(char *) * (no_of_cols + 1));
    *type_table = (char **) xmalloc(sizeof(char *) * (no_of_cols + 1));
    *size_table = (int *) xmalloc(sizeof(int) * (no_of_cols + 1));
    *done = (int *) xmalloc(sizeof(int) * (no_of_cols + 1));

    for (i = 0, rp = columns; rp != NULL; rp = rp->next, i++)
    {
        (*done)[i] = 0;

        cols = SplitStringAsRList((char *) rp->item, ',');

        if (!cols)
        {
            CfOut(cf_error, "", "No columns promised for table \"%s\" - makes no sense", table);
            return false;
        }

        if (cols->item == NULL)
        {
            CfOut(cf_error, "", "Malformed column promise for table \"%s\" - found not even a name", table);
            free(*name_table);
            free(*type_table);
            free(*size_table);
            free(*done);
            return false;
        }

        (*name_table)[i] = xstrdup((char *) cols->item);

        if (cols->next == NULL)
        {
            CfOut(cf_error, "", "Malformed column \"%s\" promised for table \"%s\" - missing a type", (*name_table)[i],
                  table);
            free(*name_table);
            free(*type_table);
            free(*size_table);
            free(*done);
            return false;
        }

        (*type_table)[i] = xstrdup(cols->next->item);

        if (cols->next->next == NULL)
        {
            (*size_table)[i] = 0;
        }
        else
        {
            if (cols->next->next->item)
            {
                (*size_table)[i] = Str2Int(cols->next->next->item);
            }
            else
            {
                (*size_table)[i] = 0;
            }
        }

        DeleteRlist(cols);
    }

    return true;
}
Ejemplo n.º 16
0
static int VerifyTablePromise(CfdbConn *cfdb, char *table_path, Rlist *columns, Attributes a, Promise *pp)
{
    char name[CF_MAXVARSIZE], type[CF_MAXVARSIZE], query[CF_MAXVARSIZE], table[CF_MAXVARSIZE], db[CF_MAXVARSIZE];
    int i, count, size, no_of_cols, *size_table, *done, identified, retval = true;
    char **name_table, **type_table;

    CfOut(cf_verbose, "", " -> Verifying promised table structure for \"%s\"", table_path);

    if (!ValidateSQLTableName(table_path, db, table))
    {
        CfOut(cf_error, "",
              " !! The structure of the promiser did not match that for an SQL table, i.e. \"database.table\"\n");
        return false;
    }
    else
    {
        CfOut(cf_verbose, "", " -> Assuming database \"%s\" with table \"%s\"", db, table);
    }

/* Verify the existence of the tables within the database */

    if (!TableExists(cfdb, table))
    {
        CfOut(cf_error, "", " !! The database did not contain the promised table \"%s\"\n", table_path);

        if ((a.database.operation) && (strcmp(a.database.operation, "create") == 0))
        {
            if ((!DONTDO) && ((a.transaction.action) != cfa_warn))
            {
                cfPS(cf_error, CF_CHG, "", pp, a, " -> Database.table %s doesn't seem to exist, creating\n",
                     table_path);
                return CreateTableColumns(cfdb, table, columns, a, pp);
            }
            else
            {
                CfOut(cf_error, "", " -> Database.table %s doesn't seem to exist, but only a warning was promised\n",
                      table_path);
            }
        }

        return false;
    }

/* Get a list of the columns in the table */

    QueryTableColumns(query, db, table);
    CfNewQueryDB(cfdb, query);

    if (cfdb->maxcolumns != 3)
    {
        cfPS(cf_error, CF_FAIL, "", pp, a, "Could not make sense of the columns");
        CfDeleteQuery(cfdb);
        return false;
    }

/* Assume that the Rlist has been validated and consists of a,b,c */

    count = 0;
    no_of_cols = RlistLen(columns);

    if (!NewSQLColumns(table, columns, &name_table, &type_table, &size_table, &done))
    {
        cfPS(cf_error, CF_FAIL, "", pp, a, "Could not make sense of the columns");
        return false;
    }

/* Obtain columns from the named table - if any */

    while (CfFetchRow(cfdb))
    {
        char *sizestr;

        name[0] = '\0';
        type[0] = '\0';
        size = CF_NOINT;

        strlcpy(name, CfFetchColumn(cfdb, 0), CF_MAXVARSIZE);
        strlcpy(type, CfFetchColumn(cfdb, 1), CF_MAXVARSIZE);
        ToLowerStrInplace(type);
        sizestr = CfFetchColumn(cfdb, 2);

        if (sizestr)
        {
            size = Str2Int(sizestr);
        }

        CfOut(cf_verbose, "", "    ... discovered column (%s,%s,%d)", name, type, size);

        if (sizestr && (size == CF_NOINT))
        {
            cfPS(cf_verbose, CF_NOP, "", pp, a,
                 " !! Integer size of SQL datatype could not be determined or was not specified - invalid promise.");
            DeleteSQLColumns(name_table, type_table, size_table, done, no_of_cols);
            CfDeleteQuery(cfdb);
            return false;
        }

        identified = false;

        for (i = 0; i < no_of_cols; i++)
        {
            if (done[i])
            {
                continue;
            }

            if (strcmp(name, name_table[i]) == 0)
            {
                CheckSQLDataType(type, type_table[i], pp);

                if (size != size_table[i])
                {
                    cfPS(cf_error, CF_FAIL, "", pp, a,
                         " !! Promised column \"%s\" in database.table \"%s\" has a non-matching array size (%d != %d)",
                         name, table_path, size, size_table[i]);
                }
                else
                {
                    CfOut(cf_verbose, "", " -> Promised column \"%s\" in database.table \"%s\" is as promised", name,
                          table_path);
                }

                count++;
                done[i] = true;
                identified = true;
                break;
            }
        }

        if (!identified)
        {
            cfPS(cf_error, CF_FAIL, "", pp, a,
                 "Column \"%s\" found in database.table \"%s\" is not part of its promise.", name, table_path);

            if ((a.database.operation) && (strcmp(a.database.operation, "drop") == 0))
            {
                cfPS(cf_error, CF_FAIL, "", pp, a,
                     "Cfengine will not promise to repair this, as the operation is potentially too destructive.");
                // Future allow deletion?
            }

            retval = false;
        }
    }

    CfDeleteQuery(cfdb);

/* Now look for deviations - only if we have promised to create missing */

    if ((a.database.operation) && (strcmp(a.database.operation, "drop") == 0))
    {
        return retval;
    }

    if (count != no_of_cols)
    {
        for (i = 0; i < no_of_cols; i++)
        {
            if (!done[i])
            {
                CfOut(cf_error, "", " !! Promised column \"%s\" missing from database table %s", name_table[i],
                      pp->promiser);

                if ((!DONTDO) && ((a.transaction.action) != cfa_warn))
                {
                    if (size_table[i] > 0)
                    {
                        snprintf(query, CF_MAXVARSIZE - 1, "ALTER TABLE %s ADD %s %s(%d)", table, name_table[i],
                                 type_table[i], size_table[i]);
                    }
                    else
                    {
                        snprintf(query, CF_MAXVARSIZE - 1, "ALTER TABLE %s ADD %s %s", table, name_table[i],
                                 type_table[i]);
                    }

                    CfVoidQueryDB(cfdb, query);
                    cfPS(cf_error, CF_CHG, "", pp, a, " !! Adding promised column \"%s\" to database table %s",
                         name_table[i], table);
                    retval = true;
                }
                else
                {
                    cfPS(cf_error, CF_WARN, "", pp, a,
                         " !! Promised column \"%s\" missing from database table %s but only a warning was promised",
                         name_table[i], table);
                    retval = false;
                }
            }
        }
    }

    DeleteSQLColumns(name_table, type_table, size_table, done, no_of_cols);

    return retval;
}
Ejemplo n.º 17
0
void KeepControlPromises()
    
{ struct Constraint *cp;
  char rettype;
  void *retval;
  struct Rlist *rp;

for (cp = ControlBodyConstraints(cf_agent); cp != NULL; cp=cp->next)
   {
   if (IsExcluded(cp->classes))
      {
      continue;
      }

   if (GetVariable("control_common",cp->lval,&retval,&rettype) != cf_notype)
      {
      /* Already handled in generic_agent */
      continue;
      }

   if (GetVariable("control_agent",cp->lval,&retval,&rettype) == cf_notype)
      {
      CfOut(cf_error,"","Unknown lval %s in agent control body",cp->lval);
      continue;
      }
            
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_maxconnections].lval) == 0)
      {
      CFA_MAXTHREADS = (int)Str2Int(retval);
      CfOut(cf_verbose,"","SET maxconnections = %d\n",CFA_MAXTHREADS);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_checksum_alert_time].lval) == 0)
      {
      CF_PERSISTENCE = (int)Str2Int(retval);
      CfOut(cf_verbose,"","SET checksum_alert_time = %d\n",CF_PERSISTENCE);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_agentfacility].lval) == 0)
      {
      SetFacility(retval);
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_agentaccess].lval) == 0)
      {
      ACCESSLIST = (struct Rlist *) retval;
      CheckAgentAccess(ACCESSLIST);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_refresh_processes].lval) == 0)
      {
      struct Rlist *rp;

      if (VERBOSE)
         {
         printf("%s> SET refresh_processes when starting: ",VPREFIX);

         for (rp  = (struct Rlist *) retval; rp != NULL; rp = rp->next)
            {
            printf(" %s",(char *)rp->item);
            PrependItem(&PROCESSREFRESH,rp->item,NULL);
            }

         printf("\n");
         }
      
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_abortclasses].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET Abort classes from ...\n");
      
      for (rp  = (struct Rlist *) retval; rp != NULL; rp = rp->next)
         {
         char name[CF_MAXVARSIZE] = "";
         strncpy(name, rp->item, CF_MAXVARSIZE - 1);
         CanonifyNameInPlace(name);

         if (!IsItemIn(ABORTHEAP,name))
            {
            AppendItem(&ABORTHEAP,name,cp->classes);
            }
         }
      
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_abortbundleclasses].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET Abort bundle classes from ...\n");
      
      for (rp  = (struct Rlist *) retval; rp != NULL; rp = rp->next)
         {
         char name[CF_MAXVARSIZE] = "";
         strncpy(name, rp->item, CF_MAXVARSIZE - 1);
         CanonifyNameInPlace(name);

         if (!IsItemIn(ABORTBUNDLEHEAP,name))
            {
            AppendItem(&ABORTBUNDLEHEAP,name,cp->classes);
            }
         }
      
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_addclasses].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","-> Add classes ...\n");
      
      for (rp  = (struct Rlist *) retval; rp != NULL; rp = rp->next)
         {
         CfOut(cf_verbose,""," -> ... %s\n",rp->item);
         NewClass(rp->item);
         }
      
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_auditing].lval) == 0)
      {
      AUDIT = GetBoolean(retval);
      CfOut(cf_verbose,"","SET auditing = %d\n",AUDIT);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_alwaysvalidate].lval) == 0)
      {
      ALWAYS_VALIDATE = GetBoolean(retval);
      CfOut(cf_verbose,"","SET alwaysvalidate = %d\n",ALWAYS_VALIDATE);
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_secureinput].lval) == 0)
      {
      CFPARANOID = GetBoolean(retval);
      CfOut(cf_verbose,"","SET secure input = %d\n",CFPARANOID);
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_binarypaddingchar].lval) == 0)
      {
      PADCHAR = *(char *)retval;
      CfOut(cf_verbose,"","SET binarypaddingchar = %c\n",PADCHAR);
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_bindtointerface].lval) == 0)
      {
      strncpy(BINDINTERFACE,retval,CF_BUFSIZE-1);
      CfOut(cf_verbose,"","SET bindtointerface = %s\n",BINDINTERFACE);
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_hashupdates].lval) == 0)
      {
      CHECKSUMUPDATES = GetBoolean(retval);
      CfOut(cf_verbose,"","SET ChecksumUpdates %d\n",CHECKSUMUPDATES);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_exclamation].lval) == 0)
      {
      EXCLAIM = GetBoolean(retval);
      CfOut(cf_verbose,"","SET exclamation %d\n",EXCLAIM);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_childlibpath].lval) == 0)
      {
      char output[CF_BUFSIZE];
      snprintf(output,CF_BUFSIZE,"LD_LIBRARY_PATH=%s",(char *)retval);
      if (putenv(strdup(output)) == 0)
         {
         CfOut(cf_verbose,"","Setting %s\n",output);
         }
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_defaultcopytype].lval) == 0)
      {
      DEFAULT_COPYTYPE = (char *)retval;
      CfOut(cf_verbose,"","SET defaultcopytype = %c\n",DEFAULT_COPYTYPE);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_fsinglecopy].lval) == 0)
      {
      SINGLE_COPY_LIST = (struct Rlist *)retval;
      CfOut(cf_verbose,"","SET file single copy list\n");
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_fautodefine].lval) == 0)
      {
      AUTO_DEFINE_LIST = (struct Rlist *)retval;
      CfOut(cf_verbose,"","SET file auto define list\n");
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_dryrun].lval) == 0)
      {
      DONTDO = GetBoolean(retval);
      CfOut(cf_verbose,"","SET dryrun = %c\n",DONTDO);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_inform].lval) == 0)
      {
      INFORM = GetBoolean(retval);
      CfOut(cf_verbose,"","SET inform = %c\n",INFORM);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_verbose].lval) == 0)
      {
      VERBOSE = GetBoolean(retval);
      CfOut(cf_verbose,"","SET inform = %c\n",VERBOSE);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_repository].lval) == 0)
      {
      VREPOSITORY = strdup(retval);
      CfOut(cf_verbose,"","SET repository = %s\n",VREPOSITORY);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_skipidentify].lval) == 0)
      {
      SKIPIDENTIFY = GetBoolean(retval);
      CfOut(cf_verbose,"","SET skipidentify = %d\n",SKIPIDENTIFY);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_suspiciousnames].lval) == 0)
      {

      for (rp  = (struct Rlist *) retval; rp != NULL; rp = rp->next)
	{
	PrependItem(&SUSPICIOUSLIST,rp->item,NULL);
	CfOut(cf_verbose,"", "-> Concidering %s as suspicious file", rp->item);
	}

      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_repchar].lval) == 0)
      {
      REPOSCHAR = *(char *)retval;
      CfOut(cf_verbose,"","SET repchar = %c\n",REPOSCHAR);
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_mountfilesystems].lval) == 0)
      {
      CF_MOUNTALL = GetBoolean(retval);
      CfOut(cf_verbose,"","SET mountfilesystems = %d\n",CF_MOUNTALL);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_editfilesize].lval) == 0)
      {
      EDITFILESIZE = Str2Int(retval);
      CfOut(cf_verbose,"","SET EDITFILESIZE = %d\n",EDITFILESIZE);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_ifelapsed].lval) == 0)
      {
      VIFELAPSED = Str2Int(retval);
      CfOut(cf_verbose,"","SET ifelapsed = %d\n",VIFELAPSED);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_expireafter].lval) == 0)
      {
      VEXPIREAFTER = Str2Int(retval);
      CfOut(cf_verbose,"","SET ifelapsed = %d\n",VEXPIREAFTER);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_timeout].lval) == 0)
      {
      CONNTIMEOUT = Str2Int(retval);
      CfOut(cf_verbose,"","SET timeout = %d\n",CONNTIMEOUT);
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_max_children].lval) == 0)
      {
      CFA_BACKGROUND_LIMIT = Str2Int(retval);
      CfOut(cf_verbose,"","SET MAX_CHILDREN = %d\n",CFA_BACKGROUND_LIMIT);
      if (CFA_BACKGROUND_LIMIT > 10)
         {
         CfOut(cf_error,"","Silly value for max_children in agent control promise (%d > 10)",CFA_BACKGROUND_LIMIT);
         CFA_BACKGROUND_LIMIT = 1;
         }
      continue;
      }
   
   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_syslog].lval) == 0)
      {
      LOGGING = GetBoolean(retval);
      CfOut(cf_verbose,"","SET syslog = %d\n",LOGGING);
      continue;
      }

   if (strcmp(cp->lval,CFA_CONTROLBODY[cfa_environment].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET environment variables from ...\n");
      
      for (rp  = (struct Rlist *) retval; rp != NULL; rp = rp->next)
         {
         if (putenv(rp->item) != 0)
            {
            CfOut(cf_error, "putenv", "Failed to set environment variable %s", rp->item);
            }
         }
      
      continue;
      }
   }

if (GetVariable("control_common",CFG_CONTROLBODY[cfg_lastseenexpireafter].lval,&retval,&rettype) != cf_notype)
   {
   LASTSEENEXPIREAFTER = Str2Int(retval);
   }

if (GetVariable("control_common",CFG_CONTROLBODY[cfg_fips_mode].lval,&retval,&rettype) != cf_notype)
   {
   FIPS_MODE = GetBoolean(retval);
   CfOut(cf_verbose,"","SET FIPS_MODE = %d\n",FIPS_MODE);
   }

if (GetVariable("control_common",CFG_CONTROLBODY[cfg_syslog_port].lval,&retval,&rettype) != cf_notype)
   {
   SYSLOGPORT = (unsigned short)Str2Int(retval);
   CfOut(cf_verbose,"","SET syslog_port to %d",SYSLOGPORT);
   }

if (GetVariable("control_common",CFG_CONTROLBODY[cfg_syslog_host].lval,&retval,&rettype) != cf_notype)
   {   
   strncpy(SYSLOGHOST,Hostname2IPString(retval),CF_MAXVARSIZE-1);
   CfOut(cf_verbose,"","SET syslog_host to %s",SYSLOGHOST);
   }

#ifdef HAVE_NOVA
Nova_Initialize();
#endif
}
Ejemplo n.º 18
0
/**
  * @brief  Display the Main Menu on HyperTerminal
  * @param  None
  * @retval None
  */
void Main_Menu(void)
{
  char cmdbuf [CMD_STRING_SIZE] = {0}, cmdname[15] = {0};     /* command input buffer        */
  int i, j;                                       /* index for command buffer    */
  int targetFlash;
  char startAddressStr[10], endAddressStr[10];
  int32_t startAddress, endAddress;
  bool inputFlashArea = false;

  while (1)  {                                    /* loop forever                */
    printf ("\n\rWiFiMCU> ");
    getline (&cmdbuf[0], sizeof (cmdbuf));        /* input command line          */

    for (i = 0; cmdbuf[i] == ' '; i++);           /* skip blanks on head         */
    for (; cmdbuf[i] != 0; i++)  {                /* convert to upper characters */
      cmdbuf[i] = toupper(cmdbuf[i]);
    }

    for (i = 0; cmdbuf[i] == ' '; i++);        /* skip blanks on head         */
    for(j=0; cmdbuf[i] != ' '&&cmdbuf[i] != 0; i++,j++)  {         /* find command name       */
      cmdname[j] = cmdbuf[i];
    }
    cmdname[j] = '\0';

    /***************** Command "0" or "BOOTUPDATE": Update the application  *************************/
    if(strcmp(cmdname, "BOOTUPDATE") == 0 || strcmp(cmdname, "0") == 0) {
      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead Bootloader only...\n\r");
        MicoFlashInitialize(MICO_FLASH_FOR_BOOT);
        SerialUpload(MICO_FLASH_FOR_BOOT, BOOT_START_ADDRESS, "BootLoaderImage.bin", BOOT_FLASH_SIZE);
        MicoFlashFinalize(MICO_FLASH_FOR_BOOT);
        continue;
      }
      printf ("\n\rUpdating Bootloader...\n\r");
      SerialDownload(MICO_FLASH_FOR_BOOT, BOOT_START_ADDRESS, BOOT_FLASH_SIZE);
    }

    /***************** Command "1" or "FWUPDATE": Update the MICO application  *************************/
    else if(strcmp(cmdname, "FWUPDATE") == 0 || strcmp(cmdname, "1") == 0)	{
      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead MICO application only...\n\r");
        MicoFlashInitialize(MICO_FLASH_FOR_APPLICATION);
        SerialUpload(MICO_FLASH_FOR_APPLICATION, APPLICATION_START_ADDRESS, "ApplicationImage.bin", APPLICATION_FLASH_SIZE);
        MicoFlashFinalize(MICO_FLASH_FOR_APPLICATION);
        continue;
      }
      printf ("\n\rUpdating MICO application...\n\r");
      SerialDownload(MICO_FLASH_FOR_APPLICATION, APPLICATION_START_ADDRESS, APPLICATION_FLASH_SIZE); 							   	
    }

    /***************** Command "2" or "DRIVERUPDATE": Update the RF driver  *************************/

    else if(strcmp(cmdname, "DRIVERUPDATE") == 0 || strcmp(cmdname, "2") == 0) {
#ifdef MICO_FLASH_FOR_DRIVER
      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead RF driver only...\n\r");
        MicoFlashInitialize(MICO_FLASH_FOR_DRIVER);
        SerialUpload(MICO_FLASH_FOR_DRIVER, DRIVER_START_ADDRESS, "DriverImage.bin", DRIVER_FLASH_SIZE);
        MicoFlashFinalize(MICO_FLASH_FOR_DRIVER);
        continue;
      }
      printf ("\n\rUpdating RF driver...\n\r");
      SerialDownload(MICO_FLASH_FOR_DRIVER, DRIVER_START_ADDRESS, DRIVER_FLASH_SIZE);  
#else
      printf ("\n\rNo independ flash memory for RF driver, exiting...\n\r");
#endif
    }

    /***************** Command "3" or "PARAUPDATE": Update the application  *************************/
    else if(strcmp(cmdname, "PARAUPDATE") == 0 || strcmp(cmdname, "3") == 0)  {
      if (findCommandPara(cmdbuf, "e", NULL, 0) != -1){
        printf ("\n\rErasing MICO settings only...\n\r");
        MicoFlashInitialize(MICO_FLASH_FOR_PARA);
        MicoFlashErase(MICO_FLASH_FOR_PARA, PARA_START_ADDRESS, PARA_END_ADDRESS);
        MicoFlashFinalize(MICO_FLASH_FOR_PARA);
        continue;
      }
      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead MICO settings only...\n\r");
        MicoFlashInitialize(MICO_FLASH_FOR_PARA);
        SerialUpload(MICO_FLASH_FOR_PARA, PARA_START_ADDRESS, "DriverImage.bin", PARA_FLASH_SIZE);
        MicoFlashFinalize(MICO_FLASH_FOR_PARA);
        continue;
      }
      printf ("\n\rUpdating MICO settings...\n\r");
      SerialDownload(MICO_FLASH_FOR_PARA, PARA_START_ADDRESS, PARA_FLASH_SIZE);                        
    }

    /***************** Command "4" or "FLASHUPDATE": : Update the Flash  *************************/
    else if(strcmp(cmdname, "FLASHUPDATE") == 0 || strcmp(cmdname, "4") == 0) {
      if (findCommandPara(cmdbuf, "i", NULL, 0) != -1){
        targetFlash = MICO_INTERNAL_FLASH;
      }else if(findCommandPara(cmdbuf, "s", NULL, 200) != -1){
        targetFlash = MICO_SPI_FLASH;
      }else{
        printf ("\n\rUnkown target type! Exiting...\n\r");
        continue;
      }

      inputFlashArea = false;
      if (findCommandPara(cmdbuf, "start", startAddressStr, 10) != -1){
        if(Str2Int((uint8_t *)startAddressStr, &startAddress)==0){ //Found Flash start address
          printf ("\n\rIllegal start address.\n\r");
          continue;
        }else{
          if (findCommandPara(cmdbuf, "end", endAddressStr, 10) != -1){ //Found Flash end address
            if(Str2Int((uint8_t *)endAddressStr, &endAddress)==0){
              printf ("\n\rIllegal end address.\n\r");
              continue;
            }else{
              inputFlashArea = true;
            }
          }else{
            printf ("\n\rFlash end address not found.\n\r");
            continue;
          }
        }
      }

      if(endAddress<startAddress && inputFlashArea == true) {
        printf ("\n\rIllegal flash address.\n\r");
        continue;
      }

      if(inputFlashArea != true){
        if(targetFlash == MICO_INTERNAL_FLASH){
          startAddress = platform_flash_peripherals[MICO_INTERNAL_FLASH].flash_start_addr ;
          endAddress = platform_flash_peripherals[MICO_INTERNAL_FLASH].flash_start_addr 
                     + platform_flash_peripherals[MICO_INTERNAL_FLASH].flash_length - 1;
        }else{
#ifdef USE_MICO_SPI_FLASH        
          startAddress = platform_flash_peripherals[MICO_SPI_FLASH].flash_start_addr ;
          endAddress = platform_flash_peripherals[MICO_SPI_FLASH].flash_start_addr 
                     + platform_flash_peripherals[MICO_SPI_FLASH].flash_length - 1;
#else
          printf ("\n\rSPI Flash not exist\n\r");
          continue;
#endif
        }
      }

      if (findCommandPara(cmdbuf, "e", NULL, 0) != -1){
        printf ("\n\rErasing flash content From 0x%x to 0x%x\n\r", startAddress, endAddress);
        MicoFlashInitialize((mico_flash_t)targetFlash);
        MicoFlashErase((mico_flash_t)targetFlash, startAddress, endAddress);
        MicoFlashFinalize((mico_flash_t)targetFlash);
        continue;
      }

      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead flash content From 0x%x to 0x%x\n\r", startAddress, endAddress);
        MicoFlashInitialize((mico_flash_t)targetFlash);
        SerialUpload((mico_flash_t)targetFlash, startAddress, "FlashImage.bin", endAddress-startAddress+1);
        MicoFlashFinalize((mico_flash_t)targetFlash);
        continue;
      }

      printf ("\n\rUpdating flash content From 0x%x to 0x%x\n\r", startAddress, endAddress);
      SerialDownload((mico_flash_t)targetFlash, startAddress, endAddress-startAddress+1);                           
    }

    /***************** Command: Reboot *************************/
    else if(strcmp(cmdname, "MEMORYMAP") == 0 || strcmp(cmdname, "5") == 0)  {
#if defined MICO_FLASH_FOR_UPDATE && defined MICO_FLASH_FOR_DRIVER
      printf(MEMMAP, flash_name[MICO_FLASH_FOR_BOOT],BOOT_START_ADDRESS,BOOT_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_PARA], PARA_START_ADDRESS, PARA_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_APPLICATION], APPLICATION_START_ADDRESS, APPLICATION_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_UPDATE], UPDATE_START_ADDRESS, UPDATE_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_DRIVER], DRIVER_START_ADDRESS, DRIVER_END_ADDRESS);
#endif
#if !defined MICO_FLASH_FOR_UPDATE && defined MICO_FLASH_FOR_DRIVER
      printf(MEMMAP, flash_name[MICO_FLASH_FOR_BOOT],BOOT_START_ADDRESS,BOOT_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_PARA], PARA_START_ADDRESS, PARA_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_APPLICATION], APPLICATION_START_ADDRESS, APPLICATION_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_DRIVER], DRIVER_START_ADDRESS, DRIVER_END_ADDRESS);
#endif
#if defined MICO_FLASH_FOR_UPDATE && !defined MICO_FLASH_FOR_DRIVER
      printf(MEMMAP, flash_name[MICO_FLASH_FOR_BOOT],BOOT_START_ADDRESS,BOOT_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_PARA], PARA_START_ADDRESS, PARA_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_APPLICATION], APPLICATION_START_ADDRESS, APPLICATION_END_ADDRESS);
#endif
#if !defined MICO_FLASH_FOR_UPDATE && !defined MICO_FLASH_FOR_DRIVER
      printf(MEMMAP, flash_name[MICO_FLASH_FOR_BOOT],BOOT_START_ADDRESS,BOOT_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_PARA], PARA_START_ADDRESS, PARA_END_ADDRESS,\
                     flash_name[MICO_FLASH_FOR_APPLICATION], APPLICATION_START_ADDRESS, APPLICATION_END_ADDRESS);
#endif 
    }
    /***************** Command: Excute the application *************************/
    else if(strcmp(cmdname, "BOOT") == 0 || strcmp(cmdname, "6") == 0)	{
      printf ("\n\rBooting.......\n\r");
      startApplication();
    }

   /***************** Command: Reboot *************************/
    else if(strcmp(cmdname, "REBOOT") == 0 || strcmp(cmdname, "7") == 0)  {
      printf ("\n\rReBooting.......\n\r");
      MicoSystemReboot();
    break;                              
  }

	else if(strcmp(cmdname, "HELP") == 0 || strcmp(cmdname, "?") == 0)	{
    printf ( menu, MODEL, Bootloader_REVISION );                       /* display command menu        */
		break;
	}

	else if(strcmp(cmdname, "") == 0 )	{                         
		break;
	}
	else{
	    printf (ERROR_STR, "UNKNOWN COMMAND");
		break;
	}
  }
}
Ejemplo n.º 19
0
/*******************************************************************************
* 函数名称: download_program_to_meter
* 输入参数: 
* 输出参数: 
* --返回值: 
* 函数功能: --
*******************************************************************************/
static void download_program_to_meter(void)
{
    uint32_t status = 0u; 
    uint8_t tick_C = 0u;
    uint8_t Rev_flag = 0u;
    uint8_t read_flash_check_flag = 0u;
    uint8_t file_size[FILE_SIZE_LENGTH] = {0};
    
    /* wait for meter send 'C', meter printf something before send 'C' */
    delay_ms(5000);  /* 存在很低的概率, 会出现在进入升级的时候会停滞几秒 */
    
    MFS_UARTErrorClr(UartUSBCh);  //CLR error flag
    MFS_UARTSWRst(UART52_Ch);  //reset UART
    UARTConfigMode(UART52_Ch, &tUARTModeConfigT);
    MFS_UARTEnableRX(UART52_Ch);
    MFS_UARTEnableTX(UART52_Ch);
    
    //SerialPutString("\n\n\rSelect Receive File ... \n\r");
    
    Rev_flag = Receive_Byte(UART52_Ch , &tick_C, Rev_timeout); 
    if (0u == Rev_flag)
    {
        if (tick_C == CRC16)
        {
            printf("Rev C. \r\n");
        }    
    }    
    else
    {
		SerialPutString("\r\n no Rev 'C' .\r\n");  
    }    
    
    if (tick_C == CRC16)
    {
        SerialPutString("downlod image .bin ... \r\n");
        
        read_flash_check_flag = 0u;
        read_flash_check_flag = MX25L3206_Read((uint8_t*)(file_size),
                                               (uint32_t)FLASH_IMAGE_SIZE_ADDRESS,
                                               FILE_SIZE_LENGTH);
        if (OK != read_flash_check_flag)
        {
            __NOP();
        }  
        else
        {
            Str2Int(file_size, &flash_image_size);  /* str to hex */

            /* Transmit the flash image through ymodem protocol */
            status = Ymodem_Transmit((uint8_t*)ApplicationAddress,   //!!!!Note
                     (const uint8_t*)"DownloadFlashImage.bin",
                     flash_image_size);  /* , ,FLASH_IMAGE_MAX_SIZE */

            MFS_UARTDisableRX(UART52_Ch);  //

            if (status != 0) 
            {
                SerialPutString("\n\rError Occured while Transmitting File\n\r");
                oneSound(10, 300);  /* BUZZER 201 error buzz */
            }
            else
            {
                SerialPutString("\n\rFile Trasmitted Successfully \n\r");
                oneSound(10, 0);  /* BUZZER 201 buzz */
            }
        }//end if flash check    
    }
    else
    {
        SerialPutString("\r\n\nAborted by user or no Rev 'C' .\n\r");  
        oneSound(10, 300);  /* BUZZER 201 error buzz */
        //while(1);  //test!!! 
    }
    
    bFM3_GPIO_PDOR0_PD = 1u; /* LED 201 light off */
    bFM3_GPIO_PDOR0_PC = 1u; /* LED 202 light off */
    MFS_UARTDisableRX(UART52_Ch);
    MFS_UARTDisableTX(UART52_Ch);
}
Ejemplo n.º 20
0
OSStatus _property_write_create_response(struct mico_service_t *service_table, 
                                    char *key, json_object *val,
                                    json_object *out_write_obj, json_object *out_err_prop_obj)
{
  OSStatus err = kUnknownErr;
  int iid = 0;
  int service_index = 0;
  int property_index = 0;
  int ret = 0;
  
  int int_value = 0;
  float float_value = 0;
  bool boolean_value = false;
  const char *set_string = NULL;
  int set_string_len = 0;
  
  require_action(service_table, exit, err = kParamErr);
  require_action(key, exit, err = kParamErr);
  require_action(val, exit, err = kParamErr);
  require_action(out_write_obj, exit, err = kParamErr);
  require_action(out_err_prop_obj, exit, err = kParamErr);
  
  Str2Int((uint8_t*)key, &iid);
  //properties_log("properties write iid=%d.", iid);
  
  err = FindPropertyByIID(service_table, iid, &service_index, &property_index);
  require_noerr(err, exit);
  
  if( MICO_PROP_PERMS_WRITABLE (service_table[service_index].properties[property_index].perms) ){
    switch(service_table[service_index].properties[property_index].format){
    case MICO_PROP_TYPE_INT:{
      //properties_log("prop got: %s, iid=%d, value=%d", 
      //               service_table[service_index].properties[property_index].type, iid, 
      //               *((int*)service_table[service_index].properties[property_index].value));
      // property set (hardware operation)
      if(NULL != service_table[service_index].properties[property_index].set){
        int_value = json_object_get_int(val);
        ret = service_table[service_index].properties[property_index].set(&service_table[service_index].properties[property_index],
                                                                          service_table[service_index].properties[property_index].arg,
                                                                          (void*)&int_value, sizeof(int));
        if (0 == ret){  // set ok, update property value
          *((int*)service_table[service_index].properties[property_index].value) =  int_value;
          json_object_object_add(out_write_obj, key, json_object_new_int(int_value));
          err = kNoErr;
        }
        else{  // return write err status
          json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_WRITE_FAILED));
          err = kWriteErr;
        }
      }
      else{ // no set func err
        json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_NO_SET_FUNC));
        err = kWriteErr;
      }
      break;
    }
    case MICO_PROP_TYPE_FLOAT:{
      //properties_log("prop got: %s, iid=%d, value=%f", 
      //               service_table[service_index].properties[property_index].type, iid, 
      //               *((float*)service_table[service_index].properties[property_index].value));
      // property set(hardware operation)
      if(NULL != service_table[service_index].properties[property_index].set){
        float_value = json_object_get_double(val);
        ret = service_table[service_index].properties[property_index].set(&service_table[service_index].properties[property_index], 
                                                                          service_table[service_index].properties[property_index].arg,
                                                                          (void*)&float_value, sizeof(float));
        if (0 == ret){  // set ok, update property value
          *((float*)service_table[service_index].properties[property_index].value) = float_value;
          json_object_object_add(out_write_obj, key, json_object_new_double(float_value));
          err = kNoErr;
        }
        else{  // return write err status
          json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_WRITE_FAILED));
          err = kWriteErr;
        }
      }
      else{ // no set func err
        json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_NO_SET_FUNC));
        err = kWriteErr;
      }
      break;
    }
    case MICO_PROP_TYPE_STRING:{
      //properties_log("prop got: %s, iid=%d, value=%s", 
      //               service_table[service_index].properties[property_index].type, iid, 
      //               (char*)service_table[service_index].properties[property_index].value);
      
      // property set(hardware operation)
      if(NULL != service_table[service_index].properties[property_index].set){
        set_string = json_object_get_string(val);
        set_string_len = json_object_get_string_len(val);
        ret = service_table[service_index].properties[property_index].set(&service_table[service_index].properties[property_index], 
                                                                          service_table[service_index].properties[property_index].arg,
                                                                          (void*)set_string, set_string_len);
        if (0 == ret){  // set ok, update property value
          memset((char*)(service_table[service_index].properties[property_index].value), '\0', service_table[service_index].properties[property_index].maxStringLen);
          strncpy((char*)(service_table[service_index].properties[property_index].value), set_string, set_string_len);
          *(service_table[service_index].properties[property_index].value_len) = set_string_len;
          json_object_object_add(out_write_obj, key, json_object_new_string(set_string));
          err = kNoErr;
        }
        else{  // return write err status
          json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_WRITE_FAILED));
          err = kWriteErr;
        }
      }
      else{ // no set func err
        json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_NO_SET_FUNC));
        err = kWriteErr;
      }
      break;
    }
    case MICO_PROP_TYPE_BOOL:{
      //properties_log("prop got: %s, iid=%d, value=%d", 
      //               service_table[service_index].properties[property_index].type, iid, 
      //               *((bool*)service_table[service_index].properties[property_index].value));
      // property set(hardware operation)
      if(NULL != service_table[service_index].properties[property_index].set){
        boolean_value = json_object_get_boolean(val);
        ret = service_table[service_index].properties[property_index].set(&service_table[service_index].properties[property_index], 
                                                                          service_table[service_index].properties[property_index].arg,
                                                                          (void*)&boolean_value, sizeof(bool));
        if (0 == ret){  // set ok, update property value
          *((bool*)service_table[service_index].properties[property_index].value) = boolean_value;
          json_object_object_add(out_write_obj, key, json_object_new_boolean(boolean_value));
          err = kNoErr;
        }
        else{  // return write err status
          json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_WRITE_FAILED));
          err = kWriteErr;
        }
      }
      else{ // no set func err
        json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_NO_SET_FUNC));
        err = kWriteErr;
      }
      break;
    }
    default:
      properties_log("ERROR: Unsupported format!");
      json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_DATA_FORMAT_ERR));
      err = kWriteErr;
      break;
    }
  }
  else{
    properties_log("ERROR: property is read only!");
    json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_NOT_WRITABLE));
    err = kNotWritableErr;
  }
  
exit:
  if(kNotFoundErr == err){   // property not found
    properties_log("ERROR: property not found!");
    json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_NOT_FOUND));
  }
  if(kRequestErr == err){   // service can not be set
    properties_log("ERROR: service can not be set!");
    json_object_object_add(out_err_prop_obj, key, json_object_new_int(MICO_PROP_CODE_NOT_SUPPORTED));
  }
  return err;
}
Ejemplo n.º 21
0
void main(void)
{
	sys_init();
    //初始化电机控制信号
    //subdiv = 16;
    moto_set(int_speed,subdiv);
    //Shutter = 0;
    //Focus = 0; 
    //moto_run(100);  

	// Global enable interrupts
	#asm("sei")
    
    Lcd_Init();
    delay_ms(5);
    Init_BH1750();       //初始化BH1750
    
    Clear_Scr();                 
	MenuInitialation(); 
    ShowMenu();
    UserChooseR = 1; 
    
	while(1)   
	{ 
        if(time_10ms)  //10ms定时扫描键盘    
        { 
        	time_10ms = 0;   
        	*pRockValue=No_rock;
        	rocker_type = Read_Rocker(pRockValue);
			if(rocker_type == keyPressed)
			{
            	switch(*pRockValue)   
				{      
					case  Down:   
					  		UserChooseR ++;   
					  		if(UserChooseR == 3)   
					  		{   
								UserChooseR = 1;   
					  		}   
					  		break;				  
					case  Enter:
					  		TempMenu = MenuPoint;
					  		Clear_Scr(); 
					  		if(MenuPoint[UserChooseR].ChildrenMenus != NULL)   
					  		{   
						  		MenuPoint = MenuPoint[UserChooseR].ChildrenMenus;   
						  		//UserChooseR = 0;   
						  		//DisplayStart = 0;   
					  		} 
					  		ShowMenu(); 					  
                      		if(TempMenu[UserChooseR].Subs != NULLSubs)   
					  		{   
						 		(*TempMenu[UserChooseR].Subs)();
					  		} 
					  		//Clear_Scr();					
					  		break;		 
				}

            	Set_Cursor(UserChooseR,1);

        		//ShowMenu();
        	}

        	key_value= Read_keyboard();
			if(key_value != No_key)
			{
	        	switch(key_value)
	        	{
	        		case Esc:
                		work_mode = 0;
                        work_state = idle_state;
                        //TIMSK &= ~(1<<OCIE2);
						break;	
	        		case OK: 
                        work_mode = 1;
                        //TIMSK |= (1<<OCIE2); 
	  				 	break;
                	case 0:
                        moto_zero('A');
                        break; 
                	case 1:
                		moto_zero('B');
                        break;
                	default:
                		break;	
				}

        	} 

        }     
	    
        
    	switch(work_state)
        {
            	case idle_state:
                				if(work_mode)
                                {
                                	work_state = step_run;
                                }
                                break;
        		case step_run:
            					moto_run(Int_step);
                    			work_state = start_expos;    
                    			break;
        		case start_expos:
            					if(run_finish)
                    			{
                    				if( expos_mode == camera )
                                    	{ expos_value = def_tv; } 
                                    else if( expos_mode == sensor )
                                    	{ expos_value = Get_TV();}
                                    else
                                    	{ expos_value = (long)1000*Str2Int(TV);}
                                    
                                    flag_1ms = 0;
                                    Shutter = 1;
                                    Focus = 1;	
                                	work_state = stop_expos;
                    			}
                            	break;
            	case stop_expos:
            					if(expos_finish)
                            	{
                                	expos_finish = 0;
                                    photo_taken++;
                                	photo_left = exp_photos - photo_taken;
                                	work_state = delay_state;
                                    cnt_10ms = 0;
                            	}
                            	break;
            	case delay_state:
            					if(photo_taken == exp_photos)
                            	{
                            		work_mode = 0;
                            	}
            					if(delay_finish)
                            	{
                            		delay_finish = 0;
                                    work_state = idle_state;
                            	}
                            	break;
            	default:
            			break;

        } 

    }    
} 
Ejemplo n.º 22
0
/**
* @brief  Display the Main Menu on HyperTerminal
* @param  None
* @retval None
*/
void Main_Menu(void)
{
  char cmdbuf [CMD_STRING_SIZE] = {0}, cmdname[15] = {0};     /* command input buffer        */
  int i, j;                                       /* index for command buffer    */
  char startAddressStr[10], endAddressStr[10], flash_dev_str[4];
  int32_t startAddress, endAddress;
  bool inputFlashArea = false;
  mico_logic_partition_t *partition;
  mico_flash_t flash_dev;
  OSStatus err = kNoErr;
  
  while (1)  {                                    /* loop forever                */
    printf ("\n\rMXCHIP> ");
    getline (&cmdbuf[0], sizeof (cmdbuf));        /* input command line          */
    
    for (i = 0; cmdbuf[i] == ' '; i++);           /* skip blanks on head         */
    for (; cmdbuf[i] != 0; i++)  {                /* convert to upper characters */
      cmdbuf[i] = toupper(cmdbuf[i]);
    }
    
    for (i = 0; cmdbuf[i] == ' '; i++);        /* skip blanks on head         */
    for(j=0; cmdbuf[i] != ' '&&cmdbuf[i] != 0; i++,j++)  {         /* find command name       */
      cmdname[j] = cmdbuf[i];
    }
    cmdname[j] = '\0';
    
    /***************** Command "0" or "BOOTUPDATE": Update the application  *************************/
    if(strcmp(cmdname, "BOOTUPDATE") == 0 || strcmp(cmdname, "0") == 0) {
      partition = MicoFlashGetInfo( MICO_PARTITION_BOOTLOADER );
      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead Bootloader...\n\r");
        SerialUpload( partition->partition_owner, partition->partition_start_addr, "BootLoaderImage.bin", partition->partition_length );
        continue;
      }
      printf ("\n\rUpdating Bootloader...\n\r");
      err = MicoFlashDisableSecurity( MICO_PARTITION_BOOTLOADER, 0x0, partition->partition_length );
      require_noerr( err, exit);

      SerialDownload( partition->partition_owner, partition->partition_start_addr, partition->partition_length );
    }
    
    /***************** Command "1" or "FWUPDATE": Update the MICO application  *************************/
    else if(strcmp(cmdname, "FWUPDATE") == 0 || strcmp(cmdname, "1") == 0)	{
      partition = MicoFlashGetInfo( MICO_PARTITION_APPLICATION );
      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead application...\n\r");
        SerialUpload( partition->partition_owner, partition->partition_start_addr, "ApplicationImage.bin", partition->partition_length );
        continue;
      }
      printf ("\n\rUpdating application...\n\r");
      err = MicoFlashDisableSecurity( MICO_PARTITION_APPLICATION, 0x0, partition->partition_length );
      require_noerr( err, exit);
      SerialDownload( partition->partition_owner, partition->partition_start_addr, partition->partition_length ); 							   	
    }
    
    /***************** Command "2" or "DRIVERUPDATE": Update the RF driver  *************************/
    else if(strcmp(cmdname, "DRIVERUPDATE") == 0 || strcmp(cmdname, "2") == 0) {
      partition = MicoFlashGetInfo( MICO_PARTITION_RF_FIRMWARE );
      if( partition == NULL ){
        printf ("\n\rNo flash memory for RF firmware, exiting...\n\r");
        continue;
      }
      
      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead RF firmware...\n\r");
        SerialUpload( partition->partition_owner, partition->partition_start_addr, "DriverImage.bin", partition->partition_length );
        continue;
      }
      printf ("\n\rUpdating RF driver...\n\r");
      err = MicoFlashDisableSecurity( MICO_PARTITION_RF_FIRMWARE, 0x0, partition->partition_length );
      require_noerr( err, exit);
      SerialDownload( partition->partition_owner, partition->partition_start_addr, partition->partition_length );    
    }
    
    /***************** Command "3" or "PARAUPDATE": Update the application  *************************/
    else if(strcmp(cmdname, "PARAUPDATE") == 0 || strcmp(cmdname, "3") == 0)  {
      partition = MicoFlashGetInfo( MICO_PARTITION_PARAMETER_1 );

      if (findCommandPara(cmdbuf, "e", NULL, 0) != -1){
        printf ("\n\rErasing settings...\n\r");

        err = MicoFlashDisableSecurity( MICO_PARTITION_PARAMETER_1, 0x0, partition->partition_length );
        require_noerr( err, exit);
        MicoFlashErase( MICO_PARTITION_PARAMETER_1, 0x0, partition->partition_length );
        continue;
      }
      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead settings...\n\r");
        SerialUpload( partition->partition_owner, partition->partition_start_addr, "DriverImage.bin", partition->partition_length );
        continue;
      }
      printf ("\n\rUpdating settings...\n\r");
      err = MicoFlashDisableSecurity( MICO_PARTITION_PARAMETER_1, 0x0, partition->partition_length );
      require_noerr( err, exit);
      SerialDownload( partition->partition_owner, partition->partition_start_addr, partition->partition_length );                        
    }
    
    /***************** Command "4" or "FLASHUPDATE": : Update the Flash  *************************/
    else if(strcmp(cmdname, "FLASHUPDATE") == 0 || strcmp(cmdname, "4") == 0) {
      if (findCommandPara(cmdbuf, "dev", flash_dev_str, 1) == -1  ){
        printf ("\n\rUnkown target type! Exiting...\n\r");
        continue;
      }
      
      if(Str2Int((uint8_t *)flash_dev_str, (int32_t *)&flash_dev)==0){ 
        printf ("\n\rDevice Number Err! Exiting...\n\r");
        continue;
      }
      if( flash_dev >= MICO_FLASH_MAX ){
        printf ("\n\rDevice Err! Exiting...\n\r");
        continue;
      }
      
      inputFlashArea = false;
      
      if (findCommandPara(cmdbuf, "start", startAddressStr, 10) != -1){
        if(Str2Int((uint8_t *)startAddressStr, &startAddress)==0){ //Found Flash start address
          printf ("\n\rIllegal start address.\n\r");
          continue;
        }else{
          if (findCommandPara(cmdbuf, "end", endAddressStr, 10) != -1){ //Found Flash end address
            if(Str2Int((uint8_t *)endAddressStr, &endAddress)==0){
              printf ("\n\rIllegal end address.\n\r");
              continue;
            }else{
              inputFlashArea = true;
            }
          }else{
            printf ("\n\rFlash end address not found.\n\r");
            continue;
          }
        }
      }
      
      if(endAddress<startAddress && inputFlashArea == true) {
        printf ("\n\rIllegal address.\n\r");
        continue;
      }
      
      if(inputFlashArea != true){
        startAddress = platform_flash_peripherals[ flash_dev ].flash_start_addr ;
        endAddress = platform_flash_peripherals[ flash_dev ].flash_start_addr 
          + platform_flash_peripherals[ flash_dev ].flash_length - 1;
      }
      
      if (findCommandPara(cmdbuf, "e", NULL, 0) != -1){
        printf ("\n\rErasing dev%d content From 0x%x to 0x%x\n\r", flash_dev, startAddress, endAddress);
        platform_flash_init( &platform_flash_peripherals[ flash_dev ] );
        platform_flash_disable_protect( &platform_flash_peripherals[ flash_dev ], startAddress, endAddress );
        platform_flash_erase( &platform_flash_peripherals[ flash_dev ], startAddress, endAddress );
        continue;
      }
      
      if (findCommandPara(cmdbuf, "r", NULL, 0) != -1){
        printf ("\n\rRead dev%d content From 0x%x to 0x%x\n\r", flash_dev, startAddress, endAddress);
        SerialUpload(flash_dev, startAddress, "FlashImage.bin", endAddress-startAddress+1);
        continue;
      }
      
      printf ("\n\rUpdating dev%d content From 0x%x to 0x%x\n\r", flash_dev, startAddress, endAddress);
      platform_flash_disable_protect( &platform_flash_peripherals[ flash_dev ], startAddress, endAddress );
      SerialDownload(flash_dev, startAddress, endAddress-startAddress+1);                           
    }
    
    
    /***************** Command: MEMORYMAP *************************/
    else if(strcmp(cmdname, "MEMORYMAP") == 0 || strcmp(cmdname, "5") == 0)  {
      printf("\r");
      for( i = 0; i <= MICO_PARTITION_PARAMETER_2; i++ ){
        partition = MicoFlashGetInfo( (mico_partition_t)i );
        if (partition->partition_owner == MICO_FLASH_NONE)
            continue;
        printf( "| %11s |  Dev:%d  | 0x%08x | 0x%08x |\r\n", partition->partition_description, partition->partition_owner, 
               partition->partition_start_addr, partition->partition_length);
      }
    }
    /***************** Command: Excute the application *************************/
    else if(strcmp(cmdname, "BOOT") == 0 || strcmp(cmdname, "6") == 0)	{
      printf ("\n\rBooting.......\n\r");
      partition = MicoFlashGetInfo( MICO_PARTITION_APPLICATION );
      bootloader_start_app( partition->partition_start_addr );
    }
    
    /***************** Command: Reboot *************************/
    else if(strcmp(cmdname, "REBOOT") == 0 || strcmp(cmdname, "7") == 0)  {
      printf ("\n\rReBooting.......\n\r");
      MicoSystemReboot();
      break;                              
    }
    
    else if(strcmp(cmdname, "HELP") == 0 || strcmp(cmdname, "?") == 0)	{
        printf ( menu, MODEL, Bootloader_REVISION, HARDWARE_REVISION );  /* display command menu        */
      break;
    }
    
    else if(strcmp(cmdname, "") == 0 )	{                         
      break;
    }
    else{
      printf (ERROR_STR, "UNKNOWN COMMAND");
      break;
    }

exit:
    continue;
  }
}
Ejemplo n.º 23
0
/**
  * @brief  Receive a file using the ymodem protocol.
  * @param  buf: Address of the first byte.
  * @retval The size of the file.
  */
int32_t Ymodem_Receive (uint8_t *buf, mico_flash_t flash, uint32_t flashdestination, int32_t maxRecvSize)
{
  uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD], file_size[FILE_SIZE_LENGTH], *file_ptr, *buf_ptr;
  int32_t i, packet_length, session_done, file_done, packets_received, errors, session_begin, size = 0;
  uint32_t  ramsource;
  MicoFlashInitialize(flash);

  for (session_done = 0, errors = 0, session_begin = 0; ;)
  {
    for (packets_received = 0, file_done = 0, buf_ptr = buf; ;)
    {
      switch (Receive_Packet(packet_data, &packet_length, NAK_TIMEOUT))
      {
        case 0:
          errors = 0;
          switch (packet_length)
          {
            /* Abort by sender */
            case - 1:
              Send_Byte(ACK);
              MicoFlashFinalize(flash);
              return 0;
            /* End of transmission */
            case 0:
              Send_Byte(ACK);
              file_done = 1;
              break;
            /* Normal packet */
            default:
              if ((packet_data[PACKET_SEQNO_INDEX] & 0xff) != (packets_received & 0xff))
              {
                Send_Byte(NAK);
              }
              else
              {
                if (packets_received == 0)
                {
                  /* Filename packet */
                  if (packet_data[PACKET_HEADER] != 0)
                  {
                    /* Filename packet has valid data */
                    for (i = 0, file_ptr = packet_data + PACKET_HEADER; (*file_ptr != 0) && (i < FILE_NAME_LENGTH);)
                    {
                      FileName[i++] = *file_ptr++;
                    }
                    FileName[i++] = '\0';
                    for (i = 0, file_ptr ++; (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH);)
                    {
                      file_size[i++] = *file_ptr++;
                    }
                    file_size[i++] = '\0';
                    Str2Int(file_size, &size);

                    /* Test the size of the image to be sent */
                    /* Image size is greater than Flash size */
                    if (size > (maxRecvSize + 1))
                    {
                      /* End session */
                      Send_Byte(CA);
                      Send_Byte(CA);
                      MicoFlashFinalize(flash);
                      return -1;//The image size is higher than memory!
                    }
                    /* erase user application area */
                    MicoFlashErase(flash, flashdestination, flashdestination + maxRecvSize - 1);
                    Send_Byte(ACK);
                    Send_Byte(CRC16);
                  }
                  /* Filename packet is empty, end session */
                  else
                  {
                    Send_Byte(ACK);
                    file_done = 1;
                    session_done = 1;
                    break;
                  }
                }
                /* Data packet */
                else
                {
                  memcpy(buf_ptr, packet_data + PACKET_HEADER, packet_length);
                  ramsource = (uint32_t)buf;

                  /* Write received data in Flash */
                  if (MicoFlashWrite(flash, &flashdestination, (uint8_t*) ramsource, (uint32_t) packet_length)  == 0)
                  {
                    Send_Byte(ACK);
                  }
                  else /* An error occurred while writing to Flash memory */
                  {
                    /* End session */
                    Send_Byte(CA);
                    Send_Byte(CA);
                    MicoFlashFinalize(flash);
                    return -2;//Verification failed!
                  }
                }
                packets_received ++;
                session_begin = 1;
              }
          }
          break;
        case 1:
          Send_Byte(CA);
          Send_Byte(CA);
          MicoFlashFinalize(flash);
          return -3;//Aborted by user.
        default:
          if (session_begin > 0)
          {
            errors ++;
          }
          if (errors > MAX_ERRORS)
          {
            Send_Byte(CA);
            Send_Byte(CA);
            MicoFlashFinalize(flash);
            return 0;//Failed to receive file!
          }
          Send_Byte(CRC16);
          break;
      }
      if (file_done != 0)
      {
        break;
      }
    }
    if (session_done != 0)
    {
      break;
    }
  }
  MicoFlashFinalize(flash);
  return (int32_t)size;//successful
}
Ejemplo n.º 24
0
void KeepControlPromises()
{
    Constraint *cp;
    Rval retval;

    CFD_MAXPROCESSES = 30;
    MAXTRIES = 5;
    CFD_INTERVAL = 0;
    DENYBADCLOCKS = true;
    CFRUNCOMMAND[0] = '\0';
    SetChecksumUpdates(true);

/* Keep promised agent behaviour - control bodies */

    Banner("Server control promises..");

    HashControls();

/* Now expand */

    for (cp = ControlBodyConstraints(cf_server); cp != NULL; cp = cp->next)
    {
        if (IsExcluded(cp->classes))
        {
            continue;
        }

        if (GetVariable("control_server", cp->lval, &retval) == cf_notype)
        {
            CfOut(cf_error, "", "Unknown lval %s in server control body", cp->lval);
            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_serverfacility].lval) == 0)
        {
            SetFacility(retval.item);
            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_denybadclocks].lval) == 0)
        {
            DENYBADCLOCKS = GetBoolean(retval.item);
            CfOut(cf_verbose, "", "SET denybadclocks = %d\n", DENYBADCLOCKS);
            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_logencryptedtransfers].lval) == 0)
        {
            LOGENCRYPT = GetBoolean(retval.item);
            CfOut(cf_verbose, "", "SET LOGENCRYPT = %d\n", LOGENCRYPT);
            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_logallconnections].lval) == 0)
        {
            LOGCONNS = GetBoolean(retval.item);
            CfOut(cf_verbose, "", "SET LOGCONNS = %d\n", LOGCONNS);
            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_maxconnections].lval) == 0)
        {
            CFD_MAXPROCESSES = (int) Str2Int(retval.item);
            MAXTRIES = CFD_MAXPROCESSES / 3;
            CfOut(cf_verbose, "", "SET maxconnections = %d\n", CFD_MAXPROCESSES);
            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_cfruncommand].lval) == 0)
        {
            strncpy(CFRUNCOMMAND, retval.item, CF_BUFSIZE - 1);
            CfOut(cf_verbose, "", "SET cfruncommand = %s\n", CFRUNCOMMAND);
            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_allowconnects].lval) == 0)
        {
            Rlist *rp;

            CfOut(cf_verbose, "", "SET Allowing connections from ...\n");

            for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
            {
                if (!IsItemIn(NONATTACKERLIST, rp->item))
                {
                    AppendItem(&NONATTACKERLIST, rp->item, cp->classes);
                }
            }

            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_denyconnects].lval) == 0)
        {
            Rlist *rp;

            CfOut(cf_verbose, "", "SET Denying connections from ...\n");

            for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
            {
                if (!IsItemIn(ATTACKERLIST, rp->item))
                {
                    AppendItem(&ATTACKERLIST, rp->item, cp->classes);
                }
            }

            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_skipverify].lval) == 0)
        {
            Rlist *rp;

            CfOut(cf_verbose, "", "SET Skip verify connections from ...\n");

            for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
            {
                if (!IsItemIn(SKIPVERIFY, rp->item))
                {
                    AppendItem(&SKIPVERIFY, rp->item, cp->classes);
                }
            }

            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_dynamicaddresses].lval) == 0)
        {
            Rlist *rp;

            CfOut(cf_verbose, "", "SET Dynamic addresses from ...\n");

            for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
            {
                if (!IsItemIn(DHCPLIST, rp->item))
                {
                    AppendItem(&DHCPLIST, rp->item, cp->classes);
                }
            }

            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_allowallconnects].lval) == 0)
        {
            Rlist *rp;

            CfOut(cf_verbose, "", "SET Allowing multiple connections from ...\n");

            for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
            {
                if (!IsItemIn(MULTICONNLIST, rp->item))
                {
                    AppendItem(&MULTICONNLIST, rp->item, cp->classes);
                }
            }

            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_allowusers].lval) == 0)
        {
            Rlist *rp;

            CfOut(cf_verbose, "", "SET Allowing users ...\n");

            for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
            {
                if (!IsItemIn(ALLOWUSERLIST, rp->item))
                {
                    AppendItem(&ALLOWUSERLIST, rp->item, cp->classes);
                }
            }

            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_trustkeysfrom].lval) == 0)
        {
            Rlist *rp;

            CfOut(cf_verbose, "", "SET Trust keys from ...\n");

            for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
            {
                if (!IsItemIn(TRUSTKEYLIST, rp->item))
                {
                    AppendItem(&TRUSTKEYLIST, rp->item, cp->classes);
                }
            }

            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_portnumber].lval) == 0)
        {
            SHORT_CFENGINEPORT = (short) Str2Int(retval.item);
            strncpy(STR_CFENGINEPORT, retval.item, 15);
            CfOut(cf_verbose, "", "SET default portnumber = %u = %s = %s\n", (int) SHORT_CFENGINEPORT, STR_CFENGINEPORT,
                  ScalarRvalValue(retval));
            SHORT_CFENGINEPORT = htons((short) Str2Int(retval.item));
            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_keyttl].lval) == 0)
        {
            CfOut(cf_verbose, "", "Ignoring deprecated option keycacheTTL");
            continue;
        }

        if (strcmp(cp->lval, CFS_CONTROLBODY[cfs_bindtointerface].lval) == 0)
        {
            strncpy(BINDINTERFACE, retval.item, CF_BUFSIZE - 1);
            CfOut(cf_verbose, "", "SET bindtointerface = %s\n", BINDINTERFACE);
            continue;
        }
    }

    if (GetVariable("control_common", CFG_CONTROLBODY[cfg_syslog_host].lval, &retval) != cf_notype)
    {
        SetSyslogHost(Hostname2IPString(retval.item));
    }

    if (GetVariable("control_common", CFG_CONTROLBODY[cfg_syslog_port].lval, &retval) != cf_notype)
    {
        SetSyslogPort(Str2Int(retval.item));
    }

    if (GetVariable("control_common", CFG_CONTROLBODY[cfg_fips_mode].lval, &retval) != cf_notype)
    {
        FIPS_MODE = GetBoolean(retval.item);
        CfOut(cf_verbose, "", "SET FIPS_MODE = %d\n", FIPS_MODE);
    }

    if (GetVariable("control_common", CFG_CONTROLBODY[cfg_lastseenexpireafter].lval, &retval) != cf_notype)
    {
        LASTSEENEXPIREAFTER = Str2Int(retval.item) * 60;
    }
}
Ejemplo n.º 25
0
/**
  * @brief  Receive a file using the ymodem protocol with CRC16.
  * @param  p_size The size of the file.
  * @retval COM_StatusTypeDef result of reception/programming
  */
COM_StatusTypeDef Ymodem_Receive ( uint32_t *p_size )
{
  uint32_t i, packet_length, session_done = 0, file_done, errors = 0, session_begin = 0;
  uint32_t flashdestination, ramsource, filesize;
  uint8_t *file_ptr;
  uint8_t file_size[FILE_SIZE_LENGTH], tmp, packets_received;
  COM_StatusTypeDef result = COM_OK;

  /* Initialize flashdestination variable */
  flashdestination = APPLICATION_ADDRESS;

  while ((session_done == 0) && (result == COM_OK))
  {
    packets_received = 0;
    file_done = 0;
    while ((file_done == 0) && (result == COM_OK))
    {
      switch (ReceivePacket(aPacketData, &packet_length, DOWNLOAD_TIMEOUT))
      {
        case HAL_OK:
          errors = 0;
          switch (packet_length)
          {
            case 2:
              /* Abort by sender */
              Serial_PutByte(ACK);
              result = COM_ABORT;
              break;
            case 0:
              /* End of transmission */
              Serial_PutByte(ACK);
              file_done = 1;
              break;
            default:
              /* Normal packet */
              if (aPacketData[PACKET_NUMBER_INDEX] != packets_received)
              {
                Serial_PutByte(NAK);
              }
              else
              {
                if (packets_received == 0)
                {
                  /* File name packet */
                  if (aPacketData[PACKET_DATA_INDEX] != 0)
                  {
                    /* File name extraction */
                    i = 0;
                    file_ptr = aPacketData + PACKET_DATA_INDEX;
                    while ( (*file_ptr != 0) && (i < FILE_NAME_LENGTH))
                    {
                      aFileName[i++] = *file_ptr++;
                    }

                    /* File size extraction */
                    aFileName[i++] = '\0';
                    i = 0;
                    file_ptr ++;
                    while ( (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH))
                    {
                      file_size[i++] = *file_ptr++;
                    }
                    file_size[i++] = '\0';
                    Str2Int(file_size, &filesize);

                    /* Test the size of the image to be sent */
                    /* Image size is greater than Flash size */
                    if (*p_size > (USER_FLASH_SIZE + 1))
                    {
                      /* End session */
                      tmp = CA;
                      HAL_UART_Transmit(&UartHandle, &tmp, 1, NAK_TIMEOUT);
                      HAL_UART_Transmit(&UartHandle, &tmp, 1, NAK_TIMEOUT);
                      result = COM_LIMIT;
                    }
                    /* erase user application area */
                    FLASH_If_Erase(APPLICATION_ADDRESS);
                    *p_size = filesize;

                    Serial_PutByte(ACK);
                    Serial_PutByte(CRC16);
                  }
                  /* File header packet is empty, end session */
                  else
                  {
                    Serial_PutByte(ACK);
                    file_done = 1;
                    session_done = 1;
                    break;
                  }
                }
                else /* Data packet */
                {
                  ramsource = (uint32_t) & aPacketData[PACKET_DATA_INDEX];

                  /* Write received data in Flash */
                  if (FLASH_If_Write(flashdestination, (uint32_t*) ramsource, packet_length/4) == FLASHIF_OK)                   
                  {
                    flashdestination += packet_length;
                    Serial_PutByte(ACK);
                  }
                  else /* An error occurred while writing to Flash memory */
                  {
                    /* End session */
                    Serial_PutByte(CA);
                    Serial_PutByte(CA);
                    result = COM_DATA;
                  }
                }
                packets_received ++;
                session_begin = 1;
              }
              break;
          }
          break;
        case HAL_BUSY: /* Abort actually */
          Serial_PutByte(CA);
          Serial_PutByte(CA);
          result = COM_ABORT;
          break;
        default:
          if (session_begin > 0)
          {
            errors ++;
          }
          if (errors > MAX_ERRORS)
          {
            /* Abort communication */
            Serial_PutByte(CA);
            Serial_PutByte(CA);
          }
          else
          {
            Serial_PutByte(CRC16); /* Ask for a packet */
          }
          break;
      }
    }
  }
  return result;
}
Ejemplo n.º 26
0
void KeepControlPromises(Policy *policy)
{
    Rval retval;
    Rlist *rp;

    Seq *constraints = ControlBodyConstraints(policy, AGENT_TYPE_AGENT);
    if (constraints)
    {
        for (size_t i = 0; i < SeqLength(constraints); i++)
        {
            Constraint *cp = SeqAt(constraints, i);

            if (IsExcluded(cp->classes, NULL))
            {
                continue;
            }

            if (GetVariable("control_common", cp->lval, &retval) != DATA_TYPE_NONE)
            {
                /* Already handled in generic_agent */
                continue;
            }

            if (GetVariable("control_agent", cp->lval, &retval) == DATA_TYPE_NONE)
            {
                CfOut(cf_error, "", "Unknown lval %s in agent control body", cp->lval);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_maxconnections].lval) == 0)
            {
                CFA_MAXTHREADS = (int) Str2Int(retval.item);
                CfOut(cf_verbose, "", "SET maxconnections = %d\n", CFA_MAXTHREADS);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_checksum_alert_time].lval) == 0)
            {
                CF_PERSISTENCE = (int) Str2Int(retval.item);
                CfOut(cf_verbose, "", "SET checksum_alert_time = %d\n", CF_PERSISTENCE);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_agentfacility].lval) == 0)
            {
                SetFacility(retval.item);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_agentaccess].lval) == 0)
            {
                ACCESSLIST = (Rlist *) retval.item;
                CheckAgentAccess(ACCESSLIST, InputFiles(policy));
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_refresh_processes].lval) == 0)
            {
                Rlist *rp;

                if (VERBOSE)
                {
                    printf("%s> SET refresh_processes when starting: ", VPREFIX);

                    for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
                    {
                        printf(" %s", (char *) rp->item);
                        PrependItem(&PROCESSREFRESH, rp->item, NULL);
                    }

                    printf("\n");
                }

                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_abortclasses].lval) == 0)
            {
                Rlist *rp;

                CfOut(cf_verbose, "", "SET Abort classes from ...\n");

                for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
                {
                    char name[CF_MAXVARSIZE] = "";

                    strncpy(name, rp->item, CF_MAXVARSIZE - 1);

                    AddAbortClass(name, cp->classes);
                }

                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_abortbundleclasses].lval) == 0)
            {
                Rlist *rp;

                CfOut(cf_verbose, "", "SET Abort bundle classes from ...\n");

                for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
                {
                    char name[CF_MAXVARSIZE] = "";

                    strncpy(name, rp->item, CF_MAXVARSIZE - 1);

                    if (!IsItemIn(ABORTBUNDLEHEAP, name))
                    {
                        AppendItem(&ABORTBUNDLEHEAP, name, cp->classes);
                    }
                }

                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_addclasses].lval) == 0)
            {
                Rlist *rp;

                CfOut(cf_verbose, "", "-> Add classes ...\n");

                for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
                {
                    CfOut(cf_verbose, "", " -> ... %s\n", ScalarValue(rp));
                    NewClass(rp->item, NULL);
                }

                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_auditing].lval) == 0)
            {
                CfOut(cf_verbose, "", "This option does nothing and is retained for compatibility reasons");
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_alwaysvalidate].lval) == 0)
            {
                ALWAYS_VALIDATE = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET alwaysvalidate = %d\n", ALWAYS_VALIDATE);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_allclassesreport].lval) == 0)
            {
                ALLCLASSESREPORT = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET allclassesreport = %d\n", ALLCLASSESREPORT);
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_secureinput].lval) == 0)
            {
                CFPARANOID = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET secure input = %d\n", CFPARANOID);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_binarypaddingchar].lval) == 0)
            {
                CfOut(cf_verbose, "", "binarypaddingchar is obsolete and does nothing\n");
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_bindtointerface].lval) == 0)
            {
                strncpy(BINDINTERFACE, retval.item, CF_BUFSIZE - 1);
                CfOut(cf_verbose, "", "SET bindtointerface = %s\n", BINDINTERFACE);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_hashupdates].lval) == 0)
            {
                bool enabled = GetBoolean(retval.item);

                SetChecksumUpdates(enabled);
                CfOut(cf_verbose, "", "SET ChecksumUpdates %d\n", enabled);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_exclamation].lval) == 0)
            {
                CfOut(cf_verbose, "", "exclamation control is deprecated and does not do anything\n");
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_childlibpath].lval) == 0)
            {
                char output[CF_BUFSIZE];

                snprintf(output, CF_BUFSIZE, "LD_LIBRARY_PATH=%s", (char *) retval.item);
                if (putenv(xstrdup(output)) == 0)
                {
                    CfOut(cf_verbose, "", "Setting %s\n", output);
                }
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_defaultcopytype].lval) == 0)
            {
                DEFAULT_COPYTYPE = (char *) retval.item;
                CfOut(cf_verbose, "", "SET defaultcopytype = %s\n", DEFAULT_COPYTYPE);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_fsinglecopy].lval) == 0)
            {
                SINGLE_COPY_LIST = (Rlist *) retval.item;
                CfOut(cf_verbose, "", "SET file single copy list\n");
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_fautodefine].lval) == 0)
            {
                SetFileAutoDefineList(ListRvalValue(retval));
                CfOut(cf_verbose, "", "SET file auto define list\n");
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_dryrun].lval) == 0)
            {
                DONTDO = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET dryrun = %c\n", DONTDO);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_inform].lval) == 0)
            {
                INFORM = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET inform = %c\n", INFORM);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_verbose].lval) == 0)
            {
                VERBOSE = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET inform = %c\n", VERBOSE);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_repository].lval) == 0)
            {
                SetRepositoryLocation(retval.item);
                CfOut(cf_verbose, "", "SET repository = %s\n", ScalarRvalValue(retval));
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_skipidentify].lval) == 0)
            {
                bool enabled = GetBoolean(retval.item);

                SetSkipIdentify(enabled);
                CfOut(cf_verbose, "", "SET skipidentify = %d\n", (int) enabled);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_suspiciousnames].lval) == 0)
            {

                for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
                {
                    AddFilenameToListOfSuspicious(ScalarValue(rp));
                    CfOut(cf_verbose, "", "-> Considering %s as suspicious file", ScalarValue(rp));
                }

                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_repchar].lval) == 0)
            {
                char c = *(char *) retval.item;

                SetRepositoryChar(c);
                CfOut(cf_verbose, "", "SET repchar = %c\n", c);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_mountfilesystems].lval) == 0)
            {
                CF_MOUNTALL = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET mountfilesystems = %d\n", CF_MOUNTALL);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_editfilesize].lval) == 0)
            {
                EDITFILESIZE = Str2Int(retval.item);
                CfOut(cf_verbose, "", "SET EDITFILESIZE = %d\n", EDITFILESIZE);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_ifelapsed].lval) == 0)
            {
                VIFELAPSED = Str2Int(retval.item);
                CfOut(cf_verbose, "", "SET ifelapsed = %d\n", VIFELAPSED);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_expireafter].lval) == 0)
            {
                VEXPIREAFTER = Str2Int(retval.item);
                CfOut(cf_verbose, "", "SET ifelapsed = %d\n", VEXPIREAFTER);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_timeout].lval) == 0)
            {
                CONNTIMEOUT = Str2Int(retval.item);
                CfOut(cf_verbose, "", "SET timeout = %jd\n", (intmax_t) CONNTIMEOUT);
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_max_children].lval) == 0)
            {
                CFA_BACKGROUND_LIMIT = Str2Int(retval.item);
                CfOut(cf_verbose, "", "SET MAX_CHILDREN = %d\n", CFA_BACKGROUND_LIMIT);
                if (CFA_BACKGROUND_LIMIT > 10)
                {
                    CfOut(cf_error, "", "Silly value for max_children in agent control promise (%d > 10)",
                          CFA_BACKGROUND_LIMIT);
                    CFA_BACKGROUND_LIMIT = 1;
                }
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_syslog].lval) == 0)
            {
                CfOut(cf_verbose, "", "SET syslog = %d\n", GetBoolean(retval.item));
                continue;
            }

            if (strcmp(cp->lval, CFA_CONTROLBODY[cfa_environment].lval) == 0)
            {
                Rlist *rp;

                CfOut(cf_verbose, "", "SET environment variables from ...\n");

                for (rp = (Rlist *) retval.item; rp != NULL; rp = rp->next)
                {
                    if (putenv(rp->item) != 0)
                    {
                        CfOut(cf_error, "putenv", "Failed to set environment variable %s", ScalarValue(rp));
                    }
                }

                continue;
            }
        }
    }

    if (GetVariable("control_common", CFG_CONTROLBODY[cfg_lastseenexpireafter].lval, &retval) != DATA_TYPE_NONE)
    {
        LASTSEENEXPIREAFTER = Str2Int(retval.item) * 60;
    }

    if (GetVariable("control_common", CFG_CONTROLBODY[cfg_fips_mode].lval, &retval) != DATA_TYPE_NONE)
    {
        FIPS_MODE = GetBoolean(retval.item);
        CfOut(cf_verbose, "", "SET FIPS_MODE = %d\n", FIPS_MODE);
    }

    if (GetVariable("control_common", CFG_CONTROLBODY[cfg_syslog_port].lval, &retval) != DATA_TYPE_NONE)
    {
        SetSyslogPort(Str2Int(retval.item));
        CfOut(cf_verbose, "", "SET syslog_port to %s", ScalarRvalValue(retval));
    }

    if (GetVariable("control_common", CFG_CONTROLBODY[cfg_syslog_host].lval, &retval) != DATA_TYPE_NONE)
    {
        SetSyslogHost(Hostname2IPString(retval.item));
        CfOut(cf_verbose, "", "SET syslog_host to %s", Hostname2IPString(retval.item));
    }

#ifdef HAVE_NOVA
    Nova_Initialize();
#endif
}
Ejemplo n.º 27
0
void KeepControlPromises(Policy *policy)
{
    Rval retval;

    RUNATTR.copy.trustkey = false;
    RUNATTR.copy.encrypt = true;
    RUNATTR.copy.force_ipv4 = false;
    RUNATTR.copy.portnumber = SHORT_CFENGINEPORT;

/* Keep promised agent behaviour - control bodies */

    Seq *constraints = ControlBodyConstraints(policy, AGENT_TYPE_RUNAGENT);
    if (constraints)
    {
        for (size_t i = 0; i < SeqLength(constraints); i++)
        {
            Constraint *cp = SeqAt(constraints, i);

            if (IsExcluded(cp->classes, NULL))
            {
                continue;
            }

            if (GetVariable("control_runagent", cp->lval, &retval) == cf_notype)
            {
                CfOut(cf_error, "", "Unknown lval %s in runagent control body", cp->lval);
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_force_ipv4].lval) == 0)
            {
                RUNATTR.copy.force_ipv4 = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET force_ipv4 = %d\n", RUNATTR.copy.force_ipv4);
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_trustkey].lval) == 0)
            {
                RUNATTR.copy.trustkey = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET trustkey = %d\n", RUNATTR.copy.trustkey);
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_encrypt].lval) == 0)
            {
                RUNATTR.copy.encrypt = GetBoolean(retval.item);
                CfOut(cf_verbose, "", "SET encrypt = %d\n", RUNATTR.copy.encrypt);
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_portnumber].lval) == 0)
            {
                RUNATTR.copy.portnumber = (short) Str2Int(retval.item);
                CfOut(cf_verbose, "", "SET default portnumber = %u\n", (int) RUNATTR.copy.portnumber);
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_background].lval) == 0)
            {
                /*
                 * Only process this option if are is no -b or -i options specified on
                 * command line.
                 */
                if (BACKGROUND || INTERACTIVE)
                {
                    CfOut(cf_error, "",
                          "Warning: 'background_children' setting from 'body runagent control' is overriden by command-line option.");
                }
                else
                {
                    BACKGROUND = GetBoolean(retval.item);
                }
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_maxchild].lval) == 0)
            {
                MAXCHILD = (short) Str2Int(retval.item);
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_output_to_file].lval) == 0)
            {
                OUTPUT_TO_FILE = GetBoolean(retval.item);
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_output_directory].lval) == 0)
            {
                if (IsAbsPath(retval.item))
                {
                    strncpy(OUTPUT_DIRECTORY, retval.item, CF_BUFSIZE - 1);
                    CfOut(cf_verbose, "", "SET output direcory to = %s\n", OUTPUT_DIRECTORY);
                }
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_timeout].lval) == 0)
            {
                RUNATTR.copy.timeout = (short) Str2Int(retval.item);
                continue;
            }

            if (strcmp(cp->lval, CFR_CONTROLBODY[cfr_hosts].lval) == 0)
            {
                if (HOSTLIST == NULL)       // Don't override if command line setting
                {
                    HOSTLIST = retval.item;
                }

                continue;
            }
        }
    }

    if (GetVariable("control_common", CFG_CONTROLBODY[cfg_lastseenexpireafter].lval, &retval) != cf_notype)
    {
        LASTSEENEXPIREAFTER = Str2Int(retval.item) * 60;
    }

}
Ejemplo n.º 28
0
void KeepControlPromises()

{ struct Constraint *cp;
  char rettype;
  void *retval;

RUNATTR.copy.trustkey = false;
RUNATTR.copy.encrypt = true;
RUNATTR.copy.force_ipv4 = false;
RUNATTR.copy.portnumber = SHORT_CFENGINEPORT;

/* Keep promised agent behaviour - control bodies */

for (cp = ControlBodyConstraints(cf_runagent); cp != NULL; cp=cp->next)
   {
   if (IsExcluded(cp->classes))
      {
      continue;
      }
   
   if (GetVariable("control_runagent",cp->lval,&retval,&rettype) == cf_notype)
      {
      CfOut(cf_error,"","Unknown lval %s in runagent control body",cp->lval);
      continue;
      }
   
   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_force_ipv4].lval) == 0)
      {
      RUNATTR.copy.force_ipv4 = GetBoolean(retval);
      CfOut(cf_verbose,"","SET force_ipv4 = %d\n",RUNATTR.copy.force_ipv4);
      continue;
      }
   
   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_trustkey].lval) == 0)
      {
      RUNATTR.copy.trustkey = GetBoolean(retval);
      CfOut(cf_verbose,"","SET trustkey = %d\n",RUNATTR.copy.trustkey);
      continue;
      }
   
   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_encrypt].lval) == 0)
      {
      RUNATTR.copy.encrypt = GetBoolean(retval);
      CfOut(cf_verbose,"","SET encrypt = %d\n",RUNATTR.copy.encrypt);
      continue;
      }

   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_portnumber].lval) == 0)
      {
      RUNATTR.copy.portnumber = (short)Str2Int(retval);
      CfOut(cf_verbose,"","SET default portnumber = %u\n",(int)RUNATTR.copy.portnumber);
      continue;
      }

   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_background].lval) == 0)
      {
      /*
       * Only process this option if are is no -b or -i options specified on
       * command line.
       */
      if (BACKGROUND || INTERACTIVE)
         {
         CfOut(cf_error, "", "Warning: 'background_children' setting from 'body runagent control' is overriden by command-line option.");
         }
      else
         {
         BACKGROUND = GetBoolean(retval);
         }
      continue;
      }
   
   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_maxchild].lval) == 0)
      {
      MAXCHILD = (short)Str2Int(retval);
      continue;
      }
   
   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_output_to_file].lval) == 0)
      {
      OUTPUT_TO_FILE = GetBoolean(retval);
      continue;
      }

   /*
    * HvB: add variabele output directory
   */
   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_output_directory].lval) == 0)
      {
      if ( IsAbsPath(retval) )
        {
	strncpy(OUTPUT_DIRECTORY,retval,CF_BUFSIZE-1);
        CfOut(cf_verbose,"","SET output direcory to = %s\n", OUTPUT_DIRECTORY);
	}
      continue;
      }

   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_timeout].lval) == 0)
      {
      RUNATTR.copy.timeout = (short)Str2Int(retval);
      continue;
      }

   if (strcmp(cp->lval,CFR_CONTROLBODY[cfr_hosts].lval) == 0)
      {
      if (HOSTLIST == NULL) // Don't override if command line setting
         {
         HOSTLIST = retval;
         }
      
      continue;
      }   
   }
}
Ejemplo n.º 29
0
//---------------------------------------------------------------------------------
static int32_t Ymodem_Receive ( char* FileName, uint32_t maxsize, uint8_t getname )
{
  uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD], file_size[FILE_SIZE_LENGTH], *file_ptr;
  int32_t i, packet_length, file_len, write_len, session_done, file_done, packets_received, errors, session_begin, size = 0;
  
  for (session_done = 0, errors = 0, session_begin = 0; ;)
  {
    for (packets_received = 0, file_done = 0; ;)
    {
      switch (Receive_Packet(packet_data, &packet_length, NAK_TIMEOUT))
      {
        case 0:
          switch (packet_length)
          {
            /* Abort by sender */
            case -1:
              Send_Byte(ACK);
              return 0;
            /* End of transmission */
            case 0:
              Send_Byte(ACK);
              file_done = 1;
              break;
            /* Normal packet */
            default:
              if ((packet_data[PACKET_SEQNO_INDEX] & 0xff) != (packets_received & 0xff))
              {
                errors ++;
                if (errors > MAX_ERRORS)
                {
                  send_CA();
                  return 0;
                }
                Send_Byte(NAK);
              }
              else
              {
                errors = 0;
                if (packets_received == 0)
                {
                  /* Filename packet */
                  if (packet_data[PACKET_HEADER] != 0)
                  {
                    // Filename packet has valid data
                    if (getname == 0) {
                      for (i = 0, file_ptr = packet_data + PACKET_HEADER; (*file_ptr != 0) && (i < SPIFFS_OBJ_NAME_LEN);)
                      {
                        FileName[i++] = *file_ptr++;
                      }
                      FileName[i++] = '\0';
                    }
                    for (i = 0, file_ptr = packet_data + PACKET_HEADER; (*file_ptr != 0) && (i < packet_length);)
                    {
                      file_ptr++;
                    }
                    for (i = 0, file_ptr ++; (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH);)
                    {
                      file_size[i++] = *file_ptr++;
                    }
                    file_size[i++] = '\0';
                    Str2Int(file_size, &size);

                    // Test the size of the file
                    if (size < 1 || size > maxsize) {
                      file_fd = FILE_NOT_OPENED;
                      /* End session */
                      send_CA();
                      return -4;
                    }

                    /* *** Open the file *** */
                    if (FILE_NOT_OPENED != file_fd) {
                      SPIFFS_close(&fs,file_fd);
                      file_fd = FILE_NOT_OPENED;
                    }
                    file_fd = SPIFFS_open(&fs, (char*)FileName, mode2flag("w"), 0);
                    if (file_fd <= FILE_NOT_OPENED) {
                      file_fd = FILE_NOT_OPENED;
                      /* End session */
                      send_CA();
                      return -2;
                    }
                    file_len = 0;
                    Send_Byte(ACK);
                    Send_Byte(CRC16);
                  }
                  /* Filename packet is empty, end session */
                  else
                  {
                    Send_Byte(ACK);
                    file_done = 1;
                    session_done = 1;
                    break;
                  }
                }
                /* Data packet */
                else
                {
                  /* Write received data to file */
                  if (file_len < size) {
                    file_len = file_len + packet_length;
                    if (file_len > size) {
                      write_len = packet_length - (file_len - size);
                    }
                    else {
                      write_len = packet_length;
                    }
                    if (file_fd <= FILE_NOT_OPENED) {
                      file_fd = FILE_NOT_OPENED;
                      // File not opened, End session
                      send_CA();
                      return -2;
                    }
                    if (SPIFFS_write(&fs,file_fd, (char*)(packet_data + PACKET_HEADER), write_len) < 0)
                    { //failed
                      SPIFFS_close(&fs,file_fd);
                      file_fd = FILE_NOT_OPENED;
                      /* End session */
                      send_CA();
                      return -1;
                    }
                  }
                  //success
                  Send_Byte(ACK);
                }
                packets_received ++;
                session_begin = 1;
              }
          }
          break;
        case 1:
          send_CA();
          return -3;
        default:
          if (session_begin >= 0)
          {
            errors ++;
          }
          if (errors > MAX_ERRORS)
          {
            send_CA();
            return 0;
          }
          Send_Byte(CRC16);
          break;
      }
      if (file_done != 0)
      {
        break;
      }
    }
    if (session_done != 0)
    {
      break;
    }
  }
  return (int32_t)size;
}
Ejemplo n.º 30
0
int32_t Ymodem_Receive(uint8_t *buf)
{
	uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD], file_size[FILE_SIZE_LENGTH], *file_ptr, *buf_ptr;
	int32_t i,j,packet_length, session_done, file_done, packets_received, errors, session_begin, size = 0;

	/* Initialize FlashDestination variable */
	FlashDestination = ApplicationAddress;

	for(session_done = 0, errors = 0, session_begin = 0; ;)
		{
		for(packets_received = 0, file_done = 0, buf_ptr = buf; ;)
			{		
			
			switch(Receive_Packet(packet_data, &packet_length, NAK_TIMEOUT))
				{	
				case 0:
					errors = 0;
					switch (packet_length)
						{
						/* Abort by sender */
						case - 1:
							Send_Byte(ACK);
							return 0;
						
						/* End of transmission */
						case 0:
							Send_Byte(ACK);
							file_done = 1;
							break;
						
						/* Normal packet */
						default:
							if ((packet_data[PACKET_SEQNO_INDEX] & 0xff) != (packets_received & 0xff))//数据包编号
								{
								Send_Byte(NAK);
								}
							else
								{
								if(packets_received == 0)/* 第一次传输文件属性  */
									{
									if(packet_data[PACKET_HEADER] != 0)/* Filename packet has valid data */
										{
										for(i = 0, file_ptr = packet_data + PACKET_HEADER; (*file_ptr != 0) && (i < FILE_NAME_LENGTH);)
											file_name[i++] = *file_ptr++;
										file_name[i++] = '\0';/*接收文件名结束*/
										
										for(i = 0, file_ptr ++; (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH);)
											file_size[i++] = *file_ptr++;
										file_size[i++] = '\0';/*接收文件名大小结束*/
										
										Str2Int(file_size, &size);

										if(size > (FLASH_SIZE - SYSTEM_BOOTLOADER_LENGTH -1))//代码长度超过空间大小
											{
											Send_Byte(CA);
											Send_Byte(CA);
											return -1;
											}
										
										if ((size % PAGE_SIZE) != 0)//根据代码大小分配块
											NbrOfPage = (size / PAGE_SIZE) + 1;
										else
											NbrOfPage = size / PAGE_SIZE;
										
										for (EraseCounter = 0; (EraseCounter < NbrOfPage) && (FLASHStatus == FLASH_OK); EraseCounter++)
											{
											FLASHStatus = FLASH_EraseSector(FlashDestination/PageSize + EraseCounter);//擦除代码所需要块
											FLASHStatus = FLASH_OK;
											}

										Send_Byte(ACK);
										Send_Byte(CRC16);
										}
									else/* Filename packet is empty, end session */
										{
										Send_Byte(ACK);
										file_done = 1;
										session_done = 1;
										break;
										}
									}
								else/* Data packet */
									{
									memcpy(buf_ptr, packet_data + PACKET_HEADER, packet_length);
									RamSource = (uint32_t)buf;
									for (j = 0;(j < packet_length) && (FlashDestination <  ApplicationAddress + size);j += 4)
										{
										/* Program the data received into STM32F10x Flash */
										FLASH_WriteWord(FlashDestination, *(uint32_t*)RamSource);
										if (*(uint32_t*)FlashDestination != *(uint32_t*)RamSource)
											{
											/* End session */
											Send_Byte(CA);
											Send_Byte(CA);
											return -2;
											}
										FlashDestination += 4;
										RamSource += 4;
										}
									Send_Byte(ACK);
									}
								packets_received ++;
								session_begin = 1;//错误计数器
								}
							}
						break;
					
					case 1:
						Send_Byte(CA);
						Send_Byte(CA);
						return -3;
					
					default:
						if (session_begin > 0)
							{
							errors ++;
							}
						if (errors > MAX_ERRORS)
							{
							Send_Byte(CA);
							Send_Byte(CA);
							return 0;
							}
						Send_Byte(CRC16);
						break;
					}	
			if (file_done != 0)
				{
				break;
				}
			}
		if (session_done != 0)
			{
			break;
			}
		}
	
	return (int32_t)size;
}