Esempio n. 1
0
TraceLabel SimulateState_get_trace_label(SimulateState_ptr const self)
{
  TraceLabel trace_label;

  check_integrity(self);

  trace_label = self->trace_label;

  check_integrity(self);

  return trace_label;
}
Esempio n. 2
0
void *SB_Imap::remove(Key_Type pv_id) {
    SB_ML_Type *lp_item;
    SB_ML_Type *lp_prev;
    int         lv_hash;

    lv_hash = hash(pv_id, iv_buckets);
    lp_item = ipp_HT[lv_hash];
    lp_prev = NULL;
    while (lp_item != NULL) {
        if (lp_item->iv_id.i == pv_id) {
            if (lp_prev == NULL)
                ipp_HT[lv_hash] = lp_item->ip_next;
            else
                lp_prev->ip_next = lp_item->ip_next;
#ifdef USE_SB_MAP_STATS
            ip_stats->chain_del(lv_hash); // remove
#endif
            iv_count--;
            iv_mod++;
#ifdef IMAP_CHECK
            check_integrity();
#endif // IMAP_CHECK
            return lp_item;
        }
        lp_prev = lp_item;
        lp_item = lp_item->ip_next;
    }
    return NULL;
}
Esempio n. 3
0
int	synthaxe_error(char *str)
{
  char  *tab_synthaxe[20];

  int   i;
  int   alright;

  alright = 0;
  i = 0;
  init_types(tab_synthaxe);
  early_space(str);
  while (tab_synthaxe[i] != NULL)
    {
      if (strncmp(str, tab_synthaxe[i], strlen(tab_synthaxe[i])) == 0)
	{
	  alright = 1;
	  printf("Déclaration de la %s %s de type %s\n",
		 get_parenthesis(get_name(str)) ? "variable" : "fonction",
		 get_name(str), get_types(str,tab_synthaxe));
	  break;
	}
      i++;
    }
  if (alright == 0)
    return (fprintf(stderr, "%s n'est pas un type valide \n", str));
  return (check_integrity(str, strlen(tab_synthaxe[i])));
}
Esempio n. 4
0
void SB_Smap::putv(Key_Type pp_key, void *pp_value) {
    SML_Type *lp_item;
    int       lv_hash;
    int       lv_len;

    SB_util_assert_cpne(pp_key, NULL); // sw fault
    SB_util_assert_pne(pp_value, NULL); // sw fault
    SB_Smap::removev(pp_key);
    lv_hash = hash(pp_key, iv_buckets);
    lp_item = new SML_Type;
    lp_item->iv_link.ip_next = reinterpret_cast<SB_QL_Type *>(ipp_HT[lv_hash]);
    lv_len = static_cast<int>(strlen(pp_key));
    lp_item->ip_key = new char[lv_len+1];
    strcpy(lp_item->ip_key, pp_key);
    lp_item->ip_value = NULL;
    lp_item->ip_vvalue = pp_value;
    lp_item->iv_use_vvalue = true;
    ipp_HT[lv_hash] = lp_item;
    iv_count++;
    iv_mod++;
#ifdef USE_SB_MAP_STATS
    ip_stats->chain_add(lv_hash);  // putv
#endif
#ifdef SMAP_CHECK
    check_integrity();
#endif // SMAP_CHECK
    if (iv_count > iv_buckets_threshold)
        SB_Smap::resize(iv_buckets_resize);
}
Esempio n. 5
0
void SimulateState_set_all(SimulateState_ptr const self,
                           bdd_ptr const state,
                           TraceLabel const label)
{
  SIMULATE_STATE_CHECK_INSTANCE(self);
  check_integrity(self);

  if ((bdd_ptr)NULL != self->bdd) {
    bdd_free(self->dd_mgr, self->bdd); self->bdd = (bdd_ptr)NULL;
  }

  self->bdd = bdd_dup(state);
  self->trace_label = label;

  check_integrity(self);
}
Esempio n. 6
0
void SimulateState_destroy(SimulateState_ptr self)
{
  SIMULATE_STATE_CHECK_INSTANCE(self);
  check_integrity(self);

  Object_destroy(OBJECT(self), NULL); self = SIMULATE_STATE(NULL);
}
Esempio n. 7
0
inline Triangular_iterator& Triangular_iterator::
operator++()
{
	++_index;
	check_integrity();
	return *this;
}
Esempio n. 8
0
void SB_Smap::remove(Key_Type pp_key, char *pp_value) {
    SML_Type *lp_item;
    SML_Type *lp_prev;
    int       lv_hash;

    SB_util_assert_cpne(pp_key, NULL); // sw fault
    lv_hash = hash(pp_key, iv_buckets);
    lp_item = ipp_HT[lv_hash];
    lp_prev = NULL;
    while (lp_item != NULL) {
        if (strcmp(pp_key, lp_item->ip_key) == 0) {
            if (lp_prev == NULL)
                ipp_HT[lv_hash] = reinterpret_cast<SML_Type *>(lp_item->iv_link.ip_next);
            else
                lp_prev->iv_link.ip_next = lp_item->iv_link.ip_next;
#ifdef USE_SB_MAP_STATS
            ip_stats->chain_del(lv_hash); // remove
#endif
            iv_count--;
            iv_mod++;
#ifdef SMAP_CHECK
            check_integrity();
#endif // SMAP_CHECK
            if (pp_value != NULL)
                strcpy(pp_value, lp_item->ip_value);
            delete [] lp_item->ip_key;
            if (!lp_item->iv_use_vvalue)
                delete [] lp_item->ip_value;
            delete lp_item;
            break;
        }
        lp_prev = lp_item;
        lp_item = reinterpret_cast<SML_Type *>(lp_item->iv_link.ip_next);
    }
}
Esempio n. 9
0
bdd_ptr SimulateState_get_bdd(SimulateState_ptr const self)
{
  bdd_ptr result;

  SIMULATE_STATE_CHECK_INSTANCE(self);
  check_integrity(self);

  if ((bdd_ptr)NULL != self->bdd &&
      TRACE_LABEL_INVALID != self->trace_label) {
    result = bdd_dup(self->bdd);
  }
  else result = (bdd_ptr)NULL;

  check_integrity(self);

  return result;
}
Esempio n. 10
0
inline Triangular_iterator Triangular_iterator::
operator++(int)
{
	Triangular_iterator tmp = *this;
	++_index;
	check_integrity();
	return tmp;
}
Esempio n. 11
0
SimulateState_ptr SimulateState_create(DDMgr_ptr const dd_mgr,
                                       bdd_ptr const bdd,
                                       TraceLabel const trace_label)
{
  SimulateState_ptr self = ALLOC(SimulateState, 1);
  SIMULATE_STATE_CHECK_INSTANCE(self);

  simulate_state_init(self, dd_mgr, bdd, trace_label);

  check_integrity(self);

  return self;
}
Esempio n. 12
0
SimulateState_ptr SimulateState_set_in_env(NuSMVEnv_ptr const env,
                                           bdd_ptr const bdd,
                                           TraceLabel const trace_label)
{
  DDMgr_ptr const dd_mgr = DD_MGR(NuSMVEnv_get_value(env, ENV_DD_MGR));
  SimulateState_ptr current_state;

  if (NuSMVEnv_has_value(env, ENV_SIMULATE_STATE)) {
    current_state =
      SIMULATE_STATE(NuSMVEnv_get_value(env, ENV_SIMULATE_STATE));
    SimulateState_set_all(current_state, bdd, trace_label);
  }
  else {
    current_state = SimulateState_create(dd_mgr, bdd, trace_label);
    NuSMVEnv_set_value(env, ENV_SIMULATE_STATE, (void*)current_state);
  }

  check_integrity(current_state);

  return current_state;
}
Esempio n. 13
0
/*------------------------------------------------------------------------*/
int do_update(char **uuids, int num_uuids, char *device, char *optarg)
{
	char tmpdir[256]="/tmp/ncvupXXXXXX";
	int n;
	int ret=0;
	if (!mkdtemp(tmpdir)) {
		fprintf(stderr,"Can't make temporary directory %s!\n",tmpdir);
		return -2;
	}
//	printf("TEMP DIR %s\n",tmpdir);
	if (unpack(tmpdir,optarg)) {
		fprintf(stderr,"Update file <%s> cannot be unpacked!\n",optarg);
		cleanup(tmpdir);
		return -2;
	}
	if (check_integrity(tmpdir)) {
		fprintf(stderr,"Update file <%s> corrupted!\n",optarg);
		cleanup(tmpdir);
		return -2;
	}
	printf("Update file integrity OK\n");
	printf("NUM uuids %i\n",num_uuids);
	for(n=0;n<num_uuids;n++) {
		if (!uuids[n])
			continue;

		printf("UUID %s: ",uuids[n]);
		fflush(stdout);
		ret=do_single_update(tmpdir, uuids[n], device);
		if (!ret)
			printf("-> Update done <-\n");
		else {
			printf("-> Update failed (ret=%i) <-\n",ret);
			uuids[n]=NULL;
		}
	}

	cleanup(tmpdir);
	return ret;
}
Esempio n. 14
0
void *process_local_buffer(void *arg)
{
  int ret = 0;
  while (1) {
    sem_wait(&mutex);
    if (counter > 0) {

      while ((ret = access_mgmt_area((u32 *)mapped_buffer,
            mgmt_area.my_unique_id)) < 0) {
        debug_print("management area access "
              "not granted\n");
        continue;
      }
#ifdef INTEGRITY
      ti81xx_poll_for_data(&ptr, &mgmt_area,
            mapped_buffer, fp2, &byte_recv);
#elif defined(THPT)
      ti81xx_poll_for_data(&ptr, &mgmt_area,
            mapped_buffer,
              NULL, &byte_recv);
#elif defined(DISPLAY)
      ti81xx_poll_for_data(&ptr, &mgmt_area,
            mapped_buffer,
              NULL, NULL);
#endif
      release_mgmt_area((u32 *)mapped_buffer);
      counter--;
    }
    sem_post(&mutex);
#ifdef INTEGRITY
    if (byte_recv == (1024 * 1024)) {
      integrity_test = check_integrity(fp1, fp2);

      break;
    }
#endif
  }
  pthread_exit(NULL);
}
Esempio n. 15
0
int main(void)
{
    
  usi_enable();
  spiX_initslave(SPIMODE);
  sei();
  

  //Initialize slave
  slave_init();
  
  //Let settings catch up
  _delay_ms(100);
  
  //An initial packet, not sure what it's for, but the other code had it
  prepare_packet("", 0);
  spiX_put(0);
  
  unsigned char input;
  do{
    
    //Wait for SS
    while(!slave_selected());
    
    //Wait for pending transfers
    spiX_wait();
    
    //Read first character from master
    input = spiX_get();
    
    //Is the master telling us to receive?
      //If so, interpret the input and prepare a response packet
    if(input == RECEIVE_CHAR)
    {
      //Retrieve the rest of the packet from master
      receive_packet();
      
      //Check integrity
      if(!check_integrity())
      {
          prep_err();
          continue;
      }
        
      //Lowercase are read operations
      if(incoming_packet[1] > 96 && incoming_packet[1] < 127)
      {
        prep_response(incoming_packet[1]);
      }
      else
      {
        do_action(incoming_packet[1]);
      }
    }
    //Is the master telling us that it's ready to receive?
    else if(input == SEND_CHAR)
    {
      //Send the prepared packet
      send_packet();
    }
    if(waiting_measure){
       slave_run_measure();
       waiting_measure = 0;
    }
    if(waiting_write){
       slave_apply();
       waiting_write = 0;
    }
    
  } while(1);      // Loop forever...
}
Esempio n. 16
0
int main(int argc, char **argv)
{
    int i, retry, ret;

    /* filedescriptor and name of device */
    struct monitor mon;
    char *fn;

    char *datadir = NULL;
    char *pnpname = NULL; /* pnpname for -i parameter */

    /* what to do */
    int dump = 0;
    int ctrl = -1;
    int value = -1;
    int caps = 0;
    int save = 0;
    int force = 0;
    int verbosity = 0;
    int probe = 0;

#ifdef HAVE_GETTEXT
    setlocale(LC_ALL, "");
    bindtextdomain(PACKAGE, LOCALEDIR);
    bindtextdomain("ddccontrol-db", LOCALEDIR);
    textdomain(PACKAGE);
#endif

    fprintf(stdout,
            _("ddccontrol version %s\n"
              "Copyright 2004-2005 Oleg I. Vdovikin ([email protected])\n"
              "Copyright 2004-2006 Nicolas Boichat ([email protected])\n"
              "This program comes with ABSOLUTELY NO WARRANTY.\n"
              "You may redistribute copies of this program under the terms of the GNU General Public License.\n\n"), VERSION);

    while ((i=getopt(argc,argv, "hdr:w:csfvpb:i:")) >= 0)
    {
        switch(i) {
        case 'h':
            usage(argv[0]);
            exit(1);
            break;
        case 'b':
            datadir = optarg;
            break;
        case 'r':
            if ((ctrl = strtol(optarg, NULL, 0)) < 0 || (ctrl > 255))
            {
                fprintf(stderr,_("'%s' does not seem to be a valid register name\n"), optarg);
                exit(1);
            }
            break;
        case 'w':
            if (ctrl == -1) {
                fprintf(stderr,_("You cannot use -w parameter without -r.\n"));
                exit(1);
            }
            if ((value = strtol(optarg, NULL, 0)) < 0 || (value > 65535))
            {
                fprintf(stderr,_("'%s' does not seem to be a valid value.\n"), optarg);
                exit(1);
            }
            break;
        case 'c':
            caps++;
            break;
        case 'd':
            dump++;
            break;
        case 's':
            save++;
            break;
        case 'f':
            force++;
            break;
        case 'v':
            verbosity++;
            break;
        case 'p':
            probe++;
            break;
        case 'i': /* Undocumented developer parameter: check integrity of a specific EDID id */
            pnpname = optarg;
            break;
        }
    }

    ddcci_verbosity(verbosity);
    if (pnpname) {
        check_integrity(datadir, pnpname);
    }

    if ((optind == argc) && (!probe)) /* Nor device, nor probe option specified. */
    {
        usage(argv[0]);
        exit(1);
    }
    else if ((optind != argc) && (probe)) /* Device and probe option specified. */
    {
        usage(argv[0]);
        exit(1);
    }

    if (!ddcci_init(datadir)) {
        printf(_("Unable to initialize ddcci library.\n"));
        exit(1);
    }

    if (probe) {
        fn = NULL;

        struct monitorlist* monlist;
        struct monitorlist* current;

        monlist = ddcci_probe();

        printf(_("Detected monitors :\n"));

        current = monlist;
        while (current != NULL)
        {
            printf(_(" - Device: %s\n"), current->filename);
            printf(_("   DDC/CI supported: %s\n"), current->supported ? _("Yes") : _("No"));
            printf(_("   Monitor Name: %s\n"), current->name);
            printf(_("   Input type: %s\n"), current->digital ? _("Digital") : _("Analog"));

            if ((!fn) && (current->supported))
            {
                printf(_("  (Automatically selected)\n"));
                fn = malloc(strlen(current->filename)+1);
                strcpy(fn, current->filename);
            }

            current = current->next;
        }

        if (fn == NULL) {
            fprintf(stderr, _(
                        "No monitor supporting DDC/CI available.\n"
                        "If your graphics card need it, please check all the required kernel modules are loaded (i2c-dev, and your framebuffer driver).\n"
                    ));
            ddcci_release();
            exit(0);
        }

        ddcci_free_list(monlist);
    }
    else {
        fn = argv[optind];
    }

    fprintf(stdout, _("Reading EDID and initializing DDC/CI at bus %s...\n"), fn);

    if ((ret = ddcci_open(&mon, fn, 0)) < 0) {
        fprintf(stderr, _(
                    "\nDDC/CI at %s is unusable (%d).\n"
                    "If your graphics card need it, please check all the required kernel modules are loaded (i2c-dev, and your framebuffer driver).\n"
                ), fn, ret);
    } else {
        fprintf(stdout, _("\nEDID readings:\n"));
        fprintf(stdout, _("\tPlug and Play ID: %s [%s]\n"),
                mon.pnpid, mon.db ? mon.db->name : NULL);
        fprintf(stdout, _("\tInput type: %s\n"), mon.digital ? _("Digital") : _("Analog"));

        if (mon.fallback) {
            /* Put a big warning (in red if we are writing to a terminal). */
            printf("%s%s\n", isatty(1) ? "\x1B[5;31m" : "", _("=============================== WARNING ==============================="));
            if (mon.fallback == 1) {
                printf(_(
                           "There is no support for your monitor in the database, but ddccontrol is\n"
                           "using a generic profile for your monitor's manufacturer. Some controls\n"
                           "may not be supported, or may not work as expected.\n"));
            }
            else if (mon.fallback == 2) {
                printf(_(
                           "There is no support for your monitor in the database, but ddccontrol is\n"
                           "using a basic generic profile. Many controls will not be supported, and\n"
                           "some controls may not work as expected.\n"));
            }
            printf(_(
                       "Please update ddccontrol-db, or, if you are already using the latest\n"
                       "version, please send the output of the following command to\n"
                       "[email protected]:\n"));
            printf("\nLANG= LC_ALL= ddccontrol -p -c -d\n\n");
            printf(_("Thank you.\n"));
            printf("%s%s\n", _("=============================== WARNING ==============================="), isatty(1) ? "\x1B[0m" : "");
        }

        if (caps) {
            fprintf(stdout, _("\nCapabilities:\n"));

            for (retry = RETRYS; retry; retry--) {
                if (ddcci_caps(&mon) >= 0) {
                    fprintf(stdout, _("Raw output: %s\n"), mon.caps.raw_caps);

                    fprintf(stdout, _("Parsed output: \n"));
                    fprintf(stdout, "\tVCP: ");
                    int i;
                    for (i = 0; i < 256; i++) {
                        if (mon.caps.vcp[i]) {
                            printf("%02x ", i);
                        }
                    }
                    printf("\n");
                    printf(_("\tType: "));
                    switch(mon.caps.type) {
                    case lcd:
                        printf(_("LCD"));
                        break;
                    case crt:
                        printf(_("CRT"));
                        break;
                    case unk:
                        printf(_("Unknown"));
                        break;
                    }
                    printf("\n");
                    break;
                }
            }

            if (retry == 0) {
                fprintf(stderr, _("Capabilities read fail.\n"));
            }
        }

        if (ctrl >= 0) {
            if (value >= 0) {
                int delay = find_write_delay(&mon, ctrl);
                if (delay >= 0) {
                    fprintf(stdout, _("\nWriting 0x%02x, 0x%02x(%d) (%dms delay)...\n"),
                            ctrl, value, value, delay);
                }
                else {
                    fprintf(stdout, _("\nWriting 0x%02x, 0x%02x(%d)...\n"),
                            ctrl, value, value);
                }
                ddcci_writectrl(&mon, ctrl, value, delay);
            } else {
                fprintf(stdout, _("\nReading 0x%02x...\n"), ctrl);
            }

            dumpctrl(&mon, ctrl, 1);
        }

        if (dump) {
            fprintf(stdout, _("\nControls (valid/current/max) [Description - Value name]:\n"));

            for (i = 0; i < 256; i++) {
                dumpctrl(&mon, i, force);
            }
        }
        else if (ctrl == -1 && caps == 0)
        {
            struct monitor_db* monitor = mon.db;
            struct group_db* group;
            struct subgroup_db* subgroup;
            struct control_db* control;
            struct value_db* valued;

            if (monitor) {
                printf("\n= %s\n", monitor->name);

                for (group = monitor->group_list; group != NULL; group = group->next) {
                    printf("> %s\n", group->name);

                    for (subgroup = group->subgroup_list; subgroup != NULL; subgroup = subgroup->next) {
                        printf("\t> %s\n", subgroup->name);

                        for (control = subgroup->control_list; control != NULL; control = control->next) {
                            printf(_("\t\t> id=%s, name=%s, address=%#x, delay=%dms, type=%d\n"),
                                   control->id, control->name, control->address, control->delay, control->type);

                            valued = control->value_list;
                            if (valued) {
                                printf(_("\t\t  Possible values:\n"));
                            }

                            for (; valued != NULL; valued = valued->next) {
                                printf(_("\t\t\t> id=%s - name=%s, value=%d\n"), valued->id, valued->name, valued->value);
                            }

                            for (retry = RETRYS; retry; retry--) {
                                int result;
                                unsigned short value, maximum;

                                if ((result = ddcci_readctrl(&mon, control->address, &value, &maximum)) >= 0) {
                                    printf(
                                        (result > 0)
                                        ? _("\t\t  supported, value=%d, maximum=%d\n")
                                        : _("\t\t  not supported, value=%d, maximum=%d\n"), value, maximum);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        if (save) {
            fprintf(stdout, _("\nSaving settings...\n"));

            ddcci_save(&mon);
        }
    }

    ddcci_close(&mon);

    if (probe) {
        free(fn);
    }

    ddcci_release();
    exit(0);
}
Esempio n. 17
0
MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags): QMainWindow(parent, flags), petri_dish(),
    histogramDialog(0), changed(true), auto_save(false), update_thread(this, this)
{
    setupUi(this);

    connect(&timer, SIGNAL(timeout()), &petri_dish, SLOT(step()));
    connect(&petri_dish, SIGNAL(changed()), worldView, SLOT(queueUpdate()));
    //connect(&petri_dish, SIGNAL(changed()), worldView, SLOT(repaint()));
    connect(&petri_dish, SIGNAL(changed()), this, SLOT(set_stats()));
    connect(runButton, SIGNAL(clicked()), this, SLOT(start_stop()));
    //connect(checkIntegrity, SIGNAL(clicked()), this, SLOT(check_integrity()));
    connect(stepBtn, SIGNAL(clicked()), this, SLOT(step()));

    connect(radViewDefault, SIGNAL(clicked()), &petri_dish, SLOT(set_default_view_mode()));
    connect(radViewBugs, SIGNAL(clicked()), &petri_dish, SLOT(set_bugs_view_mode()));
    connect(radViewEnergy, SIGNAL(clicked()), &petri_dish, SLOT(set_energy_view_mode()));
    connect(radViewAge, SIGNAL(clicked()), &petri_dish, SLOT(set_age_view_mode()));
    connect(radViewSize, SIGNAL(clicked()), &petri_dish, SLOT(set_dna_size_view_mode()));
    connect(radViewDNA, SIGNAL(clicked()), &petri_dish, SLOT(set_dna_view_mode()));
    connect(radViewTerrain, SIGNAL(clicked()), &petri_dish, SLOT(set_terrain_view_mode()));

    connect(actionNew, SIGNAL(triggered()), this, SLOT(new_world()));
    connect(actionSave, SIGNAL(triggered()), this, SLOT(save_world()));
    connect(actionOpen, SIGNAL(triggered()), this, SLOT(load_world()));
    connect(actionSave_As, SIGNAL(triggered()), this, SLOT(save_as_world()));
    connect(settings, SIGNAL(settingsChanged()), this, SLOT(change_world()));
    connect(actionAutoSave, SIGNAL(triggered()), this, SLOT(autosave_world()));

    connect(actionCheck_Integrity, SIGNAL(triggered()), this, SLOT(check_integrity()));

    connect(worldView, SIGNAL(clicked(int, int)), this, SLOT(edit_bug(int, int)));

    connect(idleChk, SIGNAL(clicked(bool)), this, SLOT(enableIdleDetect(bool)));

    connect(&idleTimer, SIGNAL(timeout()), this, SLOT(checkIdle()));

    autosave_timer.setInterval(1000 * 60 * 2); // every two mins
    connect(&autosave_timer, SIGNAL(timeout()), this, SLOT(save_world()));

    petri_dish.set_widget(worldView);
    petri_dish.init(settings->getParams());
    totalEnergy->setText(QString().setNum(petri_dish.get_total_energy()));
    spinDNAVal->setMaximum(settings->getParams().max_data);
    set_stats();

    last_time = 0;
    update_time.start();
    updates_per_sec = 0;


    //update_thread.start();
    horizontalSlider->setValue(1000);
    timer.start(0);

    setAttribute(Qt::WA_QuitOnClose, true);

    repaint();

    if(!qApp->arguments().size() > 1) {
        bool running;
        load_from_file(qApp->arguments().at(1), running);

        if(running) start();
    }
}
Esempio n. 18
0
void* recvThread(void* i_SqsockInfo)
{
	pid_t myPid;
	QSOCKINFO* SqsockInfo = (QSOCKINFO*)i_SqsockInfo;
	int iUartFd = SqsockInfo->iUartFd;
	int iRecvSize=0;
	int iTotalSize=0;
	int iRemainderSize=0;
	int iCopySize=0;
	int iDeleteSize;
	unsigned char uchReadBuff[READ_BUFF_SIZE]={0x0};
	unsigned char uchTmpBuff[READ_BUFF_SIZE]={0x0};
	//struct TcpMsgHead* readMsgHead;
	status_t status;
	static QData* qData;
	unsigned int uiCount;
	int errnum;
	int iDataLen;

	struct MsgHead* pstMsgHead;
	myPid = pthread_self();
	SqsockInfo->recvThreadId= myPid;
	status=EOK;

	tcflush(iUartFd, TCIFLUSH);
	while(1){
		SqsockInfo->iUartState |= 0x01;
		bzero((void*)uchReadBuff, READ_BUFF_SIZE);
		//fprintf(stderr,"### %s():%d tot:%d ###\n",__func__, __LINE__, iTotalSize);
		iRecvSize = read(iUartFd, (void*)uchReadBuff+iTotalSize, READ_BUFF_SIZE-iTotalSize);
		if(iRecvSize <= 0){
			//0.5초 이내 데이터가 안들어오는 경우 
			SqsockInfo->iUartState &= 0xF0;
			while((SqsockInfo->iUartState & 0xF0) == 0x10)
				usleep(500);
		}else{		
			iTotalSize += iRecvSize;
			//fprintf(stderr,"### %s():%d tot:%d ###\n",__func__, __LINE__, iTotalSize);
			//iTotalSize = 0;
			
			while(iTotalSize > 4){
				//헤더 검사
				//fprintf(stderr,"### %s():%d tot:%d ###\n",__func__, __LINE__, iTotalSize);
				iDeleteSize = checkHeader(uchReadBuff, iTotalSize);
				if(iDeleteSize > 0){
					//전송받은 데이터의 처음이 헤더가 아닌 경우 다음 헤더를 찾아 헤더 이전데이터를 삭제한다.
					//fprintf(stderr,"### %s():%d tot:%d del:%d###\n",__func__, __LINE__, iTotalSize, iDeleteSize);
					iTotalSize = iTotalSize - iDeleteSize;
					memset(uchTmpBuff, 0x0, sizeof(uchTmpBuff));
					memcpy(uchTmpBuff, uchReadBuff+iDeleteSize, iTotalSize);
					memset(uchReadBuff, 0x0, sizeof(uchReadBuff));
					memcpy(uchReadBuff, uchTmpBuff, iTotalSize);
				}else{
					//fprintf(stderr,"### %s():%d tot:%d del:%d###\n",__func__, __LINE__, iTotalSize, iDeleteSize);
					pstMsgHead = (struct MsgHead*)uchReadBuff;
					iDataLen = pstMsgHead->uchDataSize; 	    // Data 크기 
					iCopySize = iDataLen + sizeof(struct MsgHead)+CHECK_SUM_LENTH;
					if(iCopySize > iTotalSize){
						//헤더는 정상이지만 아직 모든 데이터를 못 받은 경우
						//fprintf(stderr,"### %s():%d tot:%d cpy:%d###\n",__func__, __LINE__, iTotalSize, iCopySize);
						break;
					}
					//데이터 무결성 확인
					if(check_integrity(uchReadBuff, iCopySize)){
						qData = qDataCreate(iCopySize);
						if (qData == NULL)
							printLog( "by pcw : %s():%d error create queue data",__func__,__LINE__);
						else{
							iRemainderSize = iTotalSize - iCopySize; 
							iTotalSize = iTotalSize - iRemainderSize;
							memcpy(qData->pvData, (void*)uchReadBuff, iCopySize);
							qData->iLength = iCopySize;
							memset(uchTmpBuff, 0x0, sizeof(uchTmpBuff));
							memcpy(uchTmpBuff, uchReadBuff+iCopySize, iRemainderSize);
							memset(uchReadBuff, 0x0, sizeof(uchReadBuff));
							memcpy(uchReadBuff, uchTmpBuff+iCopySize, iRemainderSize);
							status = qPushMutex(SqsockInfo->readQueue, &qData->link);
							if (status != EOK)
								printLog( "by pcw : %s():%d qPushMutex Error(status : %d)",__func__,__LINE__,status);
						}
					}else{
						//무결성이 깨진 경우 무결성 검사한 데이터를 모두 삭제한다.
						fprintf(stderr,"### %s():%d tot:%d cpy:%d###\n",__func__, __LINE__, iTotalSize, iCopySize);
						printRawData(uchReadBuff, iCopySize, RECV);
						iTotalSize = iTotalSize - iCopySize;
						memset(uchTmpBuff, 0x0, sizeof(uchTmpBuff));
						memcpy(uchTmpBuff, uchReadBuff+iCopySize, iTotalSize);
						memset(uchReadBuff, 0x0, sizeof(uchReadBuff));
						memcpy(uchReadBuff, uchTmpBuff, iTotalSize);
						fprintf(stderr,"### %s():%d tot:%d cpy:%d###\n",__func__, __LINE__, iTotalSize, iCopySize);
					}
				}
			}	
			
		}
	}
	//command thread end
	pthread_cancel(SqsockInfo->commandThreadId);
	status = qDestroyMutex (SqsockInfo->readQueue);
	SqsockInfo->readQueue=NULL;
	if(status != EOK)
		printLog( "by pcw : error qDestroyMutex-readQueu\n");
	//sender thread end
	pthread_cancel(SqsockInfo->sendThreadId);
	pthread_exit(SqsockInfo->sendThreadId);
	status = qDestroyMutex (SqsockInfo->writeQueue);
	SqsockInfo->writeQueue = NULL;
	if(status != EOK)
		printLog( "by pcw : error qDestroyMutex-writeQueu\n");
	return NULL;
}
Esempio n. 19
0
inline int Triangular_iterator::
operator*() const
{
	check_integrity();
	return Triangular_iterator::_elems[_index];
}
Esempio n. 20
0
int planet_posn( const int planet_no, const double jd, double *vect_2000)
{
   static POSN_NODE *nodes = NULL;
   static int n_nodes = 0, n_nodes_alloced = 0, curr_node = 0;
   int loc, rval = 0;
#ifdef TIMING_ON
   int64_t t_start;
#endif
   POSN_CACHE *cache;

   assert( fabs( jd) < 1e+9);
   if( !planet_no)            /* the sun */
      {
      vect_2000[0] = vect_2000[1] = vect_2000[2] = 0.;
      return( 0);
      }

   if( planet_no < 0 || n_nodes >= MAX_N_NODES)
      {                                  /* flag to unload everything */
      int i;

      for( i = 0; i < n_nodes; i++)
         if( nodes[i].data)
            free( nodes[i].data);
      if( nodes)
         free( nodes);
      nodes = NULL;
      n_posns_cached = 0;
      n_nodes = n_nodes_alloced = curr_node = 0;
      }

   if( planet_no < 0)
      {
      planet_posn_raw( -1, 0., NULL);
      return( 0);
      }

   if( planet_no == PLANET_POSN_EARTH || planet_no == PLANET_POSN_MOON)
      {
      double moon_loc[3];

      rval = planet_posn( 3, jd, vect_2000);   /* first,  get Earth-Moon */
      if( !rval)                               /* barycenter posn,  then */
         rval = planet_posn( 10, jd, moon_loc);    /* lunar offset vect  */
      if( !rval)
         {
         unsigned i;
         const double EARTH_MOON_BARYCENTER_FACTOR = 82.300679;
         const double factor = (planet_no == PLANET_POSN_EARTH ?
                     -1. / EARTH_MOON_BARYCENTER_FACTOR :
                 1. - 1. / EARTH_MOON_BARYCENTER_FACTOR);

         for( i = 0; i < 3; i++)
            vect_2000[i] += moon_loc[i] * factor;
         }
      return( rval);
      }

   if( !nodes || n_nodes == n_nodes_alloced - 1)
      {
      const unsigned new_n_alloced = 100 + 3 * n_nodes_alloced / 2;

      nodes = (POSN_NODE *)realloc( nodes, new_n_alloced * sizeof( POSN_NODE));
      assert( nodes);
      if( !n_nodes_alloced)      /* set up first node : */
         {
         n_nodes = 1;
         nodes[0].min_jd = -1e+10;
         nodes[0].used = 0;
         nodes[0].data = (POSN_CACHE *)calloc( node_size, sizeof( POSN_CACHE));
         }
      n_nodes_alloced = new_n_alloced;
      }

             /* Now,  find the right node in which to find/store this posn: */
   while( curr_node + 1 < n_nodes && nodes[curr_node + 1].min_jd <= jd)
      curr_node++;
   while( curr_node && jd < nodes[curr_node].min_jd)
      curr_node--;
   assert( jd >= nodes[curr_node].min_jd);
   assert( curr_node == n_nodes - 1 || jd < nodes[curr_node + 1].min_jd);

   cache = nodes[curr_node].data;
   loc = find_within_node( planet_no, jd, cache);

#ifdef TIMING_ON
   t_start = nanoseconds_since_1970( );
#endif

   if( !cache[loc].planet_no)
      {
      cache[loc].planet_no = planet_no;
      cache[loc].jd = jd;
      nodes[curr_node].used++;
      rval = planet_posn_raw( planet_no, jd, cache[loc].vect);
      n_posns_cached++;
      }
   else
      {
      assert( cache[loc].planet_no == planet_no);
      assert( cache[loc].jd == jd);
      memcpy( vect_2000, cache[loc].vect, 3 * sizeof( double));
      return( rval);
      }
#ifdef TIMING_ON
   planet_ns += nanoseconds_since_1970( ) - t_start;
#endif
   memcpy( vect_2000, cache[loc].vect, 3 * sizeof( double));
   assert( nodes[curr_node].used <= splitting_size);
#ifdef CHECK_CACHING_INTEGRITY
   if( n_posns_cached % 10000 == 0)
      check_integrity( nodes, n_nodes);
#endif
   if( nodes[curr_node].used == splitting_size)
      {
      POSN_CACHE *tcache = (POSN_CACHE *)calloc( node_size, sizeof( POSN_CACHE));
      int i, size1 = splitting_size / 2;
      const int size_left = (curr_node ? nodes[curr_node - 1].used : node_size);
      const int size_right = (curr_node < n_nodes - 1 ? nodes[curr_node + 1].used : node_size);

#ifdef CHECK_CACHING_INTEGRITY
      check_integrity( nodes, n_nodes);
#endif
      collapse_and_partition( tcache, cache);
      memset( cache, 0, node_size * sizeof( POSN_CACHE));
      nodes[curr_node].used = 0;
      if( size_left < size_right && size_left < spillover_size)
         {        /* "spill over" to left */
         curr_node--;
         size1 -= size_left / 2;
         if( debug_level > 5)
            debug_printf( "Spilling %d to left: %d\n", curr_node, size1);
         }
      else if( size_right <= size_left && size_right < spillover_size)
         {        /* "spill over" to right */
         size1 += size_right / 2;
         if( debug_level > 5)
            debug_printf( "Spilling %d to right: %d\n", curr_node, size1);
         }
      else        /* create new node */
         {
         memmove( nodes + curr_node + 2, nodes + curr_node + 1,
                  (n_nodes - curr_node - 1) * sizeof( POSN_NODE));
         nodes[curr_node + 1].data = (POSN_CACHE *)calloc( node_size, sizeof( POSN_CACHE));
         nodes[curr_node + 1].used = 0;
         if( debug_level > 5)
            debug_printf( "Splitting node %d\n", curr_node);
         n_nodes++;
         }
      while( tcache[size1].jd == tcache[size1 - 1].jd)
         size1--;
      for( i = 0; i < splitting_size; i++)
         {
         const int n = curr_node + (i < size1 ? 0 : 1);
         POSN_CACHE *cptr = nodes[n].data;
         const int new_loc = find_within_node( tcache[i].planet_no,
                           tcache[i].jd, cptr);

         cptr[new_loc] = tcache[i];
         nodes[n].used++;
         }
      nodes[curr_node + 1].min_jd = tcache[size1].jd;
#ifdef CHECK_CACHING_INTEGRITY
      check_integrity( nodes, n_nodes);
#endif
      free( tcache);
      }
   return( rval);
}
Esempio n. 21
0
static int turn_create_permission(int verbose, app_ur_conn_info *clnet_info,
		ioa_addr *peer_addr, int addrnum)
{

	if(no_permissions || (addrnum<1))
		return 0;

	char saddr[129]="\0";
	if (verbose) {
		addr_to_string(peer_addr,(u08bits*)saddr);
	}

	stun_buffer request_message, response_message;

	beg_cp:

	{
		int cp_sent = 0;

		stun_init_request(STUN_METHOD_CREATE_PERMISSION, &request_message);
		{
			int addrindex;
			for(addrindex=0;addrindex<addrnum;++addrindex) {
				stun_attr_add_addr(&request_message, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, peer_addr+addrindex);
			}
		}

		add_origin(&request_message);

		if(add_integrity(clnet_info, &request_message)<0) return -1;

		stun_attr_add_fingerprint_str(request_message.buf,(size_t*)&(request_message.len));

		while (!cp_sent) {

			int len = send_buffer(clnet_info, &request_message, 0,0);

			if (len > 0) {
				if (verbose) {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "create perm sent: %s\n",saddr);
				}
				cp_sent = 1;
			} else {
				perror("send");
				exit(1);
			}
		}
	}

	////////////<<==create permission send

	if(not_rare_event()) return 0;

	////////create permission response==>>

	{
		int cp_received = 0;
		while (!cp_received) {

			int len = recv_buffer(clnet_info, &response_message, 1, 0, NULL, &request_message);
			if (len > 0) {
				if (verbose) {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
							"cp response received: \n");
				}
				int err_code = 0;
				u08bits err_msg[129];
				if (stun_is_success_response(&response_message)) {

					cp_received = 1;

					if(clnet_info->nonce[0]) {
						if(check_integrity(clnet_info, &response_message)<0)
							return -1;
					}

					if (verbose) {
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "success\n");
					}
				} else if (stun_is_challenge_response_str(response_message.buf, (size_t)response_message.len,
									&err_code,err_msg,sizeof(err_msg),
									clnet_info->realm,clnet_info->nonce,
									clnet_info->server_name, &(clnet_info->oauth))) {
					goto beg_cp;
				} else if (stun_is_error_response(&response_message, &err_code,err_msg,sizeof(err_msg))) {
					cp_received = 1;
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "create permission error %d (%s)\n",
							      err_code,(char*)err_msg);
					return -1;
				} else {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "unknown create permission response\n");
					/* Try again ? */
				}
			} else {
				perror("recv");
				exit(-1);
			}
		}
	}

	return 0;
}
Esempio n. 22
0
static int turn_channel_bind(int verbose, uint16_t *chn,
		app_ur_conn_info *clnet_info, ioa_addr *peer_addr) {

	stun_buffer request_message, response_message;

	beg_bind:

	{
		int cb_sent = 0;

		if(negative_test) {
			*chn = stun_set_channel_bind_request(&request_message, peer_addr, (u16bits)random());
		} else {
			*chn = stun_set_channel_bind_request(&request_message, peer_addr, *chn);
		}

		add_origin(&request_message);

		if(add_integrity(clnet_info, &request_message)<0) return -1;

		stun_attr_add_fingerprint_str(request_message.buf,(size_t*)&(request_message.len));

		while (!cb_sent) {

			int len = send_buffer(clnet_info, &request_message, 0,0);
			if (len > 0) {
				if (verbose) {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "channel bind sent\n");
				}
				cb_sent = 1;
			} else {
				perror("send");
				exit(1);
			}
		}
	}

	////////////<<==channel bind send

	if(not_rare_event()) return 0;

	////////channel bind response==>>

	{
		int cb_received = 0;
		while (!cb_received) {

			int len = recv_buffer(clnet_info, &response_message, 1, 0, NULL, &request_message);
			if (len > 0) {
				if (verbose) {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
							"cb response received: \n");
				}
				int err_code = 0;
				u08bits err_msg[129];
				if (stun_is_success_response(&response_message)) {

					cb_received = 1;

					if(clnet_info->nonce[0]) {
						if(check_integrity(clnet_info, &response_message)<0)
							return -1;
					}

					if (verbose) {
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "success: 0x%x\n",
								(int) (*chn));
					}
				} else if (stun_is_challenge_response_str(response_message.buf, (size_t)response_message.len,
										&err_code,err_msg,sizeof(err_msg),
										clnet_info->realm,clnet_info->nonce,
										clnet_info->server_name, &(clnet_info->oauth))) {
					goto beg_bind;
				} else if (stun_is_error_response(&response_message, &err_code,err_msg,sizeof(err_msg))) {
					cb_received = 1;
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "channel bind: error %d (%s)\n",
							      err_code,(char*)err_msg);
					return -1;
				} else {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "unknown channel bind response\n");
					/* Try again ? */
				}
			} else {
				perror("recv");
				exit(-1);
				break;
			}
		}
	}

	return 0;
}
Esempio n. 23
0
static int clnet_allocate(int verbose,
		app_ur_conn_info *clnet_info,
		ioa_addr *relay_addr,
		int af,
		char *turn_addr, u16bits *turn_port) {

	int af_cycle = 0;
	int reopen_socket = 0;

	int allocate_finished;

	stun_buffer request_message, response_message;

	beg_allocate:

	allocate_finished=0;

	while (!allocate_finished && af_cycle++ < 32) {

		int allocate_sent = 0;

		if(reopen_socket && !use_tcp) {
			socket_closesocket(clnet_info->fd);
			clnet_info->fd = -1;
			if (clnet_connect(addr_get_port(&(clnet_info->remote_addr)), clnet_info->rsaddr, (u08bits*)clnet_info->ifname, clnet_info->lsaddr,
					verbose, clnet_info) < 0) {
				exit(-1);
			}
			reopen_socket = 0;
		}

		int af4 = dual_allocation || (af == STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4);
		int af6 = dual_allocation || (af == STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6);

		uint64_t reservation_token = 0;
		char* rt = NULL;
		int ep = !no_rtcp && !dual_allocation;

		if(!no_rtcp) {
			if (!never_allocate_rtcp && allocate_rtcp) {
				reservation_token = ioa_ntoh64(current_reservation_token);
				rt = (char*) (&reservation_token);
			}
		}

		if(is_TCP_relay()) {
			ep = -1;
		} else if(rt) {
			ep = -1;
		} else if(!ep) {
			ep = (((u08bits)random()) % 2);
			ep = ep-1;
		}

		if(!dos)
			stun_set_allocate_request(&request_message, UCLIENT_SESSION_LIFETIME, af4, af6, relay_transport, mobility, rt, ep);
		else
			stun_set_allocate_request(&request_message, UCLIENT_SESSION_LIFETIME/3, af4, af6, relay_transport, mobility, rt, ep);

		if(bps)
			stun_attr_add_bandwidth_str(request_message.buf, (size_t*)(&(request_message.len)), bps);

		if(dont_fragment)
			stun_attr_add(&request_message, STUN_ATTRIBUTE_DONT_FRAGMENT, NULL, 0);

		add_origin(&request_message);

		if(add_integrity(clnet_info, &request_message)<0) return -1;

		stun_attr_add_fingerprint_str(request_message.buf,(size_t*)&(request_message.len));

		while (!allocate_sent) {

			int len = send_buffer(clnet_info, &request_message,0,0);

			if (len > 0) {
				if (verbose) {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "allocate sent\n");
				}
				allocate_sent = 1;
			} else {
				perror("send");
				exit(1);
			}
		}

		////////////<<==allocate send

		if(not_rare_event()) return 0;

		////////allocate response==>>
		{
			int allocate_received = 0;
			while (!allocate_received) {

				int len = recv_buffer(clnet_info, &response_message, 1, 0, NULL, &request_message);

				if (len > 0) {
					if (verbose) {
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
								"allocate response received: \n");
					}
					response_message.len = len;
					int err_code = 0;
					u08bits err_msg[129];
					if (stun_is_success_response(&response_message)) {
						allocate_received = 1;
						allocate_finished = 1;

						if(clnet_info->nonce[0]) {
							if(check_integrity(clnet_info, &response_message)<0)
								return -1;
						}

						if (verbose) {
							TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "success\n");
						}
						{
							int found = 0;

							stun_attr_ref sar = stun_attr_get_first(&response_message);
							while (sar) {

								int attr_type = stun_attr_get_type(sar);
								if(attr_type == STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS) {

									if (stun_attr_get_addr(&response_message, sar, relay_addr, NULL) < 0) {
										TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
											"%s: !!!: relay addr cannot be received (1)\n",
											__FUNCTION__);
										return -1;
									} else {
										if (verbose) {
											ioa_addr raddr;
											memcpy(&raddr, relay_addr,sizeof(ioa_addr));
											addr_debug_print(verbose, &raddr,"Received relay addr");
										}

										if(!addr_any(relay_addr)) {
											if(relay_addr->ss.sa_family == AF_INET) {
												if(default_address_family != STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6) {
													found = 1;
													addr_cpy(&(clnet_info->relay_addr),relay_addr);
													break;
												}
											}
											if(relay_addr->ss.sa_family == AF_INET6) {
												if(default_address_family == STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6) {
													found = 1;
													addr_cpy(&(clnet_info->relay_addr),relay_addr);
													break;
												}
											}
										}
									}
								}

								sar = stun_attr_get_next(&response_message,sar);
							}

							if(!found) {
								TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
										"%s: !!!: relay addr cannot be received (2)\n",
										__FUNCTION__);
								return -1;
							}
						}

						stun_attr_ref rt_sar = stun_attr_get_first_by_type(
								&response_message, STUN_ATTRIBUTE_RESERVATION_TOKEN);
						uint64_t rtv = stun_attr_get_reservation_token_value(rt_sar);
						current_reservation_token = rtv;
						if (verbose)
							TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
								      "%s: rtv=%llu\n", __FUNCTION__, (long long unsigned int)rtv);

						read_mobility_ticket(clnet_info, &response_message);

					} else if (stun_is_challenge_response_str(response_message.buf, (size_t)response_message.len,
									&err_code,err_msg,sizeof(err_msg),
									clnet_info->realm,clnet_info->nonce,
									clnet_info->server_name, &(clnet_info->oauth))) {
						goto beg_allocate;
					} else if (stun_is_error_response(&response_message, &err_code,err_msg,sizeof(err_msg))) {

						allocate_received = 1;

						if(err_code == 300) {

							if(clnet_info->nonce[0]) {
								if(check_integrity(clnet_info, &response_message)<0)
									return -1;
							}

							ioa_addr alternate_server;
							if(stun_attr_get_first_addr(&response_message, STUN_ATTRIBUTE_ALTERNATE_SERVER, &alternate_server, NULL)==-1) {
								//error
							} else if(turn_addr && turn_port){
								addr_to_string_no_port(&alternate_server, (u08bits*)turn_addr);
								*turn_port = (u16bits)addr_get_port(&alternate_server);
							}

						}

						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "error %d (%s)\n",
								      err_code,(char*)err_msg);
						if (err_code != 437) {
							allocate_finished = 1;
							current_reservation_token = 0;
							return -1;
						} else {
							TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
									"trying allocate again %d...\n", err_code);
							sleep(1);
							reopen_socket = 1;
						}
					} else {
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
									"unknown allocate response\n");
						/* Try again ? */
					}
				} else {
					perror("recv");
					exit(-1);
					break;
				}
			}
		}
	}
	////////////<<== allocate response received

	if(rare_event()) return 0;

	if(!allocate_finished) {
	  TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
			"Cannot complete Allocation\n");
	  exit(-1);
	}

	allocate_rtcp = !allocate_rtcp;

	if (1) {

	  af_cycle = 0;

	  if(clnet_info->s_mobile_id[0]) {

		  int fd = clnet_info->fd;
		  SSL* ssl = clnet_info->ssl;

		  int close_now = (int)(random()%2);

		  if(close_now) {
			  int close_socket = (int)(random()%2);
			  if(ssl && !close_socket) {
				  SSL_shutdown(ssl);
				  SSL_FREE(ssl);
				  fd = -1;
			  } else if(fd>=0) {
				  close(fd);
				  fd = -1;
				  ssl = NULL;
			  }
		  }

		  app_ur_conn_info ci;
		  ns_bcopy(clnet_info,&ci,sizeof(ci));
		  ci.fd = -1;
		  ci.ssl = NULL;
		  clnet_info->fd = -1;
		  clnet_info->ssl = NULL;
		  //Reopen:
		  if(clnet_connect(addr_get_port(&(ci.remote_addr)), ci.rsaddr,
		  		(unsigned char*)ci.ifname, ci.lsaddr, clnet_verbose,
		  		clnet_info)<0) {
			  exit(-1);
		  }

		  if(ssl) {
			  SSL_shutdown(ssl);
		  	  SSL_FREE(ssl);
		  } else if(fd>=0) {
		  	  close(fd);
		  }
	  }

		beg_refresh:

	  if(af_cycle++>32) {
	    TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
			  "Cannot complete Refresh\n");
	    exit(-1);
	  }

		//==>>refresh request, for an example only:
		{
			int refresh_sent = 0;

			stun_init_request(STUN_METHOD_REFRESH, &request_message);
			uint32_t lt = htonl(UCLIENT_SESSION_LIFETIME);
			stun_attr_add(&request_message, STUN_ATTRIBUTE_LIFETIME, (const char*) &lt, 4);

			if(clnet_info->s_mobile_id[0]) {
				stun_attr_add(&request_message, STUN_ATTRIBUTE_MOBILITY_TICKET, (const char*)clnet_info->s_mobile_id, strlen(clnet_info->s_mobile_id));
			}

			if(dual_allocation && !mobility) {
				int t = ((u08bits)random())%3;
				if(t) {
					u08bits field[4];
					field[0] = (t==1) ? (u08bits)STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4 : (u08bits)STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6;
					field[1]=0;
					field[2]=0;
					field[3]=0;
					stun_attr_add(&request_message, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY, (const char*) field, 4);
				}
			}

			add_origin(&request_message);

			if(add_integrity(clnet_info, &request_message)<0) return -1;

			stun_attr_add_fingerprint_str(request_message.buf,(size_t*)&(request_message.len));

			while (!refresh_sent) {

				int len = send_buffer(clnet_info, &request_message, 0,0);

				if (len > 0) {
					if (verbose) {
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "refresh sent\n");
					}
					refresh_sent = 1;

					if(clnet_info->s_mobile_id[0]) {
						usleep(10000);
						send_buffer(clnet_info, &request_message, 0,0);
					}
				} else {
					perror("send");
					exit(1);
				}
			}
		}

		if(not_rare_event()) return 0;

		////////refresh response==>>
		{
			int refresh_received = 0;
			while (!refresh_received) {

				int len = recv_buffer(clnet_info, &response_message, 1, 0, NULL, &request_message);

				if(clnet_info->s_mobile_id[0]) {
					len = recv_buffer(clnet_info, &response_message, 1, 0, NULL, &request_message);
				}

				if (len > 0) {
					if (verbose) {
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
								"refresh response received: \n");
					}
					response_message.len = len;
					int err_code = 0;
					u08bits err_msg[129];
					if (stun_is_success_response(&response_message)) {
						read_mobility_ticket(clnet_info, &response_message);
						refresh_received = 1;
						if (verbose) {
							TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "success\n");
						}
					} else if (stun_is_challenge_response_str(response_message.buf, (size_t)response_message.len,
										&err_code,err_msg,sizeof(err_msg),
										clnet_info->realm,clnet_info->nonce,
										clnet_info->server_name, &(clnet_info->oauth))) {
						goto beg_refresh;
					} else if (stun_is_error_response(&response_message, &err_code,err_msg,sizeof(err_msg))) {
						refresh_received = 1;
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "error %d (%s)\n",
								      err_code,(char*)err_msg);
						return -1;
					} else {
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "unknown refresh response\n");
						/* Try again ? */
					}
				} else {
					perror("recv");
					exit(-1);
					break;
				}
			}
		}
	}

	return 0;
}
Esempio n. 24
0
static int turn_tcp_connection_bind(int verbose, app_ur_conn_info *clnet_info, app_tcp_conn_info *atc, int errorOK) {

	stun_buffer request_message, response_message;

	beg_cb:

	{
		int cb_sent = 0;

		u32bits cid = atc->cid;

		stun_init_request(STUN_METHOD_CONNECTION_BIND, &request_message);

		stun_attr_add(&request_message, STUN_ATTRIBUTE_CONNECTION_ID, (const s08bits*)&cid,4);

		add_origin(&request_message);

		if(add_integrity(clnet_info, &request_message)<0) return -1;

		stun_attr_add_fingerprint_str(request_message.buf,(size_t*)&(request_message.len));

		while (!cb_sent) {

			int len = send_buffer(clnet_info, &request_message, 1, atc);

			if (len > 0) {
				if (verbose) {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "connection bind sent\n");
				}
				cb_sent = 1;
			} else {
				if(errorOK)
					return 0;
				perror("send");
				exit(1);
			}
		}
	}

	////////////<<==connection bind send

	if(not_rare_event()) return 0;

	////////connection bind response==>>

	{
		int cb_received = 0;
		while (!cb_received) {

			int len = recv_buffer(clnet_info, &response_message, 1, 1, atc, &request_message);
			if (len > 0) {
				if (verbose) {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
							"connect bind response received: \n");
				}
				int err_code = 0;
				u08bits err_msg[129];
				if (stun_is_success_response(&response_message)) {

					if(clnet_info->nonce[0]) {
						if(check_integrity(clnet_info, &response_message)<0)
							return -1;
					}

					if(stun_get_method(&response_message)!=STUN_METHOD_CONNECTION_BIND)
						continue;
					cb_received = 1;
					if (verbose) {
						TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "success\n");
					}
					atc->tcp_data_bound = 1;
				} else if (stun_is_challenge_response_str(response_message.buf, (size_t)response_message.len,
										&err_code,err_msg,sizeof(err_msg),
										clnet_info->realm,clnet_info->nonce,
										clnet_info->server_name, &(clnet_info->oauth))) {
					goto beg_cb;
				} else if (stun_is_error_response(&response_message, &err_code,err_msg,sizeof(err_msg))) {
					cb_received = 1;
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "connection bind error %d (%s)\n",
							      err_code,(char*)err_msg);
					return -1;
				} else {
					TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "unknown connection bind response\n");
					/* Try again ? */
				}
			} else {
				if(errorOK)
					return 0;
				perror("recv");
				exit(-1);
			}
		}
	}

	return 0;
}