void command_put(int sfd_client, struct packet* chp, char* filename) { FILE* f = fopen(filename, "rb"); // Yo! if(!f) { fprintf(stderr, "File could not be opened for reading. Aborting...\n"); return; } clear_packet(chp); chp->type = REQU; chp->comid = PUT; strcpy(chp->buffer, filename); send_packet(sfd_client, chp); recv_packet(sfd_client, chp); //printpacket(chp, HP); if(chp->type == INFO && chp->comid == PUT && strlen(chp->buffer)) { printf("\t%s\n", chp->buffer); chp->type = DATA; send_file(sfd_client, chp, f); fclose(f); } else fprintf(stderr, "Error sending file.\n"); send_EOT(sfd_client, chp); }
void command_rget(int sfd_client, struct packet* chp) { char temp[LENBUFFER]; clear_packet(chp); chp->type = REQU; chp->comid = RGET; send_packet(sfd_client, chp); recv_packet(sfd_client, chp); //printpacket(chp, HP); while(chp->type == REQU) { if(chp->comid == LMKDIR) { strcpy(temp, chp->buffer); command_lmkdir(temp); } else if(chp->comid == LCD) { strcpy(temp, chp->buffer); command_lcd(temp); } else if(chp->comid == GET) { strcpy(temp, chp->buffer); command_get(sfd_client, chp, temp); } recv_packet(sfd_client, chp); //printpacket(chp, HP); } if(chp->type == EOT) printf("\tTransmission successfully ended.\n"); else fprintf(stderr, "There was a problem completing the request.\n"); }
void xvar::set(const void *pdata, size_t size) { assert(pdata); clear_packet(); m_type=XVAR_TYPE_PACKED; m_pPacket=xpackdata::alloc_packed_data(size); memcpy(m_pPacket->buffer(),pdata,size); }
void tgl_do_messages_mark_read_encr (struct tgl_state *TLS, tgl_peer_id_t id, long long access_hash, int last_time, void (*callback)(struct tgl_state *TLS, void *callback_extra, int), void *callback_extra) { clear_packet (); out_int (CODE_messages_read_encrypted_history); out_int (CODE_input_encrypted_chat); out_int (tgl_get_peer_id (id)); out_long (access_hash); out_int (last_time); tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &mark_read_encr_methods, tgl_peer_get (TLS, id), callback, callback_extra); }
void tgl_do_create_encr_chat_request (struct tgl_state *TLS, int user_id, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra) { clear_packet (); out_int (CODE_messages_get_dh_config); out_int (TLS->encr_param_version); out_int (256); void **x = talloc (2 * sizeof (void *)); x[0] = tgl_do_send_create_encr_chat; x[1] = (void *)(long)(user_id); tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &get_dh_config_methods, x, callback, callback_extra); }
void cc708_reset(cc708_service_decoder *decoders) { for (int i = 0; i<CCX_DECODERS_708_MAX_SERVICES; i++) { cc708_service_reset (&decoders[i]); } // Empty packet buffer clear_packet(&decoders[0]); decoders[0].parent->m_last_seq = -1; }
void cc708_reset() { printf (">>> Entry in cc708_reset()\n"); // Clear states of decoders cc708_service_reset(&decoders[0]); cc708_service_reset(&decoders[1]); // Empty packet buffer clear_packet(); last_seq=-1; resets_708++; }
/* Returns 0 for success, or -1 on failure. */ static int save_packet(ogg_packet *packet, vcut_packet *p) { clear_packet(p); p->length = packet->bytes; p->packet = vcut_malloc(p->length); if(!p->packet) return -1; memcpy(p->packet, packet->packet, p->length); return 0; }
void command_pwd(int sfd_client, struct packet* chp) { clear_packet(chp); chp->type = REQU; chp->comid = PWD; send_packet(sfd_client, chp); recv_packet(sfd_client, chp); if(chp->type == DATA && chp->comid == PWD && strlen(chp->buffer) > 0) printf("\t%s\n", chp->buffer); else fprintf(stderr, "\tError retrieving information.\n"); }
void command_cd(int sfd_client, struct packet* chp, char* path) { clear_packet(chp); chp->type = REQU; chp->comid = CD; strcpy(chp->buffer, path); send_packet(sfd_client, chp); recv_packet(sfd_client, chp); if(chp->type == INFO && chp->comid == CD && !strcmp(chp->buffer, "success")) ; else fprintf(stderr, "\tError executing command on the server.\n"); }
xvar& xvar::operator = (const wchar_t* str) { clear_packet(); if(str==0) { m_type=0; m_pData=0; return *this; } m_type=XVAR_TYPE_WSTR; unsigned size=(unsigned)wcslen(str)+1; m_pPacket=xpackdata::alloc_packed_data(sizeof(wchar_t)*size); wchar_t* pstr=(wchar_t*)m_pPacket->buffer(); wcscpy(pstr,str); return *this; }
xvar& xvar::operator = (const char* str) { clear_packet(); if(str==0) { m_type=0; m_pData=0; return *this; } m_type=XVAR_TYPE_STR; unsigned size=(unsigned)strlen(str)+1; m_pPacket=xpackdata::alloc_packed_data(size); char* pstr=(char*)m_pPacket->buffer(); strcpy(pstr,str); return *this; }
void tgl_do_send_encr_msg (struct tgl_state *TLS, struct tgl_message *M, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_message *M), void *callback_extra) { if (M->flags & TGLMF_SERVICE) { tgl_do_send_encr_msg_action (TLS, M, callback, callback_extra); return; } tgl_peer_t *P = tgl_peer_get (TLS, M->to_id); if (!P || P->encr_chat.state != sc_ok) { vlogprintf (E_WARNING, "Unknown encrypted chat\n"); if (callback) { callback (TLS, callback_extra, 0, M); } return; } assert (M->flags & TGLMF_ENCRYPTED); clear_packet (); out_int (CODE_messages_send_encrypted); out_int (CODE_input_encrypted_chat); out_int (tgl_get_peer_id (M->to_id)); out_long (P->encr_chat.access_hash); out_long (M->id); encr_start (); out_int (CODE_decrypted_message_layer); out_random (15 + 4 * (lrand48 () % 3)); out_int (TGL_ENCRYPTED_LAYER); out_int (2 * P->encr_chat.in_seq_no + (P->encr_chat.admin_id != TLS->our_id)); out_int (2 * P->encr_chat.out_seq_no + (P->encr_chat.admin_id == TLS->our_id) - 2); out_int (CODE_decrypted_message); out_long (M->id); out_int (P->encr_chat.ttl); out_cstring ((void *)M->message, M->message_len); switch (M->media.type) { case tgl_message_media_none: out_int (CODE_decrypted_message_media_empty); break; case tgl_message_media_geo: out_int (CODE_decrypted_message_media_geo_point); out_double (M->media.geo.latitude); out_double (M->media.geo.longitude); break; default: assert (0); } encr_finish (&P->encr_chat); tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &msg_send_encr_methods, M, callback, callback_extra); }
void command_ls(int sfd_client, struct packet* chp) { clear_packet(chp); chp->type = REQU; chp->comid = LS; send_packet(sfd_client, chp); while(chp->type != EOT) { if(chp->type == DATA && chp->comid == LS && strlen(chp->buffer)) printf("\t%s\n", chp->buffer); /* else fprintf(stderr, "\tError executing command on the server.\n"); */ recv_packet(sfd_client, chp); } }
void command_mkdir(int sfd_client, struct packet* chp, char* dirname) { clear_packet(chp); chp->type = REQU; chp->comid = MKDIR; strcpy(chp->buffer, dirname); send_packet(sfd_client, chp); recv_packet(sfd_client, chp); if(chp->type == INFO && chp->comid == MKDIR) { if(!strcmp(chp->buffer, "success")) printf("\tCreated directory on server.\n"); else if(!strcmp(chp->buffer, "already exists")) printf("\tDirectory already exitst on server.\n"); } else fprintf(stderr, "\tError executing command on the server.\n"); }
void tgl_do_accept_encr_chat_request (struct tgl_state *TLS, struct tgl_secret_chat *E, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra) { if (E->state != sc_request) { if (callback) { callback (TLS, callback_extra, 0, E); } return; } assert (E->state == sc_request); clear_packet (); out_int (CODE_messages_get_dh_config); out_int (TLS->encr_param_version); out_int (256); void **x = talloc (2 * sizeof (void *)); x[0] = tgl_do_send_accept_encr_chat; x[1] = E; tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &get_dh_config_methods, x, callback, callback_extra); }
void command_mgetwild(int sfd_client, struct packet* chp) { clear_packet(chp); chp->type = REQU; chp->comid = LS; send_packet(sfd_client, chp); struct command* cmd = (struct command*) malloc(sizeof(struct command)); cmd->id = MGETWILD; cmd->npaths = 0; cmd->paths = NULL; while(chp->type != EOT) { if(chp->type == DATA && chp->comid == LS && strlen(chp->buffer)) if(*chp->buffer == 'F') append_path(cmd, chp->buffer + 6); send_packet(sfd_client, chp); } command_mget(sfd_client, chp, cmd->npaths, cmd->paths); }
void clear_all_except_setup(void) { int i, j = 0; char *ptr; for (i=0; i<ACQ_MSGQ_SIZE; i++) if (packet[i].message_type==ACQ_MSGQ_SETUP_COLLECTION) { /* keep the dataset name intact but clear the rest (including the trigger details) */ ptr = (char *)packet[i].data; while (ptr[j]) j++; // while (j<(DATASIZE*sizeof(int))) {ptr[j]=0; j++;}; while (j<((DATASIZE-9012)*sizeof(int))) {ptr[j]=0; j++;}; j+=12*sizeof(int); while (j<(DATASIZE)*sizeof(int)) {ptr[j]=0; j++;}; numTrigger = 0; } else { /* clear the packet header and data */ clear_packet(i); } }
void command_get(int sfd_client, struct packet* chp, char* filename) { FILE* f = fopen(filename, "wb"); if(!f) { fprintf(stderr, "File could not be opened for writing. Aborting...\n"); return; } clear_packet(chp); chp->type = REQU; chp->comid = GET; strcpy(chp->buffer, filename); send_packet(sfd_client, chp); recv_packet(sfd_client, chp); //printpacket(chp, HP); if(chp->type == INFO && chp->comid == GET && strlen(chp->buffer)) { printf("\t%s\n", chp->buffer); receive_file(sfd_client, chp, f); fclose(f); } else fprintf(stderr, "Error getting remote file : <%s>\n", filename); }
void clear_all(void) { int i; for (i=0; i<ACQ_MSGQ_SIZE; i++) clear_packet(i); }
void tgl_do_send_create_encr_chat (struct tgl_state *TLS, void *x, unsigned char *random, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra) { int user_id = (long)x; int i; unsigned char random_here[256]; tglt_secure_random (random_here, 256); for (i = 0; i < 256; i++) { random[i] ^= random_here[i]; } BIGNUM *a = BN_bin2bn (random, 256, 0); ensure_ptr (a); BIGNUM *p = BN_bin2bn (TLS->encr_prime, 256, 0); ensure_ptr (p); BIGNUM *g = BN_new (); ensure_ptr (g); ensure (BN_set_word (g, TLS->encr_root)); BIGNUM *r = BN_new (); ensure_ptr (r); ensure (BN_mod_exp (r, g, a, p, TLS->BN_ctx)); BN_clear_free (a); static char g_a[256]; memset (g_a, 0, 256); BN_bn2bin (r, (void *)(g_a + (256 - BN_num_bytes (r)))); int t = lrand48 (); while (tgl_peer_get (TLS, TGL_MK_ENCR_CHAT (t))) { t = lrand48 (); } //bl_do_encr_chat_init (TLS, t, user_id, (void *)random, (void *)g_a); int state = sc_waiting; bl_do_encr_chat_new (TLS, t, NULL, NULL, &TLS->our_id, &user_id, random, NULL, NULL, &state, NULL, NULL, NULL, NULL, NULL, NULL, TGLPF_CREATE | TGLPF_CREATED); tgl_peer_t *_E = tgl_peer_get (TLS, TGL_MK_ENCR_CHAT (t)); assert (_E); struct tgl_secret_chat *E = &_E->encr_chat; clear_packet (); out_int (CODE_messages_request_encryption); tgl_peer_t *U = tgl_peer_get (TLS, TGL_MK_USER (E->user_id)); assert (U); if (U && U->user.access_hash) { out_int (CODE_input_user_foreign); out_int (E->user_id); out_long (U->user.access_hash); } else { out_int (CODE_input_user_contact); out_int (E->user_id); } out_int (tgl_get_peer_id (E->id)); out_cstring (g_a, 256); //write_secret_chat_file (); BN_clear_free (g); BN_clear_free (p); BN_clear_free (r); tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &send_encr_request_methods, E, callback, callback_extra); }
void tgl_do_send_accept_encr_chat (struct tgl_state *TLS, struct tgl_secret_chat *E, unsigned char *random, void (*callback)(struct tgl_state *TLS,void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra) { int i; int ok = 0; for (i = 0; i < 64; i++) { if (E->key[i]) { ok = 1; break; } } if (ok) { if (callback) { callback (TLS, callback_extra, 1, E); } return; } // Already generated key for this chat assert (E->g_key); assert (TLS->BN_ctx); unsigned char random_here[256]; tglt_secure_random (random_here, 256); for (i = 0; i < 256; i++) { random[i] ^= random_here[i]; } BIGNUM *b = BN_bin2bn (random, 256, 0); ensure_ptr (b); BIGNUM *g_a = BN_bin2bn (E->g_key, 256, 0); ensure_ptr (g_a); assert (tglmp_check_g_a (TLS, TLS->encr_prime_bn, g_a) >= 0); //if (!ctx) { // ctx = BN_CTX_new (); // ensure_ptr (ctx); //} BIGNUM *p = TLS->encr_prime_bn; BIGNUM *r = BN_new (); ensure_ptr (r); ensure (BN_mod_exp (r, g_a, b, p, TLS->BN_ctx)); static unsigned char kk[256]; memset (kk, 0, sizeof (kk)); BN_bn2bin (r, kk + (256 - BN_num_bytes (r))); static unsigned char sha_buffer[20]; sha1 (kk, 256, sha_buffer); long long fingerprint = *(long long *)(sha_buffer + 12); //bl_do_encr_chat_set_key (TLS, E, kk, *(long long *)(sha_buffer + 12)); //bl_do_encr_chat_set_sha (TLS, E, sha_buffer); int state = sc_ok; bl_do_encr_chat_new (TLS, tgl_get_peer_id (E->id), NULL, NULL, NULL, NULL, kk, NULL, sha_buffer, &state, NULL, NULL, NULL, NULL, NULL, &fingerprint, TGL_FLAGS_UNCHANGED ); clear_packet (); out_int (CODE_messages_accept_encryption); out_int (CODE_input_encrypted_chat); out_int (tgl_get_peer_id (E->id)); out_long (E->access_hash); ensure (BN_set_word (g_a, TLS->encr_root)); ensure (BN_mod_exp (r, g_a, b, p, TLS->BN_ctx)); static unsigned char buf[256]; memset (buf, 0, sizeof (buf)); BN_bn2bin (r, buf + (256 - BN_num_bytes (r))); out_cstring ((void *)buf, 256); out_long (E->key_fingerprint); BN_clear_free (b); BN_clear_free (g_a); BN_clear_free (r); tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &send_encr_accept_methods, E, callback, callback_extra); }
void main(){ CyGlobalIntEnable; // Start up initial mote processes SleepTimer_Start(); isr_SleepTimer_StartEx(sleepTimerWake_INT); FS_Init(); // SD Card modem_set_api_feed(FEED_ID, API_KEY); modem_start(); ultrasonic_start(); solinst_start(); ADC_SAR_1_Start(); //modem_power_off(); packet_ready = 0u; take_reading = 1u; t_sample = 2u; // Initialize Sample Period to 2 minutes trigger_sampler = 0u; // Initialize automated sampler to not take a sample bottle_count = 0u; // Initialize bottle count to zero NeoRTC_Start(rtcCallBackReceived); // Start and enable the RTC. NeoRTC_Set_Repeating_Minute_Alarm(t_sample); // Set 1-minute alarm // Uncomment below to set RTC /* NeoRtcTimeStruct tm = { .second = 00, .minute = 54, .hour = 18, .day = 27, .weekday = 2, .month = 5, .year = 2014, } ; RTC_WriteTime(tm); //sets time */ for(;;){ RTC_Process_Tasks(); // Loop continuously and take a reading // every "t_sample" minutes. // The variable "take_reading" is set to TRUE // by rtcCallBackReceived() defined after the for() loop if(take_reading){ // Turn on the modem to update state variables: // sampling frequency; triggering the autosampler modem_power_on(); if (clear_packet(data_packet)) { packet_ready = 0u; } // To communicate with the IoT platform, the node // 1) listens on a given port and 2) parses an incoming string // for relevant commands. Once a packet is ready to send (3), // the node 4) transmits the packet. This is achieved in as little // as four lines of code by leveraging an existing TCP/IP library. // // 1) modem_get_packet() // 2) packet_get_uint8() // 3) sprintf(data_packet, ... // 4) modem_send_packet() // if (modem_get_packet(data_packet,"t_sample,trigger_sampler")) { // Read in any updated values if(packet_get_uint8(data_packet, "t_sample", &tmp)){ t_sample = tmp; } if(packet_get_uint8(data_packet, "trigger_sampler", &tmp)){ trigger_sampler = tmp; } } /* if (send_attempts > 0) { debug_write("New reading taken before previous packet was sent"); } */ // Trigger the autosampler to collect the sample // if a sample is requested if (trigger_sampler){ // Send in acknowledgement that packet containing // info re:automated sampler has been received: modem_send_packet("trigger_sampler, 0"); trigger_sampler = 0; // Update the value locally // Trigger the autosampler as long as there are still available samples // If bottle_count >= MAX_BOTTLE_COUNT, skip taking a sample and avoid // waiting for the code to timeout if (bottle_count < MAX_BOTTLE_COUNT) { // Turn off modem to conserve energy modem_power_off(); // Start up the autosampler processes // and power on the autosampler autosampler_start(); autosampler_power_on(); // Trigger the autosampler and update current bottle_count autosampler_take_sample(&bottle_count); // Power off the autosampler // and shut down the autosampler processes autosampler_power_off(); autosampler_stop(); } else { debug_write("bottle_count >= MAX_BOTTLE_COUNT"); } } // Construct the data packet that will be transmitted // by the sensor node, starting with the bottle the // autosampler last collected a sample in // (the packet is in .csv format) sprintf(data_packet,"%s, %u\r\n", "bottle", bottle_count); // Get Sensor Readings for: // Depth, Pressure, Temperature, Conductivity // and update the data packet if (solinst_get_reading(&solinst_reading)){ sprintf(data_packet,"%s%s, %f\r\n", data_packet, "depth_press", solinst_reading.depth); sprintf(data_packet,"%s%s, %f\r\n", data_packet, "temp_press", solinst_reading.temp); } if (ultrasonic_get_reading(&ultrasonic_reading)){ sprintf(data_packet,"%s%s, %f\r\n", data_packet, "depth_sonic", ultrasonic_reading.depth); } if (ReadBatteryVoltage(&vBattery)){ sprintf(data_packet,"%s%s, %f\r\n", data_packet, "V_batt", vBattery); } // An example of writing data in JSON format // This was replaced with .csv format due to // .csv's smaller packet size /* sprintf(data_packet, "{" "\"method\":\"put\"," "\"resource\":\"/feeds/%d\"," "\"headers\":{\"X-ApiKey\":\"%s\"}," "\"body\":{\"version\":\"1.0.0\",\"datastreams\":[" "{ \"id\" : \"depth_sonic\", \"current_value\" : \"%f\"}," "{ \"id\" : \"depth_press\", \"current_value\" : \"%f\"}," "{ \"id\" : \"temp_press\", \"current_value\" : \"%f\"}," "{ \"id\" : \"trigger_sampler\", \"current_value\" : \"%d\"}," "{ \"id\" : \"V_batt\", \"current_value\" : \"%f\"}" "]}}", FEED_ID,API_KEY, ultrasonic_reading.depth, solinst_reading.depth, solinst_reading.temp,0u,vBattery); */ // Update flags for sending a packet and taking sensor readings packet_ready = 1u; take_reading = 0u; //send_attempts = 0u; // Once the flag for packet_ready has been set, // send the packet and save the packet locally } else if(packet_ready){ isr_SleepTimer_Stop; // <============= ADDRESS THIS WITH B.K. // Power on the modem in case it was turned off modem_power_on(); // modem_state should now be IDLE or READY // and we can send the packet modem_send_packet(data_packet); // Power off the modem and conserve energy modem_power_off(); // Backup data to SD Card // Use the current time to time-stamp the current reading NeoRtcTimeStruct tm_neo = NeoRTC_Read_Time(); // Overwrite current data_packet with time-stamped data sprintf(data_packet, "\r\n%d:%d:%d %d/%d/%d -- [ID %d] u_d=%f s_d=%f s_t=%f bottle=%d v_b=%f", tm_neo.hour, tm_neo.minute, tm_neo.second, tm_neo.day, tm_neo.month, tm_neo.year, moteID, ultrasonic_reading.depth, solinst_reading.depth, solinst_reading.temp,bottle_count,vBattery); // Write data_packet to a *.txt file on the SD Card Write_To_SD_Card("data.txt","a",data_packet,strlen(data_packet)); // Clear the current packet in preparation for the next reading // when the node awakens from sleep if (clear_packet(data_packet)) { packet_ready = 0u; } // If either the sensor node should take a reading nor send a packet // go to low power mode to increase battery life }else{ // Set repeating alarm to trigger every "t_sample" minutes NeoRTC_Set_Repeating_Minute_Alarm(t_sample); Goto_Low_Power_Mode(); } CyDelay(1u); // Quick Pause to prevent locking } }
void tgl_do_send_encr_msg_action (struct tgl_state *TLS, struct tgl_message *M, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_message *M), void *callback_extra) { tgl_peer_t *P = tgl_peer_get (TLS, M->to_id); if (!P || P->encr_chat.state != sc_ok) { vlogprintf (E_WARNING, "Unknown encrypted chat\n"); if (callback) { callback (TLS, callback_extra, 0, 0); } return; } assert (M->flags & TGLMF_ENCRYPTED); clear_packet (); out_int (CODE_messages_send_encrypted_service); out_int (CODE_input_encrypted_chat); out_int (tgl_get_peer_id (M->to_id)); out_long (P->encr_chat.access_hash); out_long (M->id); encr_start (); out_int (CODE_decrypted_message_layer); out_random (15 + 4 * (lrand48 () % 3)); out_int (TGL_ENCRYPTED_LAYER); out_int (2 * P->encr_chat.in_seq_no + (P->encr_chat.admin_id != TLS->our_id)); out_int (2 * P->encr_chat.out_seq_no + (P->encr_chat.admin_id == TLS->our_id) - 2); out_int (CODE_decrypted_message_service); out_long (M->id); switch (M->action.type) { case tgl_message_action_notify_layer: out_int (CODE_decrypted_message_action_notify_layer); out_int (M->action.layer); break; case tgl_message_action_set_message_ttl: out_int (CODE_decrypted_message_action_set_message_t_t_l); out_int (M->action.ttl); break; case tgl_message_action_request_key: out_int (CODE_decrypted_message_action_request_key); out_long (M->action.exchange_id); out_cstring ((void *)M->action.g_a, 256); break; case tgl_message_action_accept_key: out_int (CODE_decrypted_message_action_accept_key); out_long (M->action.exchange_id); out_cstring ((void *)M->action.g_a, 256); out_long (M->action.key_fingerprint); break; case tgl_message_action_commit_key: out_int (CODE_decrypted_message_action_commit_key); out_long (M->action.exchange_id); out_long (M->action.key_fingerprint); break; case tgl_message_action_abort_key: out_int (CODE_decrypted_message_action_abort_key); out_long (M->action.exchange_id); break; case tgl_message_action_noop: out_int (CODE_decrypted_message_action_noop); break; default: assert (0); } encr_finish (&P->encr_chat); tglq_send_query (TLS, TLS->DC_working, packet_ptr - packet_buffer, packet_buffer, &msg_send_encr_methods, M, callback, callback_extra); }
void bl_do_edit_message_encr (struct tgl_state *TLS, tgl_message_id_t *id, tgl_peer_id_t *from_id, tgl_peer_id_t *to_id, int *date, const char *message, int message_len, struct tl_ds_decrypted_message_media *media, struct tl_ds_decrypted_message_action *action, struct tl_ds_encrypted_file *file, int flags) /* {{{ */ { clear_packet (); assert (!(flags & 0xfffe0000)); struct tgl_message *M = tgl_message_get (TLS, id); if (flags & (1 << 16)) { if (!M) { M = tglm_message_alloc (TLS, id); } else { assert (!(M->flags & TGLMF_CREATED)); } assert (!(M->flags & TGLMF_CREATED)); } else { assert (M->flags & TGLMF_CREATED); } assert (flags & TGLMF_CREATED); assert (flags & TGLMF_ENCRYPTED); if ((M->flags & TGLMF_PENDING) && !(flags & TGLMF_PENDING)){ tglm_message_remove_unsent (TLS, M); } if (!(M->flags & TGLMF_PENDING) && (flags & TGLMF_PENDING)){ tglm_message_insert_unsent (TLS, M); } M->flags = flags & 0xffff; if (from_id) { M->from_id = *from_id; } if (to_id) { assert (flags & 0x10000); M->to_id = *to_id; } if (date) { M->date = *date; } struct tgl_secret_chat *E = (void *)tgl_peer_get (TLS, M->to_id); assert (E); if (action) { tglf_fetch_message_action_encrypted (TLS, &M->action, action); M->flags |= TGLMF_SERVICE; } if (message) { M->message_len = message_len; M->message = tstrndup (message, message_len); assert (!(M->flags & TGLMF_SERVICE)); } if (media) { tglf_fetch_message_media_encrypted (TLS, &M->media, media); assert (!(M->flags & TGLMF_SERVICE)); } if (file) { tglf_fetch_encrypted_message_file (TLS, &M->media, file); assert (!(M->flags & TGLMF_SERVICE)); } if (action && !(M->flags & TGLMF_OUT) && M->action.type == tgl_message_action_notify_layer) { E->layer = M->action.layer; } if ((flags & TGLMF_CREATE) && (flags & TGLMF_OUT)) { E->out_seq_no ++; } if (flags & 0x10000) { tglm_message_insert (TLS, M); } }
void process_current_packet (void) { #ifdef DEBUG_708_PACKETS printf ("Processing EIA-708 packet, length=%d\n",current_packet_length); #endif if (current_packet_length==0) return; int seq=(current_packet[0] & 0xC0) >> 6; // Two most significants bits int len=current_packet[0] & 0x3F; // 6 least significants bits if (len==0) // This is well defined in EIA-708; no magic. len=128; else len=len*2; // Note that len here is the length including the header #ifdef DEBUG_708_PACKETS printf ("Sequence: %d, packet length: %d\n",seq,len); #endif if (current_packet_length!=len) // Is this possible? { printf ("Packet length mismatch (%s%d), first two data bytes %02X %02X, current picture:%s\n", current_packet_length-len>0?"+":"", current_packet_length-len, current_packet[0], current_packet[1], pict_types[current_picture_coding_type]); cc708_reset(); return; } if (last_seq!=-1 && (last_seq+1)%4!=seq) { printf ("Unexpected sequence number, it was [%d] but should have been [%d]\n", seq,(last_seq+1)%4); cc708_reset(); return; } last_seq=seq; unsigned char *pos=current_packet+1; while (pos<current_packet+len) { int service_number=(pos[0] & 0xE0)>>5; // 3 more significant bits int block_length = (pos[0] & 0x1F); // 5 less significant bits #ifdef DEBUG_708_PACKETS printf ("Standard header: Service number: [%d] Block length: [%d]\n",service_number, block_length); #endif if (service_number==7) // There is an extended header { pos++; service_number=(pos[0] & 0x3F); // 6 more significant bits // printf ("Extended header: Service number: [%d]\n",service_number); if (service_number<7) { printf ("Illegal service number in extended header: [%d]\n",service_number); } } /* if (service_number==0 && block_length==0) // Null header already? { if (pos!=(current_packet+len-1)) // i.e. last byte in packet { // Not sure if this is correct printf ("Null header before it was expected.\n"); // break; } } */ pos++; // Move to service data if (service_number==1) // Primary language process_service_block (&decoders[0], pos, block_length); if (service_number==2) // Secondary language process_service_block (&decoders[1], pos, block_length); pos+=block_length; // Skip data } clear_packet(); if (pos!=current_packet+len) // For some reason we didn't parse the whole packet { printf ("There was a problem with this packet, reseting\n"); cc708_reset(); } if (len<128 && *pos) // Null header is mandatory if there is room { printf ("Warning: Null header expected but not found.\n"); } }
void process_current_packet (cc708_service_decoder *decoders) { int seq = (decoders[0].parent->m_current_packet[0] & 0xC0) >> 6; // Two most significants bits int len = decoders[0].parent->m_current_packet[0] & 0x3F; // 6 least significants bits if (decoders[0].parent->m_current_packet_length == 0) return; if (len==0) // This is well defined in EIA-708; no magic. len=128; else len=len*2; // Note that len here is the length including the header if (decoders[0].parent->m_current_packet_length != len) // Is this possible? { cc708_reset(decoders); return; } int last_seq = decoders[0].parent->m_last_seq; if ((last_seq != -1) && ((last_seq+1)%4 != seq)) { cc708_reset(decoders); return; } decoders[0].parent->m_last_seq = seq; unsigned char *pos = decoders[0].parent->m_current_packet + 1; while (pos < decoders[0].parent->m_current_packet + len) { int service_number=(pos[0] & 0xE0)>>5; // 3 more significant bits int block_length = (pos[0] & 0x1F); // 5 less significant bits if (service_number==7) // There is an extended header { pos++; service_number=(pos[0] & 0x3F); // 6 more significant bits if (service_number<7) { } pos = decoders[0].parent->m_current_packet + len; break; } pos++; // Move to service data if (service_number==0 && block_length!=0) // Illegal, but specs say what to do... { pos = decoders[0].parent->m_current_packet + len; // Move to end break; } if (service_number>0 && decoders[service_number].inited) process_service_block (&decoders[service_number], pos, block_length); pos+=block_length; // Skip data } clear_packet(&decoders[0]); if (pos != decoders[0].parent->m_current_packet + len) // For some reason we didn't parse the whole packet { cc708_reset(decoders); } if (len<128 && *pos) // Null header is mandatory if there is room { ;//ccx_common_logging.debug_ftn(CCX_DMT_708, "Warning: Null header expected but not found.\n"); } }
int main(int argc, char *argv[]) { key_t shmkey; int shmid, shmsize; int i, j, k, t = 0, c = 0; int pause = PAUSE, again = 1; int setupIndex = -1; int minSampleIndex = -1, minMessageIndex = -1; int maxSampleIndex = -1, maxMessageIndex = -1; int minSampleValue = INT_MAX, minMessageValue = INT_MAX; int maxSampleValue = INT_MIN, maxMessageValue = INT_MIN; int maxCountCleared = 0, countCleared = 0, countLoop = 0; int countInvalid = 0, countData = 0, countSetup = 0, countCancel = 0, countUnknown = 0; for (i=0; i<MAXNUMTRIGCHAN; i++) lastValue[i] = 0; /* make the shared memory key * if ((shmkey = ftok(ACQ_MSGQ_SHMPATH, ACQ_MSGQ_SHMPROJID)) == -1) { * perror("ftok"); * exit(1); * } */ /* use the pre-defined shared memory key */ shmkey = ACQ_MSGQ_SHMKEY; /* determine the size of the shared memory buffer */ shmsize = sizeof(ACQ_MessagePacketType) * ACQ_MSGQ_SIZE; /* connect to (and possibly create) the segment */ if ((shmid = shmget(shmkey, shmsize, PERMISSION | IPC_CREAT )) == -1) { perror("shmget"); exit(1); } /* attach to the segment to get a pointer to it */ packet = shmat(shmid, (void *)0, 0); if ((char *)packet == (char *)(-1)) { perror("shmat"); exit(1); } display_start(); display_print("initializing\n"); // clear_all_except_setup(); // clear_all(); display_refresh(); while (again) { clear(); setupIndex = -1; minSampleIndex = -1, minMessageIndex = -1; maxSampleIndex = -1, maxMessageIndex = -1; minSampleValue = INT_MAX, minMessageValue = INT_MAX; maxSampleValue = INT_MIN, maxMessageValue = INT_MIN; countInvalid = 0, countData = 0, countSetup = 0, countCancel = 0, countUnknown = 0; /******************************************************************************* * collect information about all packets in the buffer *******************************************************************************/ for (i=0; i<ACQ_MSGQ_SIZE; i++) { if (i<SHOWPACKET) print_packet(i); switch (packet[i].message_type) { case ACQ_MSGQ_SETUP_COLLECTION: if (countSetup>0) { /* multiple packets with a setup are not allowed, only keep the first */ display_print("clearing superfluous setup packet at %d (setup @ %d)\n", i, setupIndex); clear_packet(i); countCleared++; break; } countSetup++; setupIndex = i; /* update the specifications that relate to trigger maintenance */ numRealChan = packet[i].data[DATASIZE-TRIGSIZE*3-MAXNUMTRIGCHAN-2]; /* update the value */ numTrigChan = packet[i].data[DATASIZE-TRIGSIZE*3-MAXNUMTRIGCHAN-1]; /* update the value */ trigChan = packet[i].data+DATASIZE-TRIGSIZE*3-MAXNUMTRIGCHAN; /* update the pointer */ trigPointer = packet[i].data+DATASIZE-TRIGSIZE*3; /* update the pointer */ if (numRealChan<0) numRealChan = 0; if (numTrigChan<0) numTrigChan = 0; if (numTrigChan>MAXNUMTRIGCHAN) { display_print("cannot maintain more than %d trigger channels in real time\n", MAXNUMTRIGCHAN); numTrigChan = MAXNUMTRIGCHAN; } break; case ACQ_MSGQ_DATA: countData++; if (packet[i].sampleNumber<minSampleValue) { minSampleIndex = i; minSampleValue = packet[i].sampleNumber; } if (packet[i].sampleNumber>maxSampleValue) { maxSampleIndex = i; maxSampleValue = packet[i].sampleNumber; } if (packet[i].messageId<minMessageValue) { minMessageIndex = i; minMessageValue = packet[i].messageId; } if (packet[i].messageId>maxMessageValue) { maxMessageIndex = i; maxMessageValue = packet[i].messageId; } if ((packet[i].sampleNumber/ packet[i].numSamples)>lastPacket) { /* detect the flanks in the trigger channels */ lastPacket = packet[i].sampleNumber/ packet[i].numSamples; for (j=0; j<numTrigChan; j++) { if (trigChan[j]>-1 && trigChan[j]<numRealChan) for (k=0; k<packet[i].numSamples; k++) { int sample = k*numRealChan + trigChan[j]; /* detect changes in the value of the trigger channel */ if (packet[i].data[sample]!=lastValue[j]) { lastValue[j] = packet[i].data[sample]; if (lastValue[j]) { display_print("trigger detected\n"); /* only store it if it is an upgoing flank */ trigPointer[numTrigger+0] = trigChan[j]; /* channel number */ trigPointer[numTrigger+1] = packet[i].sampleNumber+k; /* sample number */ trigPointer[numTrigger+2] = lastValue[j]; /* sample value */ numTrigger = wrapnumtrigger(numTrigger+3); } } } } } break; case ACQ_MSGQ_CLOSE_CONNECTION: countCancel++; break; case ACQ_MSGQ_INVALID: countInvalid++; break; default: countUnknown++; clear_packet(i); countCleared++; break; } /* end switch */ } /* end for */ /******************************************************************************* * print information about all packets in the buffer *******************************************************************************/ display_print("\n"); display_print("buffer size = %d\n", ACQ_MSGQ_SIZE); display_print("shm size = %d\n", shmsize); display_print("shm key = %#x\n", shmkey); display_print("pause = %d\n", pause); if (setupIndex>=0) display_print("dataset = %s @ %d\n", (char *)packet[setupIndex].data, setupIndex); else display_print("dataset = <unknown>\n"); display_print("\n"); display_print("countSetup = %d\n", countSetup); display_print("countData = %d\n", countData); display_print("countCancel = %d\n", countCancel); display_print("countInvalid = %d\n", countInvalid); display_print("countUnknown = %d\n", countUnknown); display_print("countCleared = %d\n", countCleared); display_print("\n"); /* this might look like a weird location to reinitialize */ maxCountCleared = (countCleared>maxCountCleared ? countCleared : maxCountCleared); countCleared = 0; display_print("min(sampleNumber) = %d @ %d\n", minSampleValue, minSampleIndex); display_print("max(sampleNumber) = %d @ %d\n", maxSampleValue, maxSampleIndex); // display_print("min(messageId) = %d @ %d\n", minMessageValue, minMessageIndex); // display_print("max(messageId) = %d @ %d\n", maxMessageValue, maxMessageIndex); display_print("max(countCleared) = %d\n", maxCountCleared); display_print("\n"); if (maxSampleIndex>=0) display_print("current trial = %d @ %d\n", maxSampleValue/packet[maxSampleIndex].numSamples, maxSampleIndex); else display_print("current trial = <unknown>\n"); display_print("\n"); display_print("numRealChan = %d\n", numRealChan); display_print("numTrigChan = %d\n", numTrigChan); display_print("numTrigger = %d\n", numTrigger/3); display_print("lastPacket = %d\n", lastPacket); display_print("trigChan = "); for (i=0; i<numTrigChan; i++) display_print("%d\t", trigChan[i]); display_print("\n"); display_print("lastValue = "); for (i=0; i<numTrigChan; i++) display_print("%d\t", lastValue[i]); display_print("\n"); display_print("\n"); display_refresh(); /******************************************************************************* * do the desired maintenance on the packet buffer (only if a key was pressed) *******************************************************************************/ k = getch(); switch (k) { case 's': write_setup(0); break; case 'p': pause = PAUSE; break; case 'f': while (countInvalid && packet[t].message_type!=ACQ_MSGQ_INVALID) t = wrapnumpacket(t+1); while (packet[t].message_type==ACQ_MSGQ_INVALID) { write_data(t, c); t = wrapnumpacket(t+1); c++; } break; case 'd': while (countInvalid && packet[t].message_type!=ACQ_MSGQ_INVALID) t = wrapnumpacket(t+1); write_data(t, c); t = wrapnumpacket(t+1); c++; break; case 'c': maxCountCleared = 0; clear_all_except_setup(); break; case 'h': showDisplay = (!showDisplay); break; case 'x': maxCountCleared = 0; clear_all(); break; case 'q': again = 0; break; } if (k!=ERR) { display_print("key pressed = %d\n", k); display_refresh(); continue; } /******************************************************************************* * do the regular maintenance on the packet buffer *******************************************************************************/ if (countCancel) { display_print("initializing all packets\n"); clear_all(); countInvalid = ACQ_MSGQ_SIZE; countData = 0; countSetup = 0; countCancel = 0; } // if ((MINFREE-countInvalid)>1 && pause) { // pause/=(MINFREE-countInvalid); // display_print("decreasing pause to %d\n", pause); // } while (countInvalid<MINFREE && countData) /* make more empty packets available */ if (setupIndex>-1) { /* moving the setup one packet at a time may look inefficient, but this only happens at the start of online acquisition */ display_print("moving setup from %d to %d\n", setupIndex, minSampleIndex); memcpy(&packet[minSampleIndex], &packet[setupIndex], sizeof(ACQ_MessagePacketType)); countCleared++; countInvalid++; countData--; // NOTE: don't clear the packet, since Matlab might be reading from it // display_print("clearing packet %d\n", setupIndex); // clear_packet(setupIndex); packet[setupIndex].message_type = ACQ_MSGQ_INVALID; setupIndex = minSampleIndex; minSampleIndex = wrapnumpacket(minSampleIndex+1); /* the next is probably now the oldest */ } else { display_print("clearing packet %d\n", minSampleIndex); clear_packet(minSampleIndex); countCleared++; countInvalid++; countData--; minSampleIndex = wrapnumpacket(minSampleIndex+1); /* the next is probably now the oldest */ } while (setupIndex>-1 && countData && packet[wrapnumpacket(setupIndex+1)].message_type==ACQ_MSGQ_INVALID) { /* move the setup to the next empty packet */ /* moving the setup one packet at a time may look inefficient, but this only happens at the start of online acquisition */ display_print("moving setup from %d to %d\n", setupIndex, wrapnumpacket(setupIndex+1)); memcpy(&packet[wrapnumpacket(setupIndex+1)], &packet[setupIndex], sizeof(ACQ_MessagePacketType)); // NOTE: don't clear the packet, since Matlab might be reading from it // clear_packet(setupIndex); packet[setupIndex].message_type = ACQ_MSGQ_INVALID; countCleared++; setupIndex = wrapnumpacket(setupIndex+1); } display_refresh(); usleep(pause); if (countInvalid>4) printf("ok %d\n", countLoop); else printf("error %d\n", countLoop); countLoop++; } /* detach from the shared memory segment */ if (shmdt(packet) == -1) { perror("shmdt"); exit(1); } /* end curses mode */ display_stop(); /* end of program */ return 0; }
/** * The main program * * Parameters: * - int argc => The number of arguments passed * - char** args => The arguments list * * Return: * - int => The result of the execution */ int main(int argc, char** args) { /* ################################################## Initialisations ################################################## */ // If there are too many arguments if (argc > 1) { perror("There are too many arguments. This program requires none"); return 1; } /* ##### Network structures ##### */ // Socket creation and bind int server_socket = init_socket(); // The variable to store datas received struct packet packet_received; struct packet packet_to_send; char buffer[BUFFER_SIZE]; // The structure to store the source informations struct sockaddr_in source; socklen_t source_length = (socklen_t)sizeof(struct sockaddr); // To know the current state of the server int server_state = S_FREE; /* ##### Audio reader parameters ##### */ // Some more variables that we'll need to read the audio file int sample_rate, sample_size, channels; int read_audio, read_init_audio = 0; /* ##### Timeout parameters ##### */ int nb; fd_set watch_over; struct timeval timeout; /* ################################################## Serve clients ################################################## */ while (1) { // Server always running // Clear and initialize the fd set FD_ZERO(&watch_over); FD_SET(server_socket, &watch_over); timeout.tv_sec = TIMEOUT_SERVER; // 5 sec timeout.tv_usec = 0; nb = select(server_socket+1, &watch_over, NULL, NULL, &timeout); // If error during the select if (nb < 0) { perror("Can't attach the select to the file descriptor"); return 1; } // Just consider the client is gone if timeout reached if (nb == 0) { server_state = S_FREE; } // If open, just act normally if (FD_ISSET(server_socket, &watch_over)) { // Clear packets clear_packet(&packet_to_send); clear_packet(&packet_received); // Wait a packet if (recvfrom(server_socket, &packet_received, sizeof(struct packet), 0, (struct sockaddr*)&source, &source_length) != -1) { // In function of the type of the packet received switch (packet_received.type) { // --------------- Receiving the filename --------------- case P_FILENAME: // If the server is busy, refuse the client asking for a file (it's the first packet sent) if (server_state == S_BUSY) server_error_encountered(server_socket, P_SERVER_ERROR, "Server busy for the moment. Please try later", (struct sockaddr*)&source, NULL); // If not busy, then put this client as the current else { // Put the server busy server_state = S_BUSY; // Initialize by getting informations about the music to play read_init_audio = aud_readinit(packet_received.message, &sample_rate, &sample_size, &channels); // If an error happened (maybe the file doesn't exist) if (read_init_audio == -1) server_error_encountered(server_socket, P_SERVER_ERROR, "Error at opening the audio file, the file requested may be inexistant", (struct sockaddr*)&source, &server_state); // If none else { // Store informations about this file snprintf(buffer, sizeof(buffer), "%d %d %d", sample_rate, sample_size, channels); // Create the packet to send create_packet(&packet_to_send, P_FILE_HEADER, buffer); // Send it if (sendto(server_socket, &packet_to_send, sizeof(struct packet), 0, (struct sockaddr*)&source, source_length) == -1) server_error_encountered(server_socket, P_ERR_TRANSMISSION, "Error at sending the file header", (struct sockaddr*)&source, &server_state); } } break; // --------------- Client requesting another block --------------- case P_REQ_NEXT_BLOCK: // Fill the buffer read_audio = read(read_init_audio, buffer, BUFFER_SIZE); // If the end of file is reached int type = P_BLOCK; if (read_audio != BUFFER_SIZE) type = P_EOF; // Create the packet to send create_packet(&packet_to_send, type, buffer); // And send it if (sendto(server_socket, &packet_to_send, sizeof(struct packet), 0, (struct sockaddr*)&source, source_length) == -1) server_error_encountered(server_socket, P_ERR_TRANSMISSION, "Error at sending the next block", (struct sockaddr*)&source, &server_state); break; // --------------- Client requesting the same packet (if it doesn't received it) --------------- case P_REQ_SAME_PACKET: // Resend packet previously created if (sendto(server_socket, &packet_to_send, sizeof(struct packet), 0, (struct sockaddr*)&source, source_length) == -1) server_error_encountered(server_socket, P_ERR_TRANSMISSION, "Error at sending the same block", (struct sockaddr*)&source, &server_state); break; // --------------- Client received correctly the close transmission --------------- case P_CLOSED: // Close the descriptor file when it's done if ((read_init_audio > 0) && (close(read_init_audio) != 0)) perror("Error at closing the read file descriptor"); // Free the server server_state = S_FREE; break; } } // If an error during the receiving of a packet else server_error_encountered(server_socket, P_ERR_TRANSMISSION, "Error during the receiving of a packet", (struct sockaddr*)&source, &server_state); } } // Then close the socket if (close(server_socket) == -1) { perror("Error during the closing of the server socket"); return 1; } // If everything's was ok return 0; }
int main(int argc, char *argv[]) { struct sockaddr_in si_me, si_other; int sk; socklen_t slen = sizeof(si_other); int len, ret; fd_set readsock; struct packet p; char buf[PAYLOAD_SIZE]; char log_file[LINE_LENGTH]; char serial_file[LINE_LENGTH]; unsigned int crc32_value; struct hostent *hostentry; unsigned int i; int mask; memset(log_file, 0, LINE_LENGTH); memset(serial_file, 0, LINE_LENGTH); memset(buf, 0, PAYLOAD_SIZE); if (argv[1] != NULL) { if(!strcmp(argv[1], "debug")) mask = (LOG_MASK(LOG_ERR) | LOG_MASK(LOG_DEBUG)); else mask = LOG_MASK(LOG_ERR); } else mask = LOG_MASK(LOG_ERR); /* Our process ID and Session ID */ pid_t pid, sid; /* Fork off the parent process */ pid = fork(); if (pid < 0) { exit(1); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { save_pid(PID_FILE, pid); exit(0); } /* Change the file mode mask */ umask(0); /* Open any logs here */ /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { /* Log the failure */ exit(1); } /* Change the current working directory */ if ((chdir("/")) < 0) { /* Log the failure */ exit(1); } /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); /* Daemon-specific initialization goes here */ openlog("USBlogger server", LOG_PID | LOG_CONS | LOG_NDELAY | LOG_NOWAIT, LOG_LOCAL0); setlogmask(mask); ret = parse_config(CONFIG_FILE, log_file, serial_file, CONFIG_NUM_PARAMS); if (ret) { syslog(LOG_ERR, "Something wrong happened while reading configuration. Please check config file - %s", CONFIG_FILE); exit(1); } /* Initialize the socket to recv messages */ sk = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sk == -1) { syslog(LOG_ERR, "socket creation failed"); exit(1); } memset(&si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); ret = bind(sk, (struct sockaddr *)&si_me, sizeof(si_me)); if (ret == -1) { syslog(LOG_ERR, "bind failed"); exit(1); } /* The Big Loop */ while (1) { FD_ZERO(&readsock); FD_SET(sk, &readsock); ret = select(FD_SETSIZE, &readsock, NULL, NULL, NULL); if (ret == -1) { syslog(LOG_ERR, "error in select() at main loop"); exit(1); } else if (ret > 0) { if (FD_ISSET(sk, &readsock)) { len = recvfrom(sk, buf, PAYLOAD_SIZE, 0, (struct sockaddr *)&si_other, &slen); if (len == -1) { syslog(LOG_ERR, "recvfrom returned an error"); continue; } syslog(LOG_DEBUG, "len = %d, Received the message from client ... ", len); // for(i = 0; i < len; i++) // putchar(buf[i]); // putchar('\n'); ret = parse_packet(&p, buf, len); if(ret) { syslog(LOG_ERR, "parser found an error during parsing a packet"); //clear_packet(&p); memset(buf, 0, PAYLOAD_SIZE); continue; } print_packet(&p); ret = is_serial_allowed(serial_file, p.fields[2].value_val); if (ret != 0) { //serial is not in the list, so saving log save_packet(log_file, &p); } // serial in the list, nothing to do crc32_value = crc32(buf, len); syslog(LOG_DEBUG, "CRC32 value of the message is = %x", crc32_value); hostentry = gethostbyname(p.fields[1].value_val); if(hostentry == NULL) { syslog(LOG_ERR, "Resolving hostname failed"); clear_packet(&p); memset(buf, 0, PAYLOAD_SIZE); continue; } syslog(LOG_DEBUG, "Client IP: %s", inet_ntoa(*((struct in_addr *)hostentry->h_addr_list[0])) ); clear_packet(&p); memset(buf, 0, PAYLOAD_SIZE); ret = send_buffer_to_client(sk, (struct in_addr *)hostentry->h_addr_list[0], (char *)&crc32_value, sizeof(crc32_value)); /* // Any device plugged into server if (bus_msg->msgtype == '1') { tableret = add_to_table(bus_msg); if (tableret != 0) { printf("No hub any more.\n"); return -1; } print_table(); printf("Received a bus (%s) from %s\n", bus_msg->busname, inet_ntoa(si_other.sin_addr)); sprintf(cmd, "usbip_attach "); strcat(cmd, inet_ntoa(si_other.sin_addr)); strcat(cmd, " "); strcat(cmd, bus_msg->busname); system(cmd); } // Any device unplugged from server if (bus_msg->msgtype == '0') { char str[2]; tableret = del_from_table(bus_msg); if (tableret == -1) { printf("Device not found.\n"); return -1; } print_table(); printf("Received a bus (%s) from %s\n", bus_msg->busname, inet_ntoa(si_other.sin_addr)); sprintf(cmd, "usbip_detach "); sprintf(str, "%d", tableret); strcat(cmd, str); system(cmd); } */ } } } close(sk); return 0; }