void server_look(int conn_fd, char * local_path) { char server_path[SIZE]; char filename[SIZE]; char file_path[SIZE]; char len[SIZE]; char tmp[SIZE] = {"\n\n\t\t.\n\n\t\t.."}; struct dirent * ptr; struct stat buf; DIR * dir; int fd; char name[SIZE][SIZE]; int i = 0; int num; char log[SIZE]; char log_path[SIZE]; strcpy(log_path, local_path); memset(log, '\0', sizeof(log)); strcpy(log, "浏览服务器目录:"); strcat(log, log_path); sys_log(log); stat (local_path, &buf); if (S_ISREG(buf.st_mode)) { ; } chdir(local_path); getcwd(file_path, sizeof(file_path)); file_path[strlen(file_path)] = '/'; file_path[strlen(file_path) + 1] = '\0'; dir = opendir(file_path); while ((ptr = readdir(dir)) != NULL) { if (strcmp(ptr->d_name, ".") && strcmp(ptr->d_name, "..")) { strcat(tmp, "\n\n\t\t"); strcat(tmp, ptr->d_name); strcpy(name[i++], ptr->d_name); } } strcat(tmp, "\n请选择要保存的位置\n..返回上层目录\n"); send(conn_fd, tmp, SIZE, 0); recv(conn_fd, filename, SIZE, 0); if (strcmp(filename, "1") == 0) { recv(conn_fd, filename, SIZE, 0); mkdir(filename, 0777); chdir(filename); sys_log("进入新建文件夹目录"); server_look(conn_fd, filename); } else if (strcmp (filename, "2") == 0) { loop: num = i - 1; recv(conn_fd, filename, SIZE, 0); for (; num >= 0; num--) { if (strcmp(filename, name[num]) == 0) { send_data(conn_fd, "n\n"); goto loop; } } send_data(conn_fd, "y\n"); recv(conn_fd, len, SIZE, 0); server_recv(conn_fd, filename, len); } else if (strncmp(filename, "..", 2) == 0) { server_look(conn_fd, ".."); } else { server_look(conn_fd, filename); } }
int vec2elemental(const std::vector<double> &vec, El::DistMatrix<El::Complex<double>,El::VC,El::STAR> &Y){ int data_dof=2; int SCAL_EXP = 1; int nlocal,gsize; //local elements, start p_id, global size double *pt_array; // will hold local array int r,q,rq; //Grid sizes int nbigs; //Number of large sends (i.e. send 1 extra data point) int pstart; // p_id of nstart int rank = El::mpi::WorldRank(); //p_id int send_size; // base send size bool print = rank == -1; // Get Grid and associated params const El::Grid* g = &(Y.Grid()); r = g->Height(); q = g->Width(); MPI_Comm comm = (g->Comm()).comm; // Get sizes, array in petsc nlocal = vec.size()/data_dof; int nstart = 0; MPI_Exscan(&nlocal,&nstart,1,MPI_INT,MPI_SUM,comm); //VecGetOwnershipRange(pt_vec,&nstart,NULL); //Find processor that nstart belongs to, number of larger sends rq = r * q; pstart = nstart % rq; //int div nbigs = nlocal % rq; send_size = nlocal/rq; if(print){ std::cout << "r: " << r << " q: " << q <<std::endl; std::cout << "nstart: " << nstart << std::endl; std::cout << "ps: " << pstart << std::endl; std::cout << "nbigs: " << nbigs << std::endl; std::cout << "send_size: " << send_size << std::endl; } // Make send_lengths std::vector<int> send_lengths(rq); std::fill(send_lengths.begin(),send_lengths.end(),send_size); if(nbigs >0){ for(int j=0;j<nbigs;j++){ send_lengths[(pstart + j) % rq] += 1; } } // Make send_disps std::vector<int> send_disps = exscan(send_lengths); std::vector<El::Complex<double>> indata(nlocal); // copy the data from an ffm tree to into a local vec of complex data for sending #pragma omp parallel for El::Complex<double> val; for(int i=0;i<nlocal;i++){ El::SetRealPart(val,vec[2*i+0]); El::SetImagPart(val,vec[2*i+1]); indata[i] = val; } // Make send_dataA, i.e. reorder the data std::vector<El::Complex<double>> send_data(nlocal); for(int proc=0;proc<rq;proc++){ int offset = send_disps[proc]; int base_idx = (proc - pstart + rq) % rq; for(int j=0; j<send_lengths[proc]; j++){ int idx = base_idx + (j * rq); send_data[offset + j] = indata[idx]; } } // Do all2all to get recv_lengths std::vector<int> recv_lengths(rq); MPI_Alltoall(&send_lengths[0], 1, MPI_INT, &recv_lengths[0], 1, MPI_INT,comm); // Scan to get recv_disps std::vector<int> recv_disps = exscan(recv_lengths); // Do all2allv to get data on correct processor El::Complex<double> * recv_data = Y.Buffer(); //MPI_Alltoallv(&send_data[0],&send_lengths[0],&send_disps[0],MPI_DOUBLE, \ // &recv_data[0],&recv_lengths[0],&recv_disps[0],MPI_DOUBLE,comm); El::mpi::AllToAll(&send_data[0], &send_lengths[0], &send_disps[0], recv_data,&recv_lengths[0],&recv_disps[0],comm); if(print){ std::cout << "Send data: " <<std::endl << send_data <<std::endl; std::cout << "Send lengths: " <<std::endl << send_lengths <<std::endl; std::cout << "Send disps: " <<std::endl << send_disps <<std::endl; std::cout << "Recv data: " <<std::endl << recv_data <<std::endl; std::cout << "Recv lengths: " <<std::endl << recv_lengths <<std::endl; std::cout << "Recv disps: " <<std::endl << recv_disps <<std::endl; } return 0; }
// Process RMSREQ command // This command returns averaged RMS values for a given channel void process_rmsreq( const char *rq_station, // station name const char *rq_chan, // Channel ID const char *rq_loc, // Location ID STDTIME2 rq_tBeginTime, // Start time long rq_iSamples // Number of data points to transfer ) { char loglocation[4] ; char logchannel[4] ; char str_record[8192]; char log_msg[8192]; char msgbuf[512]; char loopDir[MAXCONFIGLINELEN+1]; char buf_filename[2*MAXCONFIGLINELEN+2]; static char looperrstr[MAXCONFIGLINELEN+2]; char *errmsg; char *msgptr; int prslen ; int badval ; int iLoopRecordSize; int indexFirst; int indexLast; int iStart; int iCount; int iLoopSize; int iSample; int iTry; int iEmpty; int iRecord; int iSeek; STDTIME2 rq_tEndTime; STDTIME2 startTime; FILE *fp_buf; seed_header *pheader; // Parse and validate log [location-]channel strcpy(loglocation, " ") ; ++cmdcnt ; parse_request(' ') ; prslen = strlen(prsbuf) ; badval = 0 ; switch (prslen) { case 3 : memcpy(logchannel, prsbuf, 4); break ; case 5 : if (prsbuf[1] == '-') { memcpy(loglocation, prsbuf, 1) ; loglocation[1] = 0; memcpy(logchannel, &prsbuf[2], 4) ; } else badval = 1 ; break ; case 6 : if (prsbuf[2] == '-') { memcpy(loglocation, prsbuf, 2) ; loglocation[2] = 0; memcpy(logchannel, &prsbuf[3], 4) ; } else badval = 1 ; break ; default : badval = 1 ; } if (badval == 1) { send_data ("Invalid log [location-]channel name\n"); return ; } fprintf(stderr, "DEBUG process RMSREQ %s.%s-%s in %s-%s %d,%d,%02d:%02d:%02d %ld %s-%s\n", rq_station,rq_loc,rq_chan, loglocation, logchannel, rq_tBeginTime.year, rq_tBeginTime.day, rq_tBeginTime.hour, rq_tBeginTime.minute, rq_tBeginTime.second, rq_iSamples, loglocation, logchannel); // Get index of first record for this data request startTime = ST_AddToTime2(rq_tBeginTime, 0, -1, 0, 0, 0); rq_tEndTime = rq_tBeginTime; rq_tEndTime.year = 3000; // give max year as end time LoopRecordSize(&iLoopRecordSize); errmsg = GetRecordRange(rq_station, logchannel, loglocation, startTime, rq_tEndTime, &indexFirst, &indexLast, &iCount, &iLoopSize); if (errmsg != NULL) { sprintf(msgbuf, "%s\n", errmsg); send_data(msgbuf); return; } fprintf(stderr, "indexFirst=%d, indexLast=%d, iCount=%d, iLoopSize=%d\n", indexFirst, indexLast, iCount, iLoopSize); // Make sure there are data records to return if (iCount < 1) { send_data("No log records found for given day\n"); return; } // Get name of buffer file // If blank location code, leave off leading location code in filename LoopDirectory(loopDir); if (loglocation[0] == ' ' || loglocation[0] == 0) { sprintf(buf_filename, "%s/%s/%s.buf", loopDir, rq_station, logchannel); } else { sprintf(buf_filename, "%s/%s/%s_%s.buf", loopDir, rq_station, loglocation, logchannel); } // Open the buffer file if ((fp_buf=fopen(buf_filename, "r")) == NULL) { // Buffer file does not exist so no records to return sprintf(msgbuf, "Unable to open log file %s\n", buf_filename); send_data(msgbuf); return; } // Loop until we've averaged rq_iSamples data points // Or the record time is before the requested start time iSample = 0; iTry = 0; while (iSample < rq_iSamples && ((iTry + indexFirst + iEmpty + iLoopSize - 1) % iLoopSize) != indexLast) { iRecord = (iTry + indexFirst + iEmpty) % iLoopSize; iSeek = iRecord * iLoopRecordSize; // Seek to the record position fseek(fp_buf, iSeek, SEEK_SET); if (iSeek != ftell(fp_buf)) { // If seek failed, we hit end of file fprintf(stderr, "process_rms: Unable to seek to %d in %s", iSeek, buf_filename); fclose(fp_buf); sprintf(msgbuf, "Only found %d of requested %ld rms samples\n", iSample, rq_iSamples); send_data(msgbuf); return; } // Failed to seek to required file buffer position // Read in the data if (fread(str_record, iLoopRecordSize, 1, fp_buf) != 1) { sprintf(looperrstr, "Unable to read record %d in %s\n", iRecord, buf_filename); fclose(fp_buf); send_data(looperrstr); return; } // Failed to read record // Convert the log record into a message string pheader = (seed_header *)str_record; iStart = min(ntohs(pheader->first_data_byte), 128); iCount = min(ntohs(pheader->samples_in_record), iLoopRecordSize-iStart-1); strncpy(log_msg, &str_record[iStart], iCount); log_msg[iCount] = 0; // Search the log record for rms lines matching requested channel msgptr = log_msg; while(*msgptr != 0 && iSample < rq_iSamples) { // Look for {125} messages if (strncmp(msgptr, "{125}", 5) == 0) { // Look for Matching channel and location code if (strncmp(&msgptr[27], rq_loc, 2) == 0 && strncmp(&msgptr[30], rq_chan, 3) == 0) { // The time must be after the start time int year=0; int month=0; int dom=0; int hour=0; int minute=0; int second=0; int iCmp; STDTIME2 rms_time={0}; LONG julian; if (sscanf(&msgptr[6], "%d-%d-%d %d:%d:%d", &year, &month, &dom, &hour,&minute, &second) == 6) { julian = ST_Julian2(year, month, dom); rms_time = ST_CnvJulToSTD2(julian); rms_time = ST_AddToTime2(rms_time, 0, hour, minute, second, 0); } iCmp = ST_TimeComp2(rms_time, rq_tBeginTime); if (iCmp >= 0) { double rms[3]; if (sscanf(&msgptr[34], "%lf %lf %lf", &rms[0], &rms[1], &rms[2] ) == 3) { sprintf(msgbuf, "%.3lf\n", rms[1]); send_data(msgbuf); iSample++; if (gDebug) { fprintf(stderr, "Sample %d: %70.70s\n", iSample, msgptr); } } // no errors scanning line } // Time is after desired start time } // RMS line matches desired channel and location } // string started with {125} // Time to find start of next line while (*msgptr != 0 && *msgptr != '\n') msgptr++; if (*msgptr == '\n') msgptr++; } // while we need to check more lines for desired RMS values iTry++; } // while more samples need to found // Close buffer file fclose(fp_buf); if (iSample < rq_iSamples) { sprintf(msgbuf, "Error, only found %d/%ld samples.\n", iSample, rq_iSamples); send_data(msgbuf); } return; } // process_rmsreq()
void symbolic_attacker(int attacker_id, struct keypair* keypair) /*@ requires [?f]world(?pub, ?key_clsfy) &*& true == bad(attacker_id) &*& principal(attacker_id, ?count) &*& keypair(keypair, attacker_id, ?id, ?info, pub); @*/ //@ ensures false; { //@ retreive_proof_obligations(); for (;;) /*@ invariant [f]world(pub, key_clsfy) &*& proof_obligations(pub) &*& principal(attacker_id, _) &*& keypair(keypair, attacker_id, id, info, pub); @*/ { struct network_status *net_stat = 0; int net_choise = random_int_(); int port = random_int_(); if (net_choise % 2 == 0) net_stat = network_bind_and_accept(port % 65536); else net_stat = network_connect("localhost", port % 65536); { int action = random_int_(); int *counter; switch (action % 13) { case 0: //@ open [f]world(pub, key_clsfy); //@ assert [_]is_key_classifier(_, pub, key_clsfy); //@ retreive_public_invariant_constraints(key_clsfy); //@ duplicate_lemma_function_pointer_chunk(key_classifier); /*@ { lemma void public_key_classifier(cryptogram key, int p, int c, bool symmetric) requires polarssl_proof_pred(pub, key_clsfy)() &*& [_]polarssl_pub(pub)(key) &*& symmetric ? key == cg_symmetric_key(p, c) : key == cg_private_key(p, c); ensures polarssl_proof_pred(pub, key_clsfy)() &*& col || true == key_clsfy(p, c, symmetric); { open [_]polarssl_pub(pub)(key); item k; if (symmetric) k = symmetric_key_item(p, c); else k = private_key_item(p, c); open polarssl_proof_pred(pub, key_clsfy)(); assert is_key_classifier(?proof, pub, key_clsfy); proof(k, p, c, symmetric); close polarssl_proof_pred(pub, key_clsfy)(); } produce_lemma_function_pointer_chunk(public_key_classifier) : public_key_classifier(polarssl_pub(pub), key_clsfy, polarssl_proof_pred(pub, key_clsfy)) (key__, p__, c__, sym__) { call(); } {duplicate_lemma_function_pointer_chunk(public_key_classifier);}; } @*/ //@ close polarssl_proof_pred(pub, key_clsfy)(); attacker(); //@ open polarssl_proof_pred(pub, key_clsfy)(); //@ close [f]world(pub, key_clsfy); //@ leak public_invariant_constraints(_, _); //@ leak is_public_key_classifier(_, _, _, _); //@ leak is_key_classifier(_, _, _); break; case 1: // Anyone can publish arbitrary data items... send_data(net_stat); break; case 2: // Anyone can create pairs of public items... send_pair_composed(net_stat); break; case 3: // Anyone can deconstruct a public pair... send_pair_decomposed(net_stat); break; case 4: // Bad principals can publish generated nonce items... send_nonce(net_stat); break; case 5: // Bad principals can increment public nonces... increment_and_send_nonce(net_stat); break; case 6: // Bad principals can leak their keys... send_keys(net_stat, keypair); break; case 7: // Anyone can hmac public payload with public key send_hmac(net_stat, keypair); break; case 8: // Anyone can symmteric encrypt public payload with public key send_symmetric_encrypted(net_stat, keypair); break; case 9: // Anyone can symmteric decrypt message with public key send_symmetric_decrypted(net_stat, keypair); break; case 10: // Anyone can asymmteric encrypt public payload with public key send_asymmetric_encrypted(net_stat, keypair); break; case 11: // Anyone can asymmteric decrypt message with public key send_asymmetric_decrypted(net_stat, keypair); break; case 12: // Anyone can asymmteric sign public payload with public key send_asymmetric_signature(net_stat, keypair); } } network_disconnect(net_stat); } //@ leak proof_obligations(pub); }
void* typing_func(void) { char message_buffer[LENGHT_MESSAGE]; char message_buffer_2[LENGHT_MESSAGE]; char confirm_file[LENGHT_MESSAGE]; char filename[LENGHT_MESSAGE]; char ch; int buffer_int; FILE *fp; while (state == 0) { //Reset string for get new message strcpy(message_buffer, ""); strcpy(message_buffer_2, ""); wscanw(global_typing, " %[^\n]s", message_buffer); while (strlen(message_buffer) > 200) { werase(global_typing); draw_new(global_display, "system>> Message cannot more than 200 characters."); wscanw(global_typing, " %[^\n]s", message_buffer); } //Draw_new line to display message strcpy(message_buffer_2, "you>> "); strcat(message_buffer_2, message_buffer); draw_new(global_display, message_buffer_2); //Check exit command if (strcmp(message_buffer, ":q!") == 0) { //set state to stop all function state = 1; } else if (message_buffer[0] == '/') { if (split_strcmp(0, 6, "/upload", 0, 6, message_buffer)){ split_str(8, strlen(message_buffer), message_buffer, filename); sprintf(message_buffer, "3system>> Sending file to you: %s", filename); send_data(message_buffer); sleep(1); draw_new(global_display, "system>> Uploading..."); fp = fopen(filename, "r"); while( ( ch = fgetc(fp) ) != EOF ){ sprintf(message_buffer, "4%c", ch); if(send_data(message_buffer) == 0) draw_new(global_display, "system>> Send failed"); } fclose(fp); sleep(1); strcpy(message_buffer, "5"); send_data(message_buffer); draw_new(global_display, "system>> Done!"); } else if (split_strcmp(0, 2, "/up", 0, 2, message_buffer)){ split_str(4, strlen(message_buffer), message_buffer, message_buffer_2); buffer_int = atoi(message_buffer_2); draw_old_line(global_display, 1, buffer_int); } else if (split_strcmp(0, 4, "/down", 0, 4, message_buffer)){ split_str(6, strlen(message_buffer), message_buffer, message_buffer_2); buffer_int = atoi(message_buffer_2); draw_old_line(global_display, 2, buffer_int); } else if (split_strcmp(0, 4, "/help", 0, 4, message_buffer)){ draw_new(global_display, "system>> ### THIS IS HELP! ###"); draw_new(global_display, "system>> \":q!\" to exit program."); draw_new(global_display, "system>> \"/talkto [nickname]\" to choose contact."); draw_new(global_display, "system>> \"/untalk\" to remove contact that we are talking."); draw_new(global_display, "system>> \"/upload [file]\" to upload file to client that you are talking."); draw_new(global_display, "system>> \"/watline\" to show number of latest line"); draw_new(global_display, "system>> \"/up [amount of line]\" to scroll screen up n lines."); draw_new(global_display, "system>> \"/down [amount of line]\" to scroll screen down n lines."); draw_new(global_display, "system>> \"/find [word]\" to find number of line that word was display."); draw_new(global_display, "system>> \"/contact\" to show all user on server."); } else if (split_strcmp(0, 4, "/find", 0, 4, message_buffer)){ split_str(6, strlen(message_buffer) - 1, message_buffer, message_buffer_2); search(message_buffer_2, global_display); } else if (split_strcmp(0, 7, "/watline", 0, 7, message_buffer)){ //bottom_line come from buffer_screen.h sprintf(message_buffer, "system>> v This is lines number %d. v", bottom_line); draw_new(global_display, message_buffer); } else if ( split_strcmp(0, 6, "/talkto", 0, 6, message_buffer) || split_strcmp(0, 6, "/untalk", 0, 6, message_buffer) || split_strcmp(0, 7, "/contact", 0, 7, message_buffer)) { sprintf(message_buffer_2, "0%s", message_buffer); send_data(message_buffer_2); } else { draw_new(global_display, "system>> Command not found."); } } else { //Set protocal to send packet sprintf(message_buffer_2, "0%s", message_buffer); if(send_data(message_buffer_2) == 0) draw_new(global_display, "system>> Send failed"); } werase(global_typing); } pthread_cancel(*global_display_thread); return 0; }
/** * Avalia se o pacote deve ser redirecionado ou salvo. * @param packet Ponteiro para o pacote. * @param usage_type Tipo do cliente que está chamando a função. * @return 0 em falha e !0 em sucesso. */ int where_to_send(char *packet, usage_type_t usage_type) { struct iphdr *ip; struct udphdr *udp; struct data_info *data; struct in_addr tmp; int ret; ip = (struct iphdr *)packet; udp = get_udp_packet(packet); /* Verifica a sanidade do pacote, se estiver com erro, dropa */ if (!sanity_check(ip)) { printf("Packet received with error, dropping.\n"); cstats.lost_pkts++; return 0; } switch (usage_type) { case ROUTER_USAGE: /* Router esta fazendo forward do pacote, subtrai ttl */ ip->ttl -= IPTTLDEC; ip->check = 0; ip->check = in_cksum((unsigned short *)ip, ip->tot_len); cstats.fw_pkts += ip->tot_len; printf("Forwarding packet:\n"); printf("\tPacket ttl %d\n", ip->ttl); printf("\tPacket size: %d bytes\n", ip->tot_len); tmp.s_addr = ip->saddr; printf("\tFrom: %s\n", inet_ntoa(tmp)); tmp.s_addr = ip->daddr; printf("\tTo: %s\n", inet_ntoa(tmp)); if ((ret = send_data(packet)) < 0) { printf("* Error forwarding packet. *\n"); cstats.lost_pkts++; } break; default: data = get_packet_data(packet); if (data->fragmented) { save_packet_fragment(data); if (is_packet_complete(data)) { /* Se o pacote for um fragmento e completar o dado, salva e * remove do buffer */ printf("Fragmented Data complete.\n"); struct data_info *dinfo = get_defragmented_data(data->id); ret = save_data(dinfo); cstats.recv_pkts += ip->tot_len; printf("Data received:\n"); printf("\tPacket: %lld bytes\n", dinfo->tot_len); tmp.s_addr = ip->saddr; printf("\tFrom: %s\n", inet_ntoa(tmp)); printf("\tFile Name: %s\n", ((char *)dinfo + sizeof(struct data_info))); printf("\tFile size: %ld bytes\n", dinfo->data_size); } else { /* Se o pacote for um fragmento, apenas adiciona ao buffer e * adiciona seus dados à estatística. */ cstats.recv_pkts += ip->tot_len; printf("."); ret = 0; } break; } /* Se o pacote não for um fragmento, salva e adiciona seus dados à * estatística. */ ret = save_data(data); cstats.recv_pkts += ip->tot_len; printf("Data received:\n"); printf("\tPacket: %d bytes\n", ip->tot_len); tmp.s_addr = ip->saddr; printf("\tFrom: %s\n", inet_ntoa(tmp)); printf("\tFile Name: %s\n", ((char *)data + sizeof(struct data_info))); printf("\tFile size: %ld bytes\n", data->data_size); break; } return ret; }
void send_commands() { kvstore_cmd_t cmd; kvstore_ack_t ack; char buf[100]; const char *delims = " "; char * parsed; int len; /* FIXME for now. Improve this by using a more * appropriate parser */ char *op, *kv_key, *kv_val; //int ret; memset(&cmd, 0, sizeof(kvstore_cmd_t)); memset(&ack, 0, sizeof(kvstore_ack_t)); do { memset(buf, 0, sizeof(buf)); printf("\n(kv) "); fflush(stdout); fgets(buf, sizeof(buf), stdin); parsed = strdup(buf); str_trim(&parsed); len = strlen(parsed); if (len == 0) { continue; } op = strtok(parsed, delims); // get the op kvstore_type_t kv_type = get_type(op); if (kv_type == KVSTORE_NONE) { printf("ERROR: Invalid Operation"); continue; } switch (kv_type) { case KVSTORE_EXIT: return; default: break; } // get the key and message kv_key = strtok(NULL, delims); if (kv_key == NULL) { printf("ERROR: Invalid Operation"); continue; } // if we're just using get if (kv_type == KVSTORE_GET) { kv_val = ""; } else { kv_val = strtok(NULL, "\0"); } // set the code and message then encrypt memset(&cmd, 0, sizeof(cmd)); cmd.type = kv_type; strncpy((char *)&cmd.payload.key, kv_key, KVSTORE_KEY_LEN); strncpy((char *)&cmd.payload.val, kv_val, KVSTORE_VAL_LEN); cmd.payload.key[strlen(kv_key)] = '\0'; // copy the IV memcpy(cmd.iv, iv, KVSTORE_AESIV_LEN); aes_setkey_enc(&aes, enckey, KVSTORE_AESKEY_BITS); aes_crypt_cbc(&aes, AES_ENCRYPT, sizeof(cmd.payload), iv, (const unsigned char *)&cmd.payload, (unsigned char *)&cmd.payload); if (send_data(&pfd, &cmd, sizeof(cmd))) { goto exit; } if (kv_type == KVSTORE_SET) { // just get the acknowledgement // TODO check content if (get_ack(&pfd, &ack)) { goto exit; } printf("OK"); } else if (kv_type == KVSTORE_GET) { // get the data if(get_resp(&pfd, &cmd)) { goto exit; } aes_setkey_dec(&aes, enckey, KVSTORE_AESKEY_BITS); // now decrypt aes_crypt_cbc(&aes, AES_DECRYPT, sizeof(cmd.payload), cmd.iv, (const unsigned char *)&cmd.payload, (unsigned char *)&cmd.payload); printf("%s", cmd.payload.val); } // printf("op: %s, title: %s, data: %s\n", op, kv_key, kv_msg); } while(1); exit: printf("error\n"); }
static int mitsu70x_main_loop(void *vctx, int copies) { struct mitsu70x_ctx *ctx = vctx; struct mitsu70x_state rdbuf, rdbuf2; int last_state = -1, state = S_IDLE; int ret; if (!ctx) return CUPS_BACKEND_FAILED; top: if (state != last_state) { if (dyesub_debug) DEBUG("last_state %d new %d\n", last_state, state); } ret = mitsu70x_get_state(ctx, &rdbuf); if (ret) return CUPS_BACKEND_FAILED; if (memcmp(&rdbuf, &rdbuf2, sizeof(rdbuf))) { memcpy(&rdbuf2, &rdbuf, sizeof(rdbuf)); } else if (state == last_state) { sleep(1); } last_state = state; fflush(stderr); switch (state) { case S_IDLE: INFO("Waiting for printer idle\n"); #if 0 // XXX no idea if this works.. if (rdbuf.data[9] != 0x00) { break; } #endif INFO("Sending attention sequence\n"); if ((ret = send_data(ctx->dev, ctx->endp_down, ctx->databuf, 512))) return CUPS_BACKEND_FAILED; state = S_SENT_ATTN; break; case S_SENT_ATTN: { struct mitsu70x_status_resp resp; ret = mitsu70x_get_status(ctx, &resp); if (ret < 0) return CUPS_BACKEND_FAILED; /* Yes, do it twice.. */ ret = mitsu70x_get_status(ctx, &resp); if (ret < 0) return CUPS_BACKEND_FAILED; // XXX check resp for sanity? state = S_SENT_HDR; break; } case S_SENT_HDR: INFO("Sending Page setup sequence\n"); if ((ret = mitsu70x_do_pagesetup(ctx))) return ret; INFO("Sending header sequence\n"); /* K60 may require fixups */ if (ctx->k60) { /* K60 only has a lower deck */ ctx->databuf[512+32] = 1; /* 4x6 prints on 6x8 media need multicut mode */ if (ctx->databuf[512+16] == 0x07 && ctx->databuf[512+16+1] == 0x48 && ctx->databuf[512+16+2] == 0x04 && ctx->databuf[512+16+3] == 0xc2) { ctx->databuf[512+48] = 1; } } if ((ret = send_data(ctx->dev, ctx->endp_down, ctx->databuf + 512, 512))) return CUPS_BACKEND_FAILED; INFO("Sending data\n"); if ((ret = send_data(ctx->dev, ctx->endp_down, ctx->databuf + 1024, ctx->datalen - 1024))) return CUPS_BACKEND_FAILED; state = S_SENT_DATA; break; case S_SENT_DATA: INFO("Waiting for printer to acknowledge completion\n"); state = S_FINISHED; break; default: break; }; if (state != S_FINISHED) goto top; /* Clean up */ if (terminate) copies = 1; INFO("Print complete (%d copies remaining)\n", copies - 1); if (copies && --copies) { state = S_IDLE; goto top; } return CUPS_BACKEND_OK; }
/* * Send a file via the TFTP data session. */ void tftp_send(int peer, uint16_t *block, struct tftp_stats *ts) { struct tftphdr *rp; int size, n_data, n_ack, try; uint16_t oldblock; char sendbuffer[MAXPKTSIZE]; char recvbuffer[MAXPKTSIZE]; rp = (struct tftphdr *)recvbuffer; *block = 1; ts->amount = 0; do { if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Sending block %d", *block); size = read_file(sendbuffer, segsize); if (size < 0) { tftp_log(LOG_ERR, "read_file returned %d", size); send_error(peer, errno + 100); goto abort; } for (try = 0; ; try++) { n_data = send_data(peer, *block, sendbuffer, size); if (n_data > 0) { if (try == maxtimeouts) { tftp_log(LOG_ERR, "Cannot send DATA packet #%d, " "giving up", *block); return; } tftp_log(LOG_ERR, "Cannot send DATA packet #%d, trying again", *block); continue; } n_ack = receive_packet(peer, recvbuffer, MAXPKTSIZE, NULL, timeoutpacket); if (n_ack < 0) { if (n_ack == RP_TIMEOUT) { if (try == maxtimeouts) { tftp_log(LOG_ERR, "Timeout #%d send ACK %d " "giving up", try, *block); return; } tftp_log(LOG_WARNING, "Timeout #%d on ACK %d", try, *block); continue; } /* Either read failure or ERROR packet */ if (debug&DEBUG_SIMPLE) tftp_log(LOG_ERR, "Aborting: %s", rp_strerror(n_ack)); goto abort; } if (rp->th_opcode == ACK) { ts->blocks++; if (rp->th_block == *block) { ts->amount += size; break; } /* Re-synchronize with the other side */ (void) synchnet(peer); if (rp->th_block == (*block - 1)) { ts->retries++; continue; } } } oldblock = *block; (*block)++; if (oldblock > *block) { if (options[OPT_ROLLOVER].o_request == NULL) { /* * "rollover" option not specified in * tftp client. Default to rolling block * counter to 0. */ *block = 0; } else { *block = atoi(options[OPT_ROLLOVER].o_request); } ts->rollovers++; } gettimeofday(&(ts->tstop), NULL); } while (size == segsize); abort: return; } /* * Receive a file via the TFTP data session. * * - It could be that the first block has already arrived while * trying to figure out if we were receiving options or not. In * that case it is passed to this function. */ void tftp_receive(int peer, uint16_t *block, struct tftp_stats *ts, struct tftphdr *firstblock, size_t fb_size) { struct tftphdr *rp; uint16_t oldblock; int n_data, n_ack, writesize, i, retry; char recvbuffer[MAXPKTSIZE]; ts->amount = 0; if (firstblock != NULL) { writesize = write_file(firstblock->th_data, fb_size); ts->amount += writesize; for (i = 0; ; i++) { n_ack = send_ack(peer, *block); if (n_ack > 0) { if (i == maxtimeouts) { tftp_log(LOG_ERR, "Cannot send ACK packet #%d, " "giving up", *block); return; } tftp_log(LOG_ERR, "Cannot send ACK packet #%d, trying again", *block); continue; } break; } if (fb_size != segsize) { gettimeofday(&(ts->tstop), NULL); return; } } rp = (struct tftphdr *)recvbuffer; do { oldblock = *block; (*block)++; if (oldblock > *block) { if (options[OPT_ROLLOVER].o_request == NULL) { /* * "rollover" option not specified in * tftp client. Default to rolling block * counter to 0. */ *block = 0; } else { *block = atoi(options[OPT_ROLLOVER].o_request); } ts->rollovers++; } for (retry = 0; ; retry++) { if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Receiving DATA block %d", *block); n_data = receive_packet(peer, recvbuffer, MAXPKTSIZE, NULL, timeoutpacket); if (n_data < 0) { if (retry == maxtimeouts) { tftp_log(LOG_ERR, "Timeout #%d on DATA block %d, " "giving up", retry, *block); return; } if (n_data == RP_TIMEOUT) { tftp_log(LOG_WARNING, "Timeout #%d on DATA block %d", retry, *block); send_ack(peer, oldblock); continue; } /* Either read failure or ERROR packet */ if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Aborting: %s", rp_strerror(n_data)); goto abort; } if (rp->th_opcode == DATA) { ts->blocks++; if (rp->th_block == *block) break; tftp_log(LOG_WARNING, "Expected DATA block %d, got block %d", *block, rp->th_block); /* Re-synchronize with the other side */ (void) synchnet(peer); if (rp->th_block == (*block-1)) { tftp_log(LOG_INFO, "Trying to sync"); *block = oldblock; ts->retries++; goto send_ack; /* rexmit */ } } else { tftp_log(LOG_WARNING, "Expected DATA block, got %s block", packettype(rp->th_opcode)); } } if (n_data > 0) { writesize = write_file(rp->th_data, n_data); ts->amount += writesize; if (writesize <= 0) { tftp_log(LOG_ERR, "write_file returned %d", writesize); if (writesize < 0) send_error(peer, errno + 100); else send_error(peer, ENOSPACE); goto abort; } } send_ack: for (i = 0; ; i++) { n_ack = send_ack(peer, *block); if (n_ack > 0) { if (i == maxtimeouts) { tftp_log(LOG_ERR, "Cannot send ACK packet #%d, " "giving up", *block); return; } tftp_log(LOG_ERR, "Cannot send ACK packet #%d, trying again", *block); continue; } break; } gettimeofday(&(ts->tstop), NULL); } while (n_data == segsize); /* Don't do late packet management for the client implementation */ if (acting_as_client) return; for (i = 0; ; i++) { n_data = receive_packet(peer, (char *)rp, pktsize, NULL, timeoutpacket); if (n_data <= 0) break; if (n_data > 0 && rp->th_opcode == DATA && /* and got a data block */ *block == rp->th_block) /* then my last ack was lost */ send_ack(peer, *block); /* resend final ack */ } abort: return; }
uint32_t group_newpeer(Group_Chat *chat, uint8_t *client_id) { addpeer(chat, client_id); return send_data(chat, client_id, crypto_box_PUBLICKEYBYTES, 16); //TODO: better return values? }
/* * Called by libusb (as triggered by handle_event()) when a transfer comes in. * Only channel data comes in asynchronously, and all transfers for this are * queued up beforehand, so this just needs to chuck the incoming data onto * the libsigrok session bus. */ static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer) { struct sr_dev_inst *sdi; struct dev_context *devc; sdi = transfer->user_data; devc = sdi->priv; if (devc->dev_state == FLUSH) { g_free(transfer->buffer); libusb_free_transfer(transfer); devc->dev_state = CAPTURE; devc->aq_started = g_get_monotonic_time(); read_channel(sdi, data_amount(sdi)); return; } if (devc->dev_state != CAPTURE) return; if (!devc->sample_buf) { devc->sample_buf_size = 10; devc->sample_buf = g_try_malloc(devc->sample_buf_size * sizeof(transfer)); devc->sample_buf_write = 0; } if (devc->sample_buf_write >= devc->sample_buf_size) { devc->sample_buf_size += 10; devc->sample_buf = g_try_realloc(devc->sample_buf, devc->sample_buf_size * sizeof(transfer)); if (!devc->sample_buf) { sr_err("Sample buffer malloc failed."); devc->dev_state = STOPPING; return; } } devc->sample_buf[devc->sample_buf_write++] = transfer; devc->samp_received += transfer->actual_length / NUM_CHANNELS; sr_spew("receive_transfer(): calculated samplerate == %" PRIu64 "ks/s", (uint64_t)(transfer->actual_length * 1000 / (g_get_monotonic_time() - devc->read_start_ts + 1) / NUM_CHANNELS)); sr_spew("receive_transfer(): status %s received %d bytes.", libusb_error_name(transfer->status), transfer->actual_length); if (transfer->actual_length == 0) /* Nothing to send to the bus. */ return; if (devc->limit_samples && devc->samp_received >= devc->limit_samples) { sr_info("Requested number of samples reached, stopping. %" PRIu64 " <= %" PRIu64, devc->limit_samples, devc->samp_received); send_data(sdi, devc->sample_buf, devc->limit_samples); sdi->driver->dev_acquisition_stop(sdi); } else if (devc->limit_msec && (g_get_monotonic_time() - devc->aq_started) / 1000 >= devc->limit_msec) { sr_info("Requested time limit reached, stopping. %d <= %d", (uint32_t)devc->limit_msec, (uint32_t)(g_get_monotonic_time() - devc->aq_started) / 1000); send_data(sdi, devc->sample_buf, devc->samp_received); g_free(devc->sample_buf); devc->sample_buf = NULL; sdi->driver->dev_acquisition_stop(sdi); } else { read_channel(sdi, data_amount(sdi)); } }
uint32_t group_sendmessage(Group_Chat *chat, uint8_t *message, uint32_t length) { return send_data(chat, message, length, 64); //TODO: better return values? }
static int32_t nt35510_init(struct lcd_spec *self) { Send_data send_cmd = self->info.mcu->ops->send_cmd; Send_data send_data = self->info.mcu->ops->send_data; LCD_PRINT("nt35510_init===\n"); mdelay(200); //Power setting sequence send_cmd(0xF000); send_data(0x55); send_cmd(0xF001); send_data(0xAA); send_cmd(0xF002); send_data(0x52); send_cmd(0xF003); send_data(0x08); send_cmd(0xF004); send_data(0x01); send_cmd(0xB000); send_data(0x09); send_cmd(0xB001); send_data(0x09); send_cmd(0xB002); send_data(0x09); send_cmd(0xB600); send_data(0x34); send_cmd(0xB601); send_data(0x34); send_cmd(0xB602); send_data(0x34); send_cmd(0xB100); send_data(0x09); send_cmd(0xB101); send_data(0x09); send_cmd(0xB102); send_data(0x09); send_cmd(0xB700); send_data(0x24); send_cmd(0xB701); send_data(0x24); send_cmd(0xB702); send_data(0x24); send_cmd(0xB300); send_data(0x05); send_cmd(0xB301); send_data(0x05); send_cmd(0xB302); send_data(0x05); send_cmd(0xB900); send_data(0x24); send_cmd(0xB901); send_data(0x24); send_cmd(0xB902); send_data(0x24); send_cmd(0xBF00); send_data(0x01); send_cmd(0xB500); send_data(0x0B); send_cmd(0xB501); send_data(0x0B); send_cmd(0xB502); send_data(0x0B); send_cmd(0xBA00); send_data(0x24); send_cmd(0xBA01); send_data(0x24); send_cmd(0xBA02); send_data(0x24); send_cmd(0xBC00); send_data(0x00); send_cmd(0xBC01); send_data(0xA3); send_cmd(0xBC02); send_data(0x00); send_cmd(0xBD00); send_data(0x00); send_cmd(0xBD01); send_data(0xA3); send_cmd(0xBD02); send_data(0x00); mdelay(120); //Display parameter setting send_cmd(0xF000); send_data(0x55); send_cmd(0xF001); send_data(0xAA); send_cmd(0xF002); send_data(0x52); send_cmd(0xF003); send_data(0x08); send_cmd(0xF004); send_data(0x00); send_cmd(0xB000); send_data(0x00); send_cmd(0xB600); send_data(0x0A); send_cmd(0xB700); send_data(0x00); send_cmd(0xB701); send_data(0x00); send_cmd(0xB800); send_data(0x01); send_cmd(0xB801); send_data(0x05); send_cmd(0xB802); send_data(0x05); send_cmd(0xB803); send_data(0x05); send_cmd(0xBA00); send_data(0x01); send_cmd(0xBC00); send_data(0x00); send_cmd(0xBc01); send_data(0x00); send_cmd(0xBC02); send_data(0x00); send_cmd(0xBD00); send_data(0x01); send_cmd(0xBD01); send_data(0x84); send_cmd(0xBD02); send_data(0x07); send_cmd(0xBD03); send_data(0x31); send_cmd(0xBD04); send_data(0x00); send_cmd(0xBE00); send_data(0x01); send_cmd(0xBE01); send_data(0x84); send_cmd(0xBE02); send_data(0x07); send_cmd(0xBE03); send_data(0x31); send_cmd(0xBE04); send_data(0x00); send_cmd(0xBF00); send_data(0x01); send_cmd(0xBF01); send_data(0x84); send_cmd(0xBF02); send_data(0x07); send_cmd(0xBF03); send_data(0x31); send_cmd(0xBF04); send_data(0x00); send_cmd(0xCC00); send_data(0x03); send_cmd(0xCC01); send_data(0x00); send_cmd(0xCC02); send_data(0x00); send_cmd(0xB101); send_data(0x03); send_cmd(0x3500); send_data(0x00); send_cmd(0x3600); send_data(0xD6);//(0x00);->0x01->0x11 send_cmd(0x3A00); send_data(0x05); send_cmd(0x2C00); //Gamma setting R+ send_cmd(0xD100); send_data(0x00); send_cmd(0xD101); send_data(0x37); send_cmd(0xD102); send_data(0x00); send_cmd(0xD103); send_data(0x51); send_cmd(0xD104); send_data(0x00); send_cmd(0xD105); send_data(0x71); send_cmd(0xD106); send_data(0x00); send_cmd(0xD107); send_data(0x96); send_cmd(0xD108); send_data(0x00); send_cmd(0xD109); send_data(0xAA); send_cmd(0xD10A); send_data(0x00); send_cmd(0xD10B); send_data(0xC9); send_cmd(0xD10C); send_data(0x00); send_cmd(0xD10D); send_data(0xE4); send_cmd(0xD10E); send_data(0x01); send_cmd(0xD10F); send_data(0x1C); send_cmd(0xD110); send_data(0x01); send_cmd(0xD111); send_data(0x3C); send_cmd(0xD112); send_data(0x01); send_cmd(0xD113); send_data(0x80); send_cmd(0xD114); send_data(0x01); send_cmd(0xD115); send_data(0xB5); send_cmd(0xD116); send_data(0x02); send_cmd(0xD117); send_data(0x02); send_cmd(0xD118); send_data(0x02); send_cmd(0xD119); send_data(0x48); send_cmd(0xD11A); send_data(0x02); send_cmd(0xD11B); send_data(0x4A); send_cmd(0xD11C); send_data(0x02); send_cmd(0xD11D); send_data(0x83); send_cmd(0xD11E); send_data(0x02); send_cmd(0xD11F); send_data(0xC5); send_cmd(0xD120); send_data(0x02); send_cmd(0xD121); send_data(0xE8); send_cmd(0xD122); send_data(0x03); send_cmd(0xD123); send_data(0x14); send_cmd(0xD124); send_data(0x03); send_cmd(0xD125); send_data(0x32); send_cmd(0xD126); send_data(0x03); send_cmd(0xD127); send_data(0x5D); send_cmd(0xD128); send_data(0x03); send_cmd(0xD129); send_data(0x73); send_cmd(0xD12A); send_data(0x03); send_cmd(0xD12B); send_data(0x91); send_cmd(0xD12C); send_data(0x03); send_cmd(0xD12D); send_data(0xA0); send_cmd(0xD12E); send_data(0x03); send_cmd(0xD12F); send_data(0xBF); send_cmd(0xD130); send_data(0x03); send_cmd(0xD131); send_data(0xCF); send_cmd(0xD132); send_data(0x03); send_cmd(0xD133); send_data(0xDF); //Gamma setting G+ send_cmd(0xD200); send_data(0x00); send_cmd(0xD201); send_data(0x37); send_cmd(0xD202); send_data(0x00); send_cmd(0xD203); send_data(0x51); send_cmd(0xD204); send_data(0x00); send_cmd(0xD205); send_data(0x71); send_cmd(0xD206); send_data(0x00); send_cmd(0xD207); send_data(0x96); send_cmd(0xD208); send_data(0x00); send_cmd(0xD209); send_data(0xAA); send_cmd(0xD20A); send_data(0x00); send_cmd(0xD20B); send_data(0xC9); send_cmd(0xD20C); send_data(0x00); send_cmd(0xD20D); send_data(0xE4); send_cmd(0xD20E); send_data(0x01); send_cmd(0xD20F); send_data(0x1C); send_cmd(0xD210); send_data(0x01); send_cmd(0xD211); send_data(0x3C); send_cmd(0xD212); send_data(0x01); send_cmd(0xD213); send_data(0x80); send_cmd(0xD214); send_data(0x01); send_cmd(0xD215); send_data(0xB5); send_cmd(0xD216); send_data(0x02); send_cmd(0xD217); send_data(0x02); send_cmd(0xD218); send_data(0x02); send_cmd(0xD219); send_data(0x48); send_cmd(0xD21A); send_data(0x02); send_cmd(0xD21B); send_data(0x4A); send_cmd(0xD21C); send_data(0x02); send_cmd(0xD21D); send_data(0x83); send_cmd(0xD21E); send_data(0x02); send_cmd(0xD21F); send_data(0xC5); send_cmd(0xD220); send_data(0x02); send_cmd(0xD221); send_data(0xE8); send_cmd(0xD222); send_data(0x03); send_cmd(0xD223); send_data(0x14); send_cmd(0xD224); send_data(0x03); send_cmd(0xD225); send_data(0x32); send_cmd(0xD226); send_data(0x03); send_cmd(0xD227); send_data(0x5D); send_cmd(0xD228); send_data(0x03); send_cmd(0xD229); send_data(0x73); send_cmd(0xD22A); send_data(0x03); send_cmd(0xD22B); send_data(0x91); send_cmd(0xD22C); send_data(0x03); send_cmd(0xD22D); send_data(0xA0); send_cmd(0xD22E); send_data(0x03); send_cmd(0xD22F); send_data(0xBF); send_cmd(0xD230); send_data(0x03); send_cmd(0xD231); send_data(0xCF); send_cmd(0xD232); send_data(0x03); send_cmd(0xD233); send_data(0xDF); //Gamma setting B+ send_cmd(0xD300); send_data(0x00); send_cmd(0xD301); send_data(0x37); send_cmd(0xD302); send_data(0x00); send_cmd(0xD303); send_data(0x51); send_cmd(0xD304); send_data(0x00); send_cmd(0xD305); send_data(0x71); send_cmd(0xD306); send_data(0x00); send_cmd(0xD307); send_data(0x96); send_cmd(0xD308); send_data(0x00); send_cmd(0xD309); send_data(0xAA); send_cmd(0xD30A); send_data(0x00); send_cmd(0xD30B); send_data(0xC9); send_cmd(0xD30C); send_data(0x00); send_cmd(0xD30D); send_data(0xE4); send_cmd(0xD30E); send_data(0x01); send_cmd(0xD30F); send_data(0x1C); send_cmd(0xD310); send_data(0x01); send_cmd(0xD311); send_data(0x3C); send_cmd(0xD312); send_data(0x01); send_cmd(0xD313); send_data(0x80); send_cmd(0xD314); send_data(0x01); send_cmd(0xD315); send_data(0xB5); send_cmd(0xD316); send_data(0x02); send_cmd(0xD317); send_data(0x02); send_cmd(0xD318); send_data(0x02); send_cmd(0xD319); send_data(0x48); send_cmd(0xD31A); send_data(0x02); send_cmd(0xD31B); send_data(0x4A); send_cmd(0xD31C); send_data(0x02); send_cmd(0xD31D); send_data(0x83); send_cmd(0xD31E); send_data(0x02); send_cmd(0xD31F); send_data(0xC5); send_cmd(0xD320); send_data(0x02); send_cmd(0xD321); send_data(0xE8); send_cmd(0xD322); send_data(0x03); send_cmd(0xD323); send_data(0x14); send_cmd(0xD324); send_data(0x03); send_cmd(0xD325); send_data(0x32); send_cmd(0xD326); send_data(0x03); send_cmd(0xD327); send_data(0x5D); send_cmd(0xD328); send_data(0x03); send_cmd(0xD329); send_data(0x73); send_cmd(0xD32A); send_data(0x03); send_cmd(0xD32B); send_data(0x91); send_cmd(0xD32C); send_data(0x03); send_cmd(0xD32D); send_data(0xA0); send_cmd(0xD32E); send_data(0x03); send_cmd(0xD32F); send_data(0xBF); send_cmd(0xD330); send_data(0x03); send_cmd(0xD331); send_data(0xCF); send_cmd(0xD332); send_data(0x03); send_cmd(0xD333); send_data(0xDF); //Gamma setting R- send_cmd(0xD400); send_data(0x00); send_cmd(0xD401); send_data(0x37); send_cmd(0xD402); send_data(0x00); send_cmd(0xD403); send_data(0x51); send_cmd(0xD404); send_data(0x00); send_cmd(0xD405); send_data(0x71); send_cmd(0xD406); send_data(0x00); send_cmd(0xD407); send_data(0x96); send_cmd(0xD408); send_data(0x00); send_cmd(0xD409); send_data(0xAA); send_cmd(0xD40A); send_data(0x00); send_cmd(0xD40B); send_data(0xC9); send_cmd(0xD40C); send_data(0x00); send_cmd(0xD40D); send_data(0xE4); send_cmd(0xD40E); send_data(0x01); send_cmd(0xD40F); send_data(0x1C); send_cmd(0xD410); send_data(0x01); send_cmd(0xD411); send_data(0x3C); send_cmd(0xD412); send_data(0x01); send_cmd(0xD413); send_data(0x80); send_cmd(0xD414); send_data(0x01); send_cmd(0xD415); send_data(0xB5); send_cmd(0xD416); send_data(0x02); send_cmd(0xD417); send_data(0x02); send_cmd(0xD418); send_data(0x02); send_cmd(0xD419); send_data(0x48); send_cmd(0xD41A); send_data(0x02); send_cmd(0xD41B); send_data(0x4A); send_cmd(0xD41C); send_data(0x02); send_cmd(0xD41D); send_data(0x83); send_cmd(0xD41E); send_data(0x02); send_cmd(0xD41F); send_data(0xC5); send_cmd(0xD420); send_data(0x02); send_cmd(0xD421); send_data(0xE8); send_cmd(0xD422); send_data(0x03); send_cmd(0xD423); send_data(0x14); send_cmd(0xD424); send_data(0x03); send_cmd(0xD425); send_data(0x32); send_cmd(0xD426); send_data(0x03); send_cmd(0xD427); send_data(0x5D); send_cmd(0xD428); send_data(0x03); send_cmd(0xD429); send_data(0x73); send_cmd(0xD42A); send_data(0x03); send_cmd(0xD42B); send_data(0x91); send_cmd(0xD42C); send_data(0x03); send_cmd(0xD42D); send_data(0xA0); send_cmd(0xD42E); send_data(0x03); send_cmd(0xD42F); send_data(0xBF); send_cmd(0xD430); send_data(0x03); send_cmd(0xD431); send_data(0xCF); send_cmd(0xD432); send_data(0x03); send_cmd(0xD433); send_data(0xDF); //Gamma setting G- send_cmd(0xD500); send_data(0x00); send_cmd(0xD501); send_data(0x37); send_cmd(0xD502); send_data(0x00); send_cmd(0xD503); send_data(0x51); send_cmd(0xD504); send_data(0x00); send_cmd(0xD505); send_data(0x71); send_cmd(0xD506); send_data(0x00); send_cmd(0xD507); send_data(0x96); send_cmd(0xD508); send_data(0x00); send_cmd(0xD509); send_data(0xAA); send_cmd(0xD50A); send_data(0x00); send_cmd(0xD50B); send_data(0xC9); send_cmd(0xD50C); send_data(0x00); send_cmd(0xD50D); send_data(0xE4); send_cmd(0xD50E); send_data(0x01); send_cmd(0xD50F); send_data(0x1C); send_cmd(0xD510); send_data(0x01); send_cmd(0xD511); send_data(0x3C); send_cmd(0xD512); send_data(0x01); send_cmd(0xD513); send_data(0x80); send_cmd(0xD514); send_data(0x01); send_cmd(0xD515); send_data(0xB5); send_cmd(0xD516); send_data(0x02); send_cmd(0xD517); send_data(0x02); send_cmd(0xD518); send_data(0x02); send_cmd(0xD519); send_data(0x48); send_cmd(0xD51A); send_data(0x02); send_cmd(0xD51B); send_data(0x4A); send_cmd(0xD51C); send_data(0x02); send_cmd(0xD51D); send_data(0x83); send_cmd(0xD51E); send_data(0x02); send_cmd(0xD51F); send_data(0xC5); send_cmd(0xD520); send_data(0x02); send_cmd(0xD521); send_data(0xE8); send_cmd(0xD522); send_data(0x03); send_cmd(0xD523); send_data(0x14); send_cmd(0xD524); send_data(0x03); send_cmd(0xD525); send_data(0x32); send_cmd(0xD526); send_data(0x03); send_cmd(0xD527); send_data(0x5D); send_cmd(0xD528); send_data(0x03); send_cmd(0xD529); send_data(0x73); send_cmd(0xD52A); send_data(0x03); send_cmd(0xD52B); send_data(0x91); send_cmd(0xD52C); send_data(0x03); send_cmd(0xD52D); send_data(0xA0); send_cmd(0xD52E); send_data(0x03); send_cmd(0xD52F); send_data(0xBF); send_cmd(0xD530); send_data(0x03); send_cmd(0xD531); send_data(0xCF); send_cmd(0xD532); send_data(0x03); send_cmd(0xD533); send_data(0xDF); //Gamma setting B- send_cmd(0xD600); send_data(0x00); send_cmd(0xD601); send_data(0x37); send_cmd(0xD602); send_data(0x00); send_cmd(0xD603); send_data(0x51); send_cmd(0xD604); send_data(0x00); send_cmd(0xD605); send_data(0x71); send_cmd(0xD606); send_data(0x00); send_cmd(0xD607); send_data(0x96); send_cmd(0xD608); send_data(0x00); send_cmd(0xD609); send_data(0xAA); send_cmd(0xD60A); send_data(0x00); send_cmd(0xD60B); send_data(0xC9); send_cmd(0xD60C); send_data(0x00); send_cmd(0xD60D); send_data(0xE4); send_cmd(0xD60E); send_data(0x01); send_cmd(0xD60F); send_data(0x1C); send_cmd(0xD610); send_data(0x01); send_cmd(0xD611); send_data(0x3C); send_cmd(0xD612); send_data(0x01); send_cmd(0xD613); send_data(0x80); send_cmd(0xD614); send_data(0x01); send_cmd(0xD615); send_data(0xB5); send_cmd(0xD616); send_data(0x02); send_cmd(0xD617); send_data(0x02); send_cmd(0xD618); send_data(0x02); send_cmd(0xD619); send_data(0x48); send_cmd(0xD61A); send_data(0x02); send_cmd(0xD61B); send_data(0x4A); send_cmd(0xD61C); send_data(0x02); send_cmd(0xD61D); send_data(0x83); send_cmd(0xD61E); send_data(0x02); send_cmd(0xD61F); send_data(0xC5); send_cmd(0xD620); send_data(0x02); send_cmd(0xD621); send_data(0xE8); send_cmd(0xD622); send_data(0x03); send_cmd(0xD623); send_data(0x14); send_cmd(0xD624); send_data(0x03); send_cmd(0xD625); send_data(0x32); send_cmd(0xD626); send_data(0x03); send_cmd(0xD627); send_data(0x5D); send_cmd(0xD628); send_data(0x03); send_cmd(0xD629); send_data(0x73); send_cmd(0xD62A); send_data(0x03); send_cmd(0xD62B); send_data(0x91); send_cmd(0xD62C); send_data(0x03); send_cmd(0xD62D); send_data(0xA0); send_cmd(0xD62E); send_data(0x03); send_cmd(0xD62F); send_data(0xBF); send_cmd(0xD630); send_data(0x03); send_cmd(0xD631); send_data(0xCF); send_cmd(0xD632); send_data(0x03); send_cmd(0xD633); send_data(0xDF); send_cmd(0x1100); // (DISPON) mdelay(100); // 100ms send_cmd(0x2900); // (DISPON) mdelay(100); return 0; }
void server_check(int conn_fd) { char buf[32]; char name[32]; char passwd[32]; char pathname[SIZE] = {"/home/qiong/userinfo/"}; int ret; int flag; int fd; char log[SIZE]; int i; send_data(conn_fd, "b\n"); sleep(1); while(1) { my_recv(conn_fd, buf, sizeof(buf)); if (buf[0] == 'u') { send_data(conn_fd, "b\n"); sleep(1); ret = recv(conn_fd, buf, sizeof(buf), 0); buf[ret-1] = '\0'; strcpy(name, buf); flag = find_name(buf); if (flag == 0) { send_data(conn_fd, "y\n"); sleep(1); } else { send_data(conn_fd, "n\n"); sleep(1); continue; } my_recv(conn_fd, buf, sizeof(buf)); send_data(conn_fd, "b\n"); sleep(1); ret = recv(conn_fd, buf, sizeof(buf), 0); buf[ret-1] = '\0'; strcpy(passwd, buf); memset(passwd, '\0', sizeof(passwd)); flag = check_passwd(name, passwd); if (flag == 0) { send_data(conn_fd, "y\n"); sleep(1); strcat(ip_name, " 用户名:"); strcat(ip_name, name); strcpy(name, "验证成功"); sys_log(name); deal(conn_fd); } else { send_data(conn_fd, "n\n"); sleep(1); continue; } } } }
/*--------------------------------------------------------------------------- Main program start here *---------------------------------------------------------------------------*/ int main() { GPIO_InitTypeDef pa0; RCC_RTC_Configuration(); LCD_GLASS_Init(); LCD_GLASS_Configure_GPIO(); init_USART(); RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA,ENABLE); GPIO_StructInit(&pa0); pa0.GPIO_Mode = GPIO_Mode_IN; pa0.GPIO_Pin = GPIO_Pin_0; GPIO_Init(GPIOA,&pa0); while(1) { if( GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == 1 && state == 0) { count++; sprintf(DataSendToServer,"GET /cpe312/index.php?Name=TESTING_%d HTTP/1.1\r\nHost: markdang.lnw.mn\r\n\r\n",count); // Test AT startup send_data("AT\r\n"); wait_data("OK"); // Restart module send_data("AT+RST\r\n"); wait_data("ready"); display("OK RST"); // Set Station & softAP Mode send_data("AT+CWMODE_CUR=3\r\n"); wait_data("OK"); display("STA+AP"); // Set Station & softAP Mode send_data("AT+CWJAP_CUR=\"CPE312\",\"25033333\"\r\n"); wait_data("OK"); display("SET AP"); // Set TCP , Address & Port : Check data http://markdang.lnw.mn/cpe312/show_data.php send_data("AT+CIPSTART=\"TCP\",\"markdang.lnw.mn\",80\r\n"); wait_data("CONNECT"); display("SETTCP"); length = strlen(DataSendToServer); // find length of data sprintf(nbr_DataSendToServer, "AT+CIPSEND=%d\r\n", length); // Set data size // Send length of data to server send_data(nbr_DataSendToServer); wait_data(">"); display("SetLEN"); // Send data to server send_data(DataSendToServer); wait_data("SEND OK"); display("SENDOK"); // Close AP send_data("AT+CWQAP\r\n"); wait_data("OK"); display("Close"); state = 1; } else if ( GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == 0 && state == 1) { state = 0; } display("ready "); } }
int check_clients(pool *p) { int i, client_sock, cnt, totalsize; ssize_t readret; char buf[2 * MAX_HEADER]; // in case of super-long request (invalid) char header[MAX_HEADER]; // actual request header parsed out from buffer char *cur; // hold the current block of request char *temp; request *req; for (i = 0; (i <= p->maxi) && (p->nready > 0); i++) { client_sock = p->clientfd[i]; req = &p->clientreq[i]; /* if the descriptor is ready, receive it and send it back */ if ((client_sock > 0) && FD_ISSET(client_sock, &p->ready_set)) { p->nready--; readret = 0; if ((readret = recv(client_sock, buf, MAX_HEADER, 0)) >= 1) { /* If client buf has content from previous request, * combine it with the buffer received this time. This is * why we need to allocate more space for the buf. */ if (strlen(p->clibuf[i]) > 0) { temp = malloc(MAX_HEADER); strcpy(temp, buf); sprintf(buf, "%s%s", p->clibuf[i], temp); memset(p->clibuf[i], 0, MAX_HEADER); free(temp); } cnt = 0; totalsize = strlen(buf); /* At this point, we should have the complete buffer we * need, then process it. */ while (cnt < totalsize) { /* Parse out each block of the request delimited by * \r\n\r\n according to the RFC spec */ cur = strstr(buf, "\r\n\r\n"); /* Deal with incomplete request header, save it into * clibuf for the next round */ if (cur == NULL) { strcpy(p->clibuf[i], buf); break; } /* Parse out the complete header */ strncpy(header, buf, cur - buf); /* Count the bytes we have read */ cnt += cur - buf; /* Parse out Content-Length in order to decide if * there is body part attached */ temp = malloc(MAX_HEADER); strcpy(temp, header); char *rv = parse_value(temp, "Content-Length"); req->content_length = rv == NULL ? 0 : atoi(rv); /* If Content-Length exists, but no body attached, * return 500 error */ if (cnt + 4 + req->content_length > totalsize) { temp = formalize_response(500, NULL, 0); send_data(client_sock, temp, strlen(temp)); break; } /* Parse out the body section for POST use */ strncpy(req->body, cur + 4, req->content_length); strcpy(buf, cur + 4 + req->content_length); cnt += 4 + req->content_length; free(temp); /* At this point, we get everything we want, go to * process it and give the response; However, valid * request should always less than 8192 bytes. Ignore * invalid ones. */ if (strlen(header) <= MAX_HEADER && process_request(client_sock, header, req) != 0) { if (close_socket(client_sock)) return 1; FD_CLR(client_sock, &p->read_set); p->clientfd[i] = -1; } } memset(buf, 0, MAX_HEADER); } if (readret == 0) { /* receiving is done, so close the client socket */ if (close_socket(client_sock)) return 1; FD_CLR(client_sock, &p->read_set); p->clientfd[i] = -1; } } } return 0; }
/****************************************************************************** Start obsluhy klienta Inspirace (vytvoreni socketu, bind): http://beej.us/guide/bgnet/output/html/multipage/clientserver.html#datagram *******************************************************************************/ int Client::start(Opt *options, struct sockaddr_storage client_addr, int index, char *buf, int numbytes, int mtu) { // Generovani nahodneho cisla pro port, na kterem bude klient obsluhovan srand (getpid()); int port = rand() % MAX_PORT + MIN_PORT; client_port = to_string(port); service_ip = options->address_at(index); int sockfd; struct addrinfo hints, *servinfo, *p; int rv; socklen_t addr_len; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; signal(SIGINT, client_signal_reaction); // Registrace funkce pro odchyt signalu if ((rv = getaddrinfo(service_ip.c_str(), client_port.c_str(), &hints, &servinfo)) != 0) { cerr << "Error - Service " << service_ip << ", " << client_port << gai_strerror(rv) << endl; return EXIT_FAILURE; } for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { continue; } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); continue; } break; } if (p == NULL) { cerr << "Error - Service " << service_ip << ", " << client_port << " - failed to bind socket" << endl; return EXIT_FAILURE; } freeaddrinfo(servinfo); client_socket = sockfd; // Ulozim si deskr. socketu // Nastavi se vychozi timeout socketu if((set_socket_timeout(options, IMPLICIT_TIMEOUT)) == SET_FAILED) return EXIT_FAILURE; // ulozim si klientovu IP pro potreby vypisu informacnich hlasek string client_ip = inet_ntop(client_addr.ss_family, get_in_addr((struct sockaddr *)&client_addr), s, sizeof s); mtu_size = mtu; // Ulozim si MTU // Cinnost obsluhy serveru string err_msg; unsigned int data_counter = 0; // Pocitadlo dat unsigned int block_counter = 0; // Pocitadlo bloku int data_len; // Pocet odeslanych B int mode; // Mod prenosu int tryouts = 0; // Pocet pokusu o znovu navazani komunikace bool reading_data = false; // Flag cteni dat bool writing_data = false; // Flag zapisu dat int ack; // Cislo potvrzeneho bloku int type; // Typ paketu int file_status; // Info o uspesnosti operace se souborem int bytes_write; // Pocet zapsanych bajtu int block_num; // Cislo bloku int recv_status; // Pocet prijatych B pri volani funkce recvfrom() char *file_buf; // Buffer pro nacitani dat ze souboru int file_buf_size;// Velikost bufferu File *f = new File(); // Nova instance objektu pro praci se soubory while(1) {// Smycka obsluhy klienta if(writing_data == true) type = packet_type(file_buf); // buffer na heapu else type = packet_type(buf); // buffer na zasobniku switch(type) {// Podle typu paketu se provadi dana operace case RRQ: {// Zadost o cteni get_filename(buf); // ukladani jmena souboru // Zjisti se mod prenosu mode = transfer_mode(buf); if(mode == UNKNOWN_MODE) {// neznamy mod err_msg = "Unknown mode"; send_error(sockfd, client_addr, err_msg, ERROR_IL); cout << current_time() << client_ip << " Unknown mode, operation aborted" << endl; clean_sources(f, sockfd); return 1; } else if(mode == NETASCII) { cout << current_time() + client_ip + " Requested READ of " << filename << " [netascii]"<< endl; } else if(mode == OCTET) { cout << current_time() + client_ip + " Requested READ of " << filename << " [octet]"<< endl; } // Otevre se soubor pro cteni file_status = f->open(filename, options->working_path(), FILE_IN, mode_tr); if(file_status == NOT_FOUND) {// Soubor nebyl nalezen err_msg = "File not found"; send_error(sockfd, client_addr, err_msg, ERROR_NF); cout << current_time() + client_ip + " File " << filename << " not found, operation aborted" << endl; clean_sources(f, sockfd); return 1; } else if(file_status == PERM_DEN) {// Nedostatecne opravneni err_msg = "Permission denided"; send_error(sockfd, client_addr, err_msg, ERROR_AV); cout << current_time() << client_ip << " Permission denided, operation aborted" << endl; clean_sources(f, sockfd); return EXIT_FAILURE; } // Zjisti se pritomnost rozsireni if(opt_extension(buf, numbytes, options, f) == EXTENSION) {// request obsahuje options send_oack(sockfd, client_addr); reading_data = true; // Alokace bufferu pro nacitani souboru if(block_size.used == true) {// byla specifikovana velikost bloku file_buf = new char[block_size.value + 1]; file_buf_size = block_size.value + 1; if(f->get_file_size() > MAX_BLOCK_COUNT * block_size.value) {// Soubor je prilis velky na prenos pres tftp err_msg = "File is too large to send"; send_error(sockfd, client_addr, err_msg, ERROR_DF); cout << current_time() + client_ip + " File is too large to send. Operation aborted\n"; clean_sources(f, sockfd); return EXIT_FAILURE; } } else {// mezi parametry nebyla velikost bloku, uvazuje se standardni file_buf = new char[STANDARD_BLOCK + 1]; file_buf_size = STANDARD_BLOCK + 1; } } else {// bez parametru, posilani prvnich dat if(f->get_file_size() > MAX_BLOCK_COUNT * STANDARD_BLOCK) {// Soubor je prilis velky na prenos pres tftp err_msg = "File is too large to send"; send_error(sockfd, client_addr, err_msg, ERROR_IL); cout << current_time() + client_ip + " File is too large to send. Operation aborted\n"; clean_sources(f, sockfd); return 1; } // Alokace bufferu pro nacitani souboru - standardni velikost file_buf = new char[STANDARD_BLOCK + 1]; reading_data = true; cout << current_time() + client_ip + " Sending DATA\n"; // poslou se prvni data data_len = send_data(sockfd, client_addr, 1, STANDARD_BLOCK, f, file_buf); data_counter += data_len; if(data_len < STANDARD_BLOCK) {// Prvni blok je zaroven i posledni, tim konci cinnost reading_data = false; } } break; } case WRQ: {// Zadost o zapis get_filename(buf); // ulozim jmeno souboru // Zjistim mod prenosu mode = transfer_mode(buf); if(mode == UNKNOWN_MODE) {// neznamy mod err_msg = "Unknown transfer mode"; send_error(sockfd, client_addr, err_msg, ERROR_IL); break; } else if(mode == NETASCII) { cout << current_time() << client_ip << " Requested WRITE of " << filename << " [netascii]" << endl; } else if(mode == OCTET) { cout << current_time() << client_ip << " Requested WRITE of " << filename << " [octet]" << endl; } // Otevre se soubor pro zapis if(mode == OCTET) { file_status = f->open(filename, options->working_path(), FILE_OUT, OCTET); } else if(mode == NETASCII) { file_status = f->open(filename, options->working_path(), FILE_OUT, NETASCII); } if(file_status == FILE_EXISTS) {// Soubor j*z existuje err_msg = "File already exists"; send_error(sockfd, client_addr, err_msg, ERROR_AE); cout << current_time() << client_ip << " File " << filename << " already exists, operation aborted" << endl; clean_sources(f, sockfd); return 1; } else if(file_status == CANNOT_OPEN) {// Nelze otevrit err_msg = "Cannot open file for writing"; send_error(sockfd, client_addr, err_msg, ERROR_IL); cout << current_time() << client_ip << " Cannot opet file " << filename << " for writing, operation aborted" << endl; clean_sources(f, sockfd); return 1; } // Zjisti se rozsireni if(opt_extension(buf, numbytes, options, f) == EXTENSION) {// request obsahuje options send_oack(sockfd, client_addr); // Alokace bufferu pro nacitani souboru if(block_size.used == true) {// byla specifikovana velikost bloku file_buf = new char[block_size.value + 10]; file_buf_size = block_size.value + 10; } else {// mezi parametry nebyla velikost bloku, uvazuje se standardni file_buf = new char[STANDARD_BLOCK + 10]; file_buf_size = STANDARD_BLOCK + 10; } writing_data = true; cout << current_time() + client_ip + " Receiving DATA\n"; } else {// Bez rozsireni, zasle se ack 0 send_ack(sockfd, client_addr, 0); // Alokace bufferu pro zapis souboru - standardni velikost file_buf = new char[STANDARD_BLOCK + 10]; file_buf_size = STANDARD_BLOCK + 10; writing_data = true; cout << current_time() + client_ip + " Receiving DATA\n"; } break; } case DATA: {// Datovy paket od klienta if(writing_data == true) {// Probiha prenos block_num = ack_number(file_buf); // zjisti se cislo bloku if((block_counter + 1) != block_num) {// Prisel blok, ktery nenavazuje na predchozi err_msg = "Error while file transfer"; send_error(sockfd, client_addr, err_msg, ERROR_IL); break; } int actual_block; if(block_size.used == true) {// Pouziva se nestandardni velikost bloku actual_block = block_size.value; bytes_write = recv_data(file_buf, numbytes, actual_block, f); // zapisou se data } else {// Standardni velikost bloku actual_block = STANDARD_BLOCK; bytes_write = recv_data(file_buf, numbytes, actual_block, f); // zapisou se data } if(bytes_write >= 0) {// Zapis byl uspesny, potvrdi se klientovi send_ack(sockfd, client_addr, block_num); block_counter++; // zvetsi se pocitadlo ulozenych bloku data_counter += bytes_write; // pricte se pocet ulozenych dat k pocitadlu if((numbytes - 4) < actual_block) {// dat bylo min nez je velikost bloku writing_data = false; f->close_file(FILE_OUT); // uzavre se soubor pro zapis cout << current_time() << client_ip << " File " << filename << " has been stored [" << data_counter << " B, " << block_counter << " blocks]" << endl; clean_sources(f, sockfd); return EXIT_FAILURE; } } else if(bytes_write == READ_ERR) {// Zapis nebyl uspesny err_msg = "Error while writing to file"; send_error(sockfd, client_addr, err_msg, ERROR_IL); clean_sources(f, sockfd); return EXIT_FAILURE; } } break; } case ACK: {// Potvrzeni od klienta, ze obdrzel konkretni datovy paket ack = ack_number(buf); if(ack == 0) cout << current_time() + client_ip + " Sending DATA\n"; if(reading_data == true) {// prenos jeste nebyl dokoncen if(block_size.used == true) {// Pouziva se nestandardni velikost bloku data_len = send_data(sockfd, client_addr, ack + 1, block_size.value, f, file_buf); if(data_len == SEND_FAIL) {// Chyba pri odesilani cerr << current_time() << client_ip << " Error in sendto, operation aborted" << endl; clean_sources(f, sockfd); return EXIT_FAILURE; } else if(data_len < block_size.value) reading_data = false; } else {// Standardni velikost bloku data_len = send_data(sockfd, client_addr, ack + 1, STANDARD_BLOCK, f, file_buf); if(data_len == SEND_FAIL) {// Chyba pri odesilani cerr << current_time() << client_ip << " Error in sendto, operation aborted" << endl; clean_sources(f, sockfd); return EXIT_FAILURE; } else if(data_len < STANDARD_BLOCK) reading_data = false; } data_counter += data_len; } else {// Prenos byl dokoncen cout << current_time() << client_ip << " File " << filename << " has been sent [" << data_counter << " B, " << ack << " blocks]\n"; clean_sources(f, sockfd); return EXIT_SUCCESS; } break; } case ERR: {// Error paket int err; if(reading_data == true) {// Klient poslal error pri cteni dat err = recv_error(buf); switch(err) { case ERROR_UN: {// Unknown transfer ID f->close_file(FILE_IN); cout << current_time() << client_ip << " Client aborted file read (transport error)" << endl; return EXIT_FAILURE; } case ERROR_DF: {// Disk full f->close_file(FILE_IN); cout << current_time() << client_ip << " Client aborted file read (too large)" << endl; return EXIT_FAILURE; } case ERROR_ND: {// Nedefinovana chyba f->close_file(FILE_IN); cout << current_time() << client_ip << " Client aborted file read (undefined error)" << endl; return EXIT_FAILURE; } } } else if(writing_data == true) {// Klient poslal error pri zapisu dat err = recv_error(buf); switch(err) { case ERROR_UN: {// Unknown transfer ID f->close_file(FILE_OUT); cout << current_time() << client_ip << " Client aborted file write" << endl; return EXIT_FAILURE; } case ERROR_ND: {// Nedefinovana chyba f->close_file(FILE_OUT); cout << current_time() << client_ip << " Client aborted file read (undefined error)" << endl; return EXIT_FAILURE; } } } break; } case UNKNOWN_OPCODE: {// Neznamy opcode err_msg = "Unknown request"; send_error(sockfd, client_addr, err_msg, ERROR_IL); clean_sources(f, sockfd); return EXIT_FAILURE; } }// konec switch(type) if(writing_data == true) {// Pokud probiha zapis, pouziva se vetsi buffer alokovany na halde recv_status = recv_packet(sockfd, client_addr, file_buf, file_buf_size); } else {// Pri cteni staci mensi velikost na zasobniku recv_status = recv_packet(sockfd, client_addr, buf, BUFSIZE); } if(recv_status == TIMEOUT_ELAPSED) {// Vyprsel cas cekani, probehne 3x pokus o znovu navazani komunikace tryouts++; if(tryouts == 3) {// Probehly tri pokusy o znovu navazani komunikace cout << current_time() << client_ip << " Timeout elapsed, operation aborted" << endl; clean_sources(f, sockfd); return 1; } else {// Probehne pokus cout << current_time() << client_ip << " Timeout elapsed, retrying..." << endl; } } else {// Byl normalne prijat paket numbytes = recv_status; tryouts = 0; // Vynuluje se pocitadlo neuspesnych pokusu } } }
int main (int argc, const char* argv[]) { // Check if the user has not given enough parameters if (argc != 3) { printf("Invalid command. Usage: \"%s [address] [port]\"\n", argv[0]); exit(EXIT_FAILURE); } // Init structs and other variables struct addrinfo* results; int sockfd, nbytes; char buf[MAXDATASIZE]; // Try to get addrinfo, exiting on error printf("Getting address information...\n"); results = get_address_info(argv[1], argv[2]); if (!results) { fprintf(stderr, "Implement assignment 1!\n"); exit(EXIT_FAILURE); } // Get IP addresses printf("Printing IP addresses for %s...\n", argv[1]); char* addr = print_addresses(results); if (!addr) { fprintf(stderr, "Implement assignment 2!\n"); exit(EXIT_FAILURE); } printf("%s", addr); free(addr); // Bind and connect socket printf("Connecting to server...\n"); sockfd = create_and_connect(results); if (!sockfd) { fprintf(stderr, "Implement assignment 3!\n"); close(sockfd); exit(EXIT_FAILURE); } // We don't need this struct anymore freeaddrinfo(results); // Receive data printf("Receiving data...\n"); nbytes = receive_data(sockfd, buf); if (!nbytes) { fprintf(stderr, "Implement assignment 4!\n"); exit(EXIT_FAILURE); } buf[nbytes] = '\0'; printf("Received: %s\n", buf); // Send data printf("Sending data...\n"); nbytes = send_data(sockfd, buf); if (!nbytes) { fprintf(stderr, "Implement assignment 5!\n"); exit(EXIT_FAILURE); } buf[nbytes] = '\0'; printf("Sent: %s\n", buf); // Receive confirmation if ((nbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv error"); exit(EXIT_FAILURE); } buf[nbytes] = '\0'; printf("Received: %s\n", buf); // Close the socket after the sending and receiving is done close(sockfd); return 0; }
static int32_t hx8369_init(struct panel_spec *self) { send_data_t send_cmd = self->info.mcu->ops->send_cmd; send_data_t send_data = self->info.mcu->ops->send_data; /* SET password */ send_cmd(0xB9); send_data(0xFF); send_data(0x83); send_data(0x69); /* Set Power */ send_cmd(0xB1); send_data(0x9D); send_data(0x00); send_data(0x34); send_data(0x07); send_data(0x00); send_data(0x0B); send_data(0x0B); send_data(0x1A); send_data(0x22); send_data(0x3F); send_data(0x3F); send_data(0x01); send_data(0x23); send_data(0x01); send_data(0xE6); send_data(0xE6); send_data(0xE6); send_data(0xE6); send_data(0xE6); /* SET Display 480x800 */ send_cmd(0xB2); send_data(0x00); send_data(0x20); send_data(0x03); send_data(0x03); send_data(0x70); send_data(0x00); send_data(0xFF); send_data(0x00); send_data(0x00); send_data(0x00); send_data(0x00); send_data(0x03); send_data(0x03); send_data(0x00); send_data(0x01); /* SET Display 480x800 */ send_cmd(0xB4); send_data(0x00); send_data(0x18); send_data(0x80); send_data(0x06); send_data(0x02); /* OSC */ send_cmd(0xB0); send_data(0x00); send_data(0x09); /*05 42HZ 07 50HZ 0B 100% 67HZ */ /* SET VCOM */ send_cmd(0xB6); send_data(0x4A); send_data(0x4A); /* SET GIP */ send_cmd(0xD5); send_data(0x00); send_data(0x03); send_data(0x03); send_data(0x00); send_data(0x01); send_data(0x02); send_data(0x28); send_data(0x70); send_data(0x11); send_data(0x13); send_data(0x00); send_data(0x00); send_data(0x40); send_data(0x06); send_data(0x51); send_data(0x07); send_data(0x00); send_data(0x00); send_data(0x41); send_data(0x06); send_data(0x50); send_data(0x07); send_data(0x07); send_data(0x0F); send_data(0x04); send_data(0x00); /* Set Gamma */ send_cmd(0xE0); send_data(0x00); send_data(0x01); send_data(0x04); send_data(0x23); send_data(0x22); send_data(0x3F); send_data(0x13); send_data(0x39); send_data(0x06); send_data(0x0B); send_data(0x0E); send_data(0x12); send_data(0x15); send_data(0x13); send_data(0x15); send_data(0x13); send_data(0x1B); send_data(0x00); send_data(0x01); send_data(0x04); send_data(0x23); send_data(0x22); send_data(0x3F); send_data(0x13); send_data(0x39); send_data(0x06); send_data(0x0B); send_data(0x0E); send_data(0x12); send_data(0x15); send_data(0x13); send_data(0x15); send_data(0x13); send_data(0x1B); send_cmd(0x35); /* TE on*/ send_data(0x00); /* set CSEL */ send_cmd(0x3A); send_data(0x07); /* CSEL=0x06, 16bit-color CSEL=0x06, 18bit-color CSEL=0x07, 24bit-color */ /*24 bit don't need to set 2DH*/ /* Sleep Out */ send_cmd(0x11); LCD_DelayMS(120); #if 0 { /* for test the lcd */ int i; send_cmd(0x2C); //Write data for (i = 0; i < 480*800/3; i++) send_data(0xff); for (i = 0; i < 480*800/3; i++) send_data(0xff00); for (i = 0; i < 480*800/3; i++) send_data(0xff0000); } #endif /* Display On */ send_cmd(0x29); LCD_DelayMS (120); /* Write data */ send_cmd(0x2C); return 0; }
// test this synchronisation protocol by; // generating sets of keys // swapping messages // stopping when all nodes agree on the set of keys // logging packet statistics int main(int argc, char **argv) { /* Catch SIGHUP etc so that we can respond to requests to do things, eg, shut down. */ struct sigaction sig; bzero(&sig, sizeof sig); sig.sa_handler = signal_handler; sigemptyset(&sig.sa_mask); sig.sa_flags = 0; sigaction(SIGINT, &sig, NULL); // setup peer state unsigned peer_count=argc > 2 ? argc-2 : 2; // a sync state per peer struct test_peer peers[peer_count]; unsigned unique[peer_count]; unsigned common=100; if (argc>=2) common = atoi(argv[1]); unsigned i, j, total_keys=common; for (i=0;i<peer_count;i++){ snprintf(peers[i].name, 10, "Peer %u", i); peers[i].state = sync_alloc_state(&peers[i], test_peer_has, test_peer_does_not_have, test_peer_now_has); unique[i]=10; if (argc>i+2) unique[i] = atoi(argv[i+2]); total_keys+=unique[i]; } struct test_key test_keys[total_keys]; bzero(test_keys, sizeof test_keys); unsigned key_index=0; LOG("--- Adding keys ---"); { int fdRand = open("/dev/urandom",O_RDONLY); assert(fdRand!=-1); LOGF("Generating %u common key(s)", common); for (i=0; i<common; i++){ assert(read(fdRand, test_keys[key_index].key.key, KEY_LEN)==KEY_LEN); for (j=0;j<peer_count;j++) sync_add_key(peers[j].state, &test_keys[key_index].key, &test_keys[key_index]); key_index++; } for (i=0; i<peer_count; i++){ LOGF("Generating %u unique key(s) for %s", unique[i], peers[i].name); for (j=0;j<unique[i];j++){ test_keys[key_index].initial_peer = &peers[i]; assert(read(fdRand, test_keys[key_index].key.key, KEY_LEN)==KEY_LEN); sync_add_key(peers[i].state, &test_keys[key_index].key, &test_keys[key_index]); key_index++; } } close(fdRand); assert(key_index == total_keys); } // debug, dump the tree structure LOG("--- BEFORE ---"); for (i=0; i<peer_count; i++){ LOGF("%s - %d Keys known", peers[i].name, peers[i].state->key_count); //dump_tree(&peer_left.root,0); } //sync_again: LOG("--- SYNCING ---"); // send messages to discover missing keys uint8_t trees_differ = 1; // TODO quick test for no progress? while(quit==0 && (trees_differ>0 || transfer_head)){ trees_differ = 0; for (i=0;i<peer_count;i++){ // stop if this peer has sent lots of packets and not made any progress if (peers[i].state->progress>50){ LOGF("%s - Quitting after no progress for %u packets", peers[i].name, peers[i].state->progress); quit=1; break; } // transmit one message from peer i to all other peers if (send_data(peers, peer_count, i)>0) trees_differ = 1; packets_sent++; // transfer during sync! while(transfer_head && transfer_head->delay_till <= packets_sent){ struct test_transfer *transfer = transfer_head; transfer_head = transfer->next; if (!transfer_head) transfer_tail = NULL; LOGF("%s - %s, *** Faking transfer complete for %s", transfer->src->name, transfer->dest->name, alloca_sync_key(&transfer->key->key)); sync_add_key(transfer->dest->state, &transfer->key->key, transfer->key); free(transfer); } } } if (!quit){ LOG("--- SYNCING COMPLETE ---"); LOGF("Sync has identified all missing keys after %u packets", packets_sent); } for (i=0;i<peer_count;i++){ LOGF("%s - Keys %u, sent %u, sent root %u, messages %u, received %u, uninteresting %u", peers[i].name, peers[i].state->key_count, peers[i].state->sent_messages, peers[i].state->sent_root, peers[i].state->sent_record_count, peers[i].state->received_record_count, peers[i].state->received_uninteresting); struct sync_peer_state *peer_state = peers[i].state->peers; while(peer_state){ struct test_peer *peer = (struct test_peer *)peer_state->peer_context; LOGF("%s - believes that %s, needs %u key(s) & has %u key(s) we need", peers[i].name, peer->name, peer_state->send_count, peer_state->recv_count ); peer_state = peer_state->next; } } /* if (transfer_head && !quit){ LOG("--- TRANSFERS ---"); while(transfer_head){ struct test_transfer *transfer = transfer_head; transfer_head = transfer->next; if (!transfer_head) transfer_tail = NULL; LOGF("%s - %s, sending %s", transfer->src->name, transfer->dest->name, alloca_sync_key(&transfer->key->key)); sync_add_key(transfer->dest->state, &transfer->key->key, transfer->key); free(transfer); } goto sync_again; }*/ // now start telling peers that these new keys are arriving for (i=0;i<peer_count;i++) sync_free_state(peers[i].state); return quit; }
bool AmSmtpClient::send_body(const vector<string>& hdrs, const AmMail& mail) { return send_command("data") || send_data(hdrs,mail) || send_command("."); }
PROCESS_THREAD(tftpd_process, ev, data) { static struct etimer t; static tftp_header *h; static int len, block, ack; static int tries; static int fd = -1; #if WITH_EXEC static char *elf_err; #endif PROCESS_BEGIN(); etimer_set(&t, CLOCK_CONF_SECOND*3); PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_TIMER); setup_server(); #if WITH_EXEC elfloader_init(); #endif print_local_addresses(); while(1) { /* connection from client */ RECV_PACKET(h); len = 0; init_config(); if(h->op == uip_htons(TFTP_RRQ)) { connect_back(); PRINTF("< rrq for %s\n", h->filename); len += strlen(h->filename)+1; if(strcmp("octet", h->filename+len)) { send_error(EUNDEF, "only octet mode supported"); goto close_connection; } len += strlen(h->filename+len)+1; /* skip mode */ parse_opts(h->options+len, uip_datalen()-len-2); if(config.to_ack & OACK_ERROR) { send_error(EOPTNEG, ""); goto close_connection; } fd = cfs_open(h->filename, CFS_READ); if(fd<0) { send_error(ENOTFOUND, ""); goto close_connection; } block = 0; ack = 0; tries = TFTP_MAXTRIES; PRINTF("starting transfer...\n"); for(;;) { if(send_oack()) len = config.blksize; /* XXX hack to prevent loop exit*/ else len = send_data(fd, block+1); if(len<0) { send_error(EUNDEF, "read failed"); goto close_file; } RECV_PACKET_TIMEOUT(h,t); if(ev == PROCESS_EVENT_TIMER) { PRINTF("ack timed out, tries left: %d\n", tries); if(--tries<=0) goto close_file; continue; } if(h->op != uip_htons(TFTP_ACK)) { send_error(EBADOP, ""); goto close_file; } config.to_ack = 0; tries = TFTP_MAXTRIES; ack = uip_htons(h->block_nr); if(ack == block+1) block++; if(len < config.blksize && ack == block) goto done; } } else if(h->op == uip_htons(TFTP_WRQ)) { connect_back(); PRINTF("< wrq for %s\n", h->filename); len += strlen(h->filename)+1; strncpy(config.filename, h->filename, sizeof(config.filename)-1); if(strcmp("octet", h->filename+strlen(h->filename)+1)) { send_error(EUNDEF, "only octet mode supported"); goto close_connection; } len += strlen(h->filename+len)+1; /* skip mode */ parse_opts(h->options+len, uip_datalen()-len-2); if(config.to_ack & OACK_ERROR) { send_error(EOPTNEG, ""); goto close_connection; } cfs_remove(h->filename); fd = cfs_open(h->filename, CFS_WRITE); if(fd<0) { send_error(EACCESS, ""); goto close_connection; } block = 0; ack = 0; tries = TFTP_MAXTRIES; PRINTF("starting transfer...\n"); if(!send_oack()) send_ack(block); for(;;) { RECV_PACKET_TIMEOUT(h,t); if(ev == PROCESS_EVENT_TIMER) { PRINTF("data timed out, tries left: %d\n", tries); if(--tries<=0) goto close_file; len = config.blksize; /* XXX hack to prevent loop exit*/ goto resend_ack; } if(h->op != uip_htons(TFTP_DATA)) { send_error(EBADOP, ""); goto close_file; } config.to_ack = 0; tries = TFTP_MAXTRIES; ack = uip_htons(h->block_nr); if(ack != block+1) continue; /* else */ block++; len = recv_data(fd, block); if(len<0) { send_error(EUNDEF, "write failed"); goto close_file; } #if WITH_EXEC if(len < config.blksize) { if(config.exec) { if(exec_file(config.filename, &elf_err) != 0) { send_error(EUNDEF, elf_err); goto close_file; } } } #endif resend_ack: if(!send_oack()) send_ack(block); if(len < config.blksize) goto done; } } done: PRINTF("done.\n"); close_file: if(fd>=0) cfs_close(fd); fd = -1; close_connection: if(client_conn) uip_udp_remove(client_conn); client_conn = 0; PRINTF("connection closed.\n"); } PROCESS_END(); }
int send_string(int fd, char *msg) { return send_data(fd, msg, strlen(msg)); }
/** Process a complete line (without CR/LF) in buf. */ static void process_line(struct sr_dev_inst *sdi) { struct dev_context *devc; double dbl; int auxint; devc = sdi->priv; switch (devc->acq_req_pending) { case 0: /* Should not happen... */ break; case 1: /* Waiting for data reply to request */ /* Convert numbers */ switch (devc->acq_req) { case AQ_U1: case AQ_U2: case AQ_I1: case AQ_I2: if (sr_atod(devc->buf, &dbl) != SR_OK) { sr_err("Failed to convert '%s' to double, errno=%d %s", devc->buf, errno, strerror(errno)); dbl = 0.0; } break; case AQ_STATUS: if (sr_atoi(devc->buf, &auxint) != SR_OK) { sr_err("Failed to convert '%s' to int, errno=%d %s", devc->buf, errno, strerror(errno)); auxint = 0; } break; default: break; } switch (devc->acq_req) { case AQ_U1: devc->channel_status[0].output_voltage_last = dbl; break; case AQ_I1: devc->channel_status[0].output_current_last = dbl; break; case AQ_U2: devc->channel_status[1].output_voltage_last = dbl; break; case AQ_I2: devc->channel_status[1].output_current_last = dbl; break; case AQ_STATUS: /* Process status and generate data. */ if (lps_process_status(sdi, auxint) == SR_OK) { send_data(sdi); } break; default: break; } devc->acq_req_pending = 2; break; case 2: /* Waiting for OK after request */ if (strcmp(devc->buf, "OK")) { sr_err("Unexpected reply while waiting for OK: '%s'", devc->buf); } devc->acq_req_pending = 0; break; } devc->buf[0] = '\0'; devc->buflen = 0; }
int tree2elemental(InvMedTree<FMM_Mat_t> *tree, El::DistMatrix<T,El::VC,El::STAR> &Y){ int data_dof=2; int SCAL_EXP = 1; int nlocal,gsize; //local elements, start p_id, global size double *pt_array; // will hold local array int r,q,rq; //Grid sizes int nbigs; //Number of large sends (i.e. send 1 extra data point) int pstart; // p_id of nstart int rank = El::mpi::WorldRank(); //p_id int send_size; // base send size bool print = rank == -1; // Get Grid and associated params const El::Grid* g = &(Y.Grid()); r = g->Height(); q = g->Width(); MPI_Comm comm = (g->Comm()).comm; std::vector<FMMNode_t*> nlist = tree->GetNGLNodes(); int cheb_deg = InvMedTree<FMM_Mat_t>::cheb_deg; int omp_p=omp_get_max_threads(); size_t n_coeff3=(cheb_deg+1)*(cheb_deg+2)*(cheb_deg+3)/6; // Get sizes, array in petsc //VecGetSize(pt_vec,&gsize); gsize = tree->M/data_dof; nlocal = tree->m/data_dof; //VecGetLocalSize(pt_vec,&nlocal); //VecGetArray(pt_vec,&pt_array); int nstart = 0; MPI_Exscan(&nlocal,&nstart,1,MPI_INT,MPI_SUM,comm); //VecGetOwnershipRange(pt_vec,&nstart,NULL); //Find processor that nstart belongs to, number of larger sends rq = r * q; pstart = nstart % rq; //int div nbigs = nlocal % rq; send_size = nlocal/rq; if(print){ std::cout << "r: " << r << " q: " << q <<std::endl; std::cout << "nstart: " << nstart << std::endl; std::cout << "ps: " << pstart << std::endl; std::cout << "nbigs: " << nbigs << std::endl; std::cout << "send_size: " << send_size << std::endl; } // Make send_lengths std::vector<int> send_lengths(rq); std::fill(send_lengths.begin(),send_lengths.end(),send_size); if(nbigs >0){ for(int j=0;j<nbigs;j++){ send_lengths[(pstart + j) % rq] += 1; } } // Make send_disps std::vector<int> send_disps = exscan(send_lengths); std::vector<El::Complex<double>> indata(nlocal); // copy the data from an ffm tree to into a local vec of complex data for sending #pragma omp parallel for for(size_t tid=0;tid<omp_p;tid++){ size_t i_start=(nlist.size()* tid )/omp_p; size_t i_end =(nlist.size()*(tid+1))/omp_p; for(size_t i=i_start;i<i_end;i++){ pvfmm::Vector<double>& coeff_vec=nlist[i]->ChebData(); double s=std::pow(0.5,COORD_DIM*nlist[i]->Depth()*0.5*SCAL_EXP); size_t offset=i*n_coeff3; for(size_t j=0;j<n_coeff3;j++){ double real = coeff_vec[j]*s; // local indices as in the pvfmm trees double imag = coeff_vec[j+n_coeff3]*s; El::Complex<double> coeff; El::SetRealPart(coeff,real); El::SetImagPart(coeff,imag); indata[offset+j] = coeff; } } } // Make send_data std::vector<El::Complex<double>> send_data(nlocal); for(int proc=0;proc<rq;proc++){ int offset = send_disps[proc]; int base_idx = (proc - pstart + rq) % rq; for(int j=0; j<send_lengths[proc]; j++){ int idx = base_idx + (j * rq); send_data[offset + j] = indata[idx]; } } // Do all2all to get recv_lengths std::vector<int> recv_lengths(rq); MPI_Alltoall(&send_lengths[0], 1, MPI_INT, &recv_lengths[0], 1, MPI_INT,comm); // Scan to get recv_disps std::vector<int> recv_disps = exscan(recv_lengths); // Do all2allv to get data on correct processor El::Complex<double> * recv_data = Y.Buffer(); //MPI_Alltoallv(&send_data[0],&send_lengths[0],&send_disps[0],MPI_DOUBLE, \ // &recv_data[0],&recv_lengths[0],&recv_disps[0],MPI_DOUBLE,comm); El::mpi::AllToAll(&send_data[0], &send_lengths[0], &send_disps[0], recv_data,&recv_lengths[0],&recv_disps[0],comm); if(print){ std::cout << "Send data: " <<std::endl << send_data <<std::endl; std::cout << "Send lengths: " <<std::endl << send_lengths <<std::endl; std::cout << "Send disps: " <<std::endl << send_disps <<std::endl; std::cout << "Recv data: " <<std::endl << recv_data <<std::endl; std::cout << "Recv lengths: " <<std::endl << recv_lengths <<std::endl; std::cout << "Recv disps: " <<std::endl << recv_disps <<std::endl; } return 0; }
data_packet_list_t *handle_packet(data_packet_t *packet, bt_config_t* config, int sockfd, packet_tracker_t *p_tracker){ /* read a incoming packet, return a list of response packets */ packet->header.magicnum = ntohs(packet->header.magicnum); packet->header.header_len = ntohs(packet->header.header_len); packet->header.packet_len = ntohs(packet->header.packet_len); packet->header.seq_num = ntohl(packet->header.seq_num); packet->header.ack_num = ntohl(packet->header.ack_num); printf("RECV handle_packet() type == %d length = %d socket = %d\n", packet->header.packet_type,packet->header.packet_len,sockfd ); if( packet->header.packet_type == 3 ){ printf("|||| RECV packet with type = DATA seq = %d\n", packet->header.seq_num); } if(packet->header.packet_type == 4){ printf("|||| RECV packet with type = ACK ack = %d\n", packet->header.ack_num); } if(packet->header.packet_type == 0){ /* if incoming packet is a WHOHAS packet */ /* scan the packet datafiled to fetch the hashes and get the count */ int count = packet->data[0]; printf("WHOHAS %d chunks\n", count); int i; char local_has[100]; char data[1500]; memset(data, 0 ,1500); int reply_count = 0; char * chunkfile = config->has_chunk_file; if ( read_chunkfile(chunkfile, local_has) < 0 ){ printf("Can not locate local chunkfile = %s\n", chunkfile); return NULL; } int find = -1; for(i = 0;i < count; i ++){ int hash_start = 4 + 20 * i; int j; char request_chunk[20]; for(j = hash_start; j < hash_start + 20; j ++){ /* if I have the chunck locally */ request_chunk[j - hash_start] = packet->data[j]; } if( 1 == find_in_local_has(request_chunk, local_has) ){ printf("find a valid local hash [%s]\n", request_chunk); find = 1; for( j = 0;j < 20;j ++){ data[reply_count + j] = request_chunk[j]; } reply_count += 20; } } data[reply_count] = '\0'; if( find == -1){ return NULL; } else{ data_packet_list_t *ret = (data_packet_list_t *)malloc(sizeof(data_packet_list_t)); ret->packet = init_packet(1, data, reply_count); ret->next = NULL; return ret; } } else if( packet->header.packet_type == 1 ){ /* if the incoming packet is an IHAVE packet */ /* here one qustions are what if mutiple nodes declare he has the requested chunk */ data_packet_list_t *ret = NULL; int count = packet->data[0]; int i; printf("starting IHAVE, %d chunks\n", count); for(i = 0;i < count; i ++){ /* for each hash value generate a GET packet */ /* each GET packet will only contain ONE hash value*/ /* TODO(cp2): add a data structrue to record which node has this chunk */ char data[21]; memset(data, 0 , 21); int j; for(j = 0;j < 20;j ++ ){ data[j] = packet->data[4 + 20 * i + j]; } int offset = get_off_set_from_master_chunkfile(data, config); printf("IHAVE registing for chunk = %d \n", offset); /* add node selection here */ /* based on node id, find the address of this node */ bt_peer_t *node; node = config->peers; while(node != NULL){ // Don't send request to itself printf("%d \n", node->id); if(node->id == sockfd){ break; } node = node->next; } if(node == NULL){ printf("Can not locate the node exiting\n"); exit(0); } printf("In node check offset = %d node_id = %d\n", offset,sockfd); /* for this chunk if I never use this node before, use this node, otherwise return*/ chunk_owner_list_t *p; for( p = file_manager.already_used; p != NULL; p = p->next){ if( p->offset == offset ){ if( p->address->sin_family == node->addr.sin_family && p->address->sin_port == node->addr.sin_port && p->address->sin_addr.s_addr == node->addr.sin_addr.s_addr){ } } } // after decide the node that I will be talking to, init the recv list // if decide to use this node { if( offset == -1){ printf("Can not init the recv_buffer with hash = %s\n", data); continue; } printf("DEBUG init recv_buffer with offset = %d\n", offset); if ( -1 == init_recv_buffer(offset,sockfd)){ printf("Can not allocate recv_buffer\n"); continue; } chunk_owner_list_t *new_element = (chunk_owner_list_t *)malloc(sizeof(chunk_owner_list_t)); new_element->address = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in)); new_element->offset = offset; new_element->address->sin_family = node->addr.sin_family; new_element->address->sin_port = node->addr.sin_port; new_element->address->sin_addr.s_addr = node->addr.sin_addr.s_addr; if( NULL == file_manager.already_used){ file_manager.already_used = new_element; new_element->next = NULL; } else{ new_element->next = file_manager.already_used; file_manager.already_used = new_element; } printf("Generating GET packet to nodeid = %d\n", sockfd); data[20] = '\0'; if ( ret == NULL ){ ret = (data_packet_list_t *)malloc( sizeof(data_packet_list_t)); ret->packet = init_packet(2, data, 20); ret->next = NULL; } else{ data_packet_t *packet = init_packet(2, data, 20); data_packet_list_t *new_block = (data_packet_list_t *)malloc( sizeof(data_packet_list_t)); new_block->packet = packet; new_block->next = ret; ret = new_block; } memset(data, 0 , 20); /* uodate the timer for this chunk */ for(j = 0;j < file_manager.chunk_count; j ++){ if( file_manager.offset[j] == offset ){ break; } } file_manager.timer[j] = time(NULL); } return ret; } else if( packet->header.packet_type == 2 ){ /* if the incoming packet is an GET packet */ /* start transmit of the data */ char hash[21]; memcpy(hash, packet->data, 20); hash[20] = '\0'; char *data = get_data_from_hash(hash, config); int offset = get_off_set_from_master_chunkfile(hash, config); /* init the flow control machine for sending back the data */ init_datalist(sockfd, offset,data); /* and call the first send */ data_packet_list_t *ret = send_data(sockfd); return ret; } else if ( packet->header.packet_type == 3 ){ /* if the incoming packet is an DATA packet */ //int offset = packet->header.ack_num; int offset; printf("Before recv_data seq = %d\n", packet->header.seq_num); data_packet_list_t *ret = recv_data(packet, sockfd, &offset); int j; for(j = 0;j < file_manager.chunk_count; j ++){ if( file_manager.offset[j] == offset ){ break; } } file_manager.timer[j] = time(NULL); /* this datapacket may be the last packet, check if it is then write back to disk */ printf("DEBUG after recv_data()\n"); check_file_manager(config); printf("DEBUG after check_file_manager()\n"); return ret; } else if( packet->header.packet_type == 4){ /* if the incoming packet is an ACK packet */ //int offset = packet->header.seq_num; data_packet_list_t *ret = handle_ack(sockfd , packet->header.ack_num - 1, p_tracker); return ret; } else{ /* TODO(for next checkpoint) : if incoming packet is other packets*/ printf("ERROR: INVALID PACKET TYPE = %d\n", packet->header.packet_type); } return NULL; }
////////////////////////////////////////////////////////////////////////////// // Routine that processes data request // Returns the number of samples actually sent int TransferSamples( const char *rq_station, // station name const char *rq_chan, // Channel ID const char *rq_loc, // Location ID STDTIME2 rq_tBeginTime, // Start time long rq_iSamples // Number of data points to transfer ) // Returns the number of samples actually sent { int indexFirst; int indexLast; int iCount; int iSample; int iSkip; int iLoopSize; int iLine; int i,j,k; int iEmpty; int iSeek; int iRecord; int iLoopRecordSize; long myData[8192]; // A seed record can never store more than this many values long rectotal; static dcptype dcp=NULL; short dframes; short dstat; short firstframe, flip, level; long headertotal; STDTIME2 tRecStart; DELTA_T2 diffTime; double delta; double dSampleRate; int iRateMult; int iRateFactor; double dTimeCorrection; seed_header *pheader; char outline[256]; short iYear, iMonth, iDom, iDoy; LONG iJulian; char cSign; STDTIME2 rq_tEndTime; char str_record[8192]; char buf_filename[2*MAXCONFIGLINELEN+2]; static char looperrstr[MAXCONFIGLINELEN+2]; char loopDir[MAXCONFIGLINELEN+1]; char *errmsg; FILE *fp_buf; // Initialize decompression code if (dcp == NULL) { if ((dcp = init_generic_decompression()) == NULL) { fprintf(stderr, "TransferSamples: failed call to init_generic_decompression()\n"); return 0; } } // first time initialization fprintf(stderr, "TransferSamples(%s %s/%s %d,%03d,%02d:%02d:%02d %ld)\n", rq_station,rq_loc,rq_chan, rq_tBeginTime.year, rq_tBeginTime.day, rq_tBeginTime.hour, rq_tBeginTime.minute, rq_tBeginTime.second, rq_iSamples); // Get index of first record for this data request rq_tEndTime = ST_AddToTime2(rq_tBeginTime, 0, 0, 0, 1, 0); LoopRecordSize(&iLoopRecordSize); errmsg = GetRecordRange(rq_station, rq_chan, rq_loc, rq_tBeginTime, rq_tEndTime, &indexFirst, &indexLast, &iCount, &iLoopSize); if (errmsg != NULL) { fprintf(stderr, "%s\n", errmsg); return 0; } // Make sure there are data records to return if (iCount < 1) return 0; // Get name of buffer file // If blank location code, leave off leading location code in filename LoopDirectory(loopDir); if (rq_loc[0] == ' ' || rq_loc[0] == 0) { sprintf(buf_filename, "%s/%s/%s.buf", loopDir, rq_station, rq_chan); } else { sprintf(buf_filename, "%s/%s/%s_%s.buf", loopDir, rq_station, rq_loc, rq_chan); } // Open the buffer file if ((fp_buf=fopen(buf_filename, "r")) == NULL) { // Buffer file does not exist so no records to return return 0; } // Loop until we've sent rq_iSamples data points iSample = 0; i=0; iEmpty = 0; iLine = 0; while (iSample < rq_iSamples) { fprintf(stderr, "DEBUG loop on sample %d of %ld\n", iSample, rq_iSamples); iRecord = (i + indexFirst + iEmpty) % iLoopSize; iSeek = iRecord * iLoopRecordSize; // Seek to the record position fseek(fp_buf, iSeek, SEEK_SET); if (iSeek != ftell(fp_buf)) { // If seek failed, we hit end of file, set iHigh sprintf(looperrstr, "TransferSamples: Unable to seek to %d in %s", iSeek, buf_filename); fclose(fp_buf); return iSample; } // Failed to seek to required file buffer position // Read in the data if (fread(str_record, iLoopRecordSize, 1, fp_buf) != 1) { sprintf(looperrstr, "TransferSamples: Unable to read record %d in %s", iRecord, buf_filename); fclose(fp_buf); return iSample; } // Failed to read record //fprintf(stderr, "decode_SEED_micro_header\n"); // Decompress the record headertotal = decode_SEED_micro_header ( (SEED_data_record *)str_record, &firstframe, &level, &flip, &dframes); if ((dframes < 1) || (dframes >= MAXSEEDFRAMES)) { fprintf(stderr, "illegal number of data frames specified!\n"); exit(0); } if ((firstframe < 0) || (firstframe > dframes)) { fprintf(stderr, "illegal first data frame! Skipping! (firstframe=%d, dframes=%d)\n", firstframe,dframes); iEmpty++; continue; } if ((level < 1) || (level > 3)) { fprintf(stderr, "illegal compression level!\n"); exit(0); } //fprintf(stderr, "decompress_generic_record\n"); rectotal = decompress_generic_record ((generic_data_record *)str_record, myData, &dstat, dcp, firstframe, headertotal, level, flip, dframes); fprintf(stderr, "Decompressed %ld records from seed record %d\n", rectotal, i+1); // Skip any data points that are prior to start time j = 0; // normaly start at first value in record if (i == 0) { // Get sample rate pheader = (seed_header *)str_record; iRateFactor = (short)ntohs(pheader->sample_rate_factor); iRateMult = (short)ntohs(pheader->sample_rate_multiplier); // Get sample rate, See SEED Reference Manual Chp 8 // Fixed Section of Data Header for formulas dSampleRate = 0; if (iRateFactor > 0 && iRateMult > 0) dSampleRate = (double)(iRateFactor * iRateMult); if (iRateFactor > 0 && iRateMult < 0) dSampleRate = -((double)iRateFactor / (double)iRateMult); if (iRateFactor < 0 && iRateMult > 0) dSampleRate = -((double)iRateMult / (double)iRateFactor); if (iRateFactor < 0 && iRateMult < 0) dSampleRate = 1.0 / (double)(iRateFactor * iRateMult); // Parse Record Start time tRecStart.year = ntohs(pheader->yr); tRecStart.day = ntohs(pheader->jday); tRecStart.hour = (int)pheader->hr; tRecStart.minute = (int)pheader->minute; tRecStart.second = (int)pheader->seconds; tRecStart.tenth_msec = ntohs(pheader->tenth_millisec); // Get time difference diffTime = ST_DiffTimes2(rq_tBeginTime , tRecStart); delta = (double)ST_DeltaToMS2(diffTime) / 10000.0; iSkip = (int)(delta * dSampleRate); fprintf(stderr, "Skip %d samples to reach start time, delta=%.4lf rate=%.4lf\n", iSkip, delta, dSampleRate); j = iSkip; // skip this many samples to find first one after start time // Get time correction value from seed header dTimeCorrection = ntohl(pheader->tenth_msec_correction) /10000.0; // See if time correction has allready been applied if (pheader->activity_flags & 0x40) dTimeCorrection = 0; fprintf(stderr, "Initial time correction of %.6lf\n", dTimeCorrection); // Add to any offset from where we started taking samples dTimeCorrection = delta - ((double)iSkip/dSampleRate); if (dTimeCorrection < 0) { cSign = '-'; dTimeCorrection = -dTimeCorrection; } else { cSign = '+'; } // Create header line iJulian = ST_GetJulian2(rq_tBeginTime); ST_CnvJulToCal2(iJulian, &iYear, &iMonth, &iDom, &iDoy); if (rq_loc[0] == ' ' || rq_loc[0] == 0) { sprintf(outline, "%s.%s %4d/%02d/%02d %02d:%02d:%02d %c%-10.6lf SEC %5.2lf SPS UNFILTERED %ld\n", rq_station, rq_chan, iYear, iMonth, iDom, rq_tBeginTime.hour, rq_tBeginTime.minute, rq_tBeginTime.second, cSign, dTimeCorrection, dSampleRate, rq_iSamples); } else { sprintf(outline, "%s.%s-%s %4d/%02d/%02d %02d:%02d:%02d %c%-10.6lf SEC %5.2lf SPS UNFILTERED %ld\n", rq_station, rq_loc, rq_chan, iYear, iMonth, iDom, rq_tBeginTime.hour, rq_tBeginTime.minute, rq_tBeginTime.second, cSign, dTimeCorrection, dSampleRate, rq_iSamples); } send_data(outline); fprintf(stderr, "Final time correction %c%-10.6lf\n", cSign, dTimeCorrection); } // If first record in // If error caused connection to close we are done if (!client_connected) { fclose(fp_buf); return iSample; } // Send data points until record is consumed, or we have sent enough for (; j < rectotal && iSample < rq_iSamples;j++,iSample++,k++) { sprintf(outline, "%5d %ld\n", iLine, myData[j]); send_data(outline); iLine++; // If error caused connection to close we are done if (!client_connected) { fclose(fp_buf); return iSample; } } // for each sample to send from this record fprintf(stderr, "finished with record\n"); i++; } // while more samples need to be sent // Close buffer file fclose(fp_buf); return iSample; } // TransferSamples()
bool Client::interact() { printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure vector<string>::iterator it = splitted_request.begin(); string get = "get"; string post = "post"; string request = ""; string file_name = ""; if ((*it).compare(get) == 0) { ++it; string temp = (*it).c_str(); if ((*it)[0] == '/') { request += "GET "; file_name = temp; } else { request += "GET "; file_name = '/' + temp; } request += file_name + " HTTP/1.0\r\n"; if (send(sockfd, request.c_str(), strlen(request.c_str()), 0) == -1) error("send"); request = "\r\n"; if (send(sockfd, request.c_str(), strlen(request.c_str()), 0) == -1) error("send"); ////////////// char buf_req[MAXREQUESTSIZE]; char buf_rest[MAXREQUESTSIZE]; while (true) { // response line detection char received_chunk[MAXREQUESTSIZE]; memset(received_chunk, 0, MAXREQUESTSIZE); receive_data(received_chunk, MAXREQUESTSIZE); // receive request line // cout << "\treceived 1 : \"" << received_chunk << "\"" << endl; string s = received_chunk; int pos = s.find("\r\n", 0); if (pos != string::npos) { string s1, s2; s1 = s.substr(0, pos); s2 = s.substr(pos); strcpy(buf_req, s1.c_str()); strcpy(buf_rest, s2.c_str()); // cout << "\tbuf_req: \"" << buf_req << "\"" << endl; // cout << "\tbuf_rest: \"" << buf_rest << "\"" << endl; break; } else { strcat(buf_req, received_chunk); } } cout << "" << endl; cout << "###################################" << endl << buf_req; vector<string> v; FileHandler::split(buf_req, ' ', v); //Response is OK cout << v[1] << endl; if (v[1].compare("200") == 0) { char file[MAXREQUESTSIZE]; //Getting headers while (true) { string s(buf_rest); // cout << "\"" << s << "\"" << endl; int pos = s.find("\r\n\r\n", 0); if (pos != string::npos) { // we reached the end of the GET request, discard the rest string headers; headers = s.substr(0, pos); //Begining of file string temp = ""; temp = s.substr(pos + 4); strcpy(file, temp.c_str()); strcat(buf_rest, headers.c_str()); cout << s << "###################################" << endl; FileHandler::create_file_from_buf(WORKINGDIRECTORY+file_name, file, strlen(file)); break; } char received_chunk[MAXREQUESTSIZE]; memset(received_chunk, 0, MAXREQUESTSIZE); receive_data(received_chunk, MAXREQUESTSIZE); // receive the rest of the request strcat(buf_rest, received_chunk); } receive_file(WORKINGDIRECTORY+file_name); } else if (v[1].compare("404") == 0) { // file not found cout<<buf_req<<endl; } else if (v[1].compare("400") == 0) { // bad request cout<<buf_req<<endl; } } else if ((*it).compare(post) == 0) { ++it; string temp = (*it).c_str(); if ((*it)[0] == '/') { request += "POST "; file_name = temp; } else { request += "POST "; file_name = '/' + temp; } request += file_name + " HTTP/1.0\r\n"; ifstream fs; FileHandler::open_file_to_read(&fs,WORKINGDIRECTORY+file_name); int file_size = FileHandler::get_file_size(&fs); string size_str;//string which will contain the result stringstream convert; // stringstream used for the conversion convert << file_size;//add the value of Number to the characters in the stream size_str = convert.str(); // cout<<"SIZE: "<<size_str<<":::"<<file_size<<endl; request += "Content-Length: " + size_str + "\r\n"; request += "\r\n"; send_data(request.c_str()); send_file(file_size,&fs); //receive response char response[MAXREQUESTSIZE]; receive_data(response,MAXREQUESTSIZE); cout<<response<<endl; } else { cout << "client: Undefined request, please use the following formats" << endl; cout << "client:\tget <file-name> <host-name> (<port-number>)" << endl; cout << "client:\tpost <file-name> <host-name> (<port-number>)" << endl; cout << "client:\twhere <host-name> and <port-number> are optional parameters" << endl; } return true; }
/*---------------------------------------------------------------------------*/ static void recv(struct polite_conn *polite) { struct rudolph2_conn *c = (struct rudolph2_conn *)polite; struct rudolph2_hdr *hdr = packetbuf_dataptr(); /* Only accept NACKs from nodes that are farther away from the base than us. */ if(hdr->type == TYPE_NACK && hdr->hops_from_base > c->hops_from_base) { c->nacks++; PRINTF("%d.%d: Got NACK for %d:%d (%d:%d)\n", rimeaddr_node_addr.u8[RIMEADDR_SIZE-2], rimeaddr_node_addr.u8[RIMEADDR_SIZE-1], hdr->version, hdr->chunk, c->version, c->rcv_nxt); if(hdr->version == c->version) { if(hdr->chunk < c->rcv_nxt) { c->snd_nxt = hdr->chunk; send_data(c, SEND_INTERVAL); } } else if(LT(hdr->version, c->version)) { c->snd_nxt = 0; send_data(c, SEND_INTERVAL); } } else if(hdr->type == TYPE_DATA) { if(hdr->hops_from_base < c->hops_from_base) { /* Only accept data from nodes that are closer to the base than us. */ c->hops_from_base = hdr->hops_from_base + 1; if(LT(c->version, hdr->version)) { PRINTF("%d.%d: rudolph2 new version %d, chunk %d\n", rimeaddr_node_addr.u8[RIMEADDR_SIZE-2], rimeaddr_node_addr.u8[RIMEADDR_SIZE-1], hdr->version, hdr->chunk); c->version = hdr->version; c->snd_nxt = c->rcv_nxt = 0; c->flags &= ~FLAG_LAST_RECEIVED; c->flags &= ~FLAG_LAST_SENT; if(hdr->chunk != 0) { send_nack(c); } else { packetbuf_hdrreduce(sizeof(struct rudolph2_hdr)); write_data(c, 0, packetbuf_dataptr(), packetbuf_totlen()); } } else if(hdr->version == c->version) { PRINTF("%d.%d: got chunk %d snd_nxt %d rcv_nxt %d\n", rimeaddr_node_addr.u8[RIMEADDR_SIZE-2], rimeaddr_node_addr.u8[RIMEADDR_SIZE-1], hdr->chunk, c->snd_nxt, c->rcv_nxt); if(hdr->chunk == c->rcv_nxt) { int len; packetbuf_hdrreduce(sizeof(struct rudolph2_hdr)); PRINTF("%d.%d: received chunk %d len %d\n", rimeaddr_node_addr.u8[RIMEADDR_SIZE-2], rimeaddr_node_addr.u8[RIMEADDR_SIZE-1], hdr->chunk, packetbuf_totlen()); len = packetbuf_totlen(); write_data(c, hdr->chunk, packetbuf_dataptr(), packetbuf_totlen()); c->rcv_nxt++; if(len < RUDOLPH2_DATASIZE) { c->flags |= FLAG_LAST_RECEIVED; send_data(c, RESEND_INTERVAL); ctimer_set(&c->t, RESEND_INTERVAL, timed_send, c); } } else if(hdr->chunk > c->rcv_nxt) { PRINTF("%d.%d: received chunk %d > %d, sending NACK\n", rimeaddr_node_addr.u8[RIMEADDR_SIZE-2], rimeaddr_node_addr.u8[RIMEADDR_SIZE-1], hdr->chunk, c->rcv_nxt); send_nack(c); } else if(hdr->chunk < c->rcv_nxt) { /* Ignore packets with a lower chunk number */ } } } } }
void server_browse(int conn_fd, char * pathname) { int i = 0; int j = 0; char tmp[SIZE]; char string[SIZE]; char file_name[SIZE] = {"\n\n\t\t.\n\n\t\t..\n\n\t\t"}; char info[SIZE]; struct dirent * ptr; struct stat buf; DIR * dir; char lenght[SIZE]; int len; char log[SIZE]; stat(pathname, &buf); if (S_ISREG(buf.st_mode)) { send_data(conn_fd, "b\n"); my_recv(conn_fd, info, sizeof(info)); if (info[0] == 'y') { sys_log("下载单个文件"); sprintf(lenght, "%d", (int)buf.st_size); printf("%s\n", lenght); server_download(conn_fd, pathname, lenght); } } chdir(pathname); memset(string, '\0', sizeof(string)); getcwd(string, sizeof(string)); string[strlen(string)] = '/'; string[strlen(string)+1] = '\0'; strcpy(log, "浏览服务器目录:"); strcat(log, string); sys_log(log); if (strcmp(string, "/home/qiong/") == 0) { send_data(conn_fd, "n\n"); deal(conn_fd); } while (1) { if ((dir = opendir (string)) == NULL) { sys_log("打开目录失败"); printf("%s\n", string); return ; } while ((ptr = readdir(dir)) != NULL) { if (strcmp(ptr->d_name, ".") && strcmp(ptr->d_name, "..")) { strcat(file_name, ptr->d_name); strcat(file_name, "\n\n\t\t"); } } file_name[strlen(file_name)] = '\0'; len = send(conn_fd, file_name, strlen(file_name), 0); memset(info, 0, sizeof(info)); len = recv(conn_fd, info, sizeof(info), 0); info[strlen(info)] = '\0'; j = 0; for (i =0; i < len; i++) { if (info[i] == ' '|| info[i] == ',') { j = 1; break; } } if (j == 1) { sys_log("进行批量下载操作"); server_batch(conn_fd); deal(conn_fd); } if (strncmp(info, "..", 2) == 0) { sys_log("返回上层目录"); server_browse(conn_fd, ".."); } else if (info[0] == '.') { ; } else { getcwd(string, sizeof(string)); string[strlen(string)] = '/'; string[strlen(string)+1] = '\0'; strcat(string, info); string[strlen(string)] = '\0'; server_browse(conn_fd, string); } } }