int main() { tpl_node *tn; int i; tn = tpl_map("A(i)",&i); tpl_load(tn,TPL_FILE,"test61_0.tpl"); while (tpl_unpack(tn,1) > 0) printf("i is %d\n", i); /* test load-then-load: implicit free via tpl_free_keep_map */ tpl_load(tn, TPL_FILE,"test61_1.tpl"); while (tpl_unpack(tn,1) > 0) printf("i is %d\n", i); tpl_free(tn); return(0); }
void irpc_recv_usb_open_device_with_vid_pid(struct irpc_connection_info *ci, int vendor_id, int product_id, irpc_device_handle *handle) { tpl_node *tn = NULL; irpc_func_t func = IRPC_USB_OPEN_DEVICE_WITH_VID_PID; int sock = ci->server_sock; irpc_send_func(func, sock); // Send vendor and product id to server. tn = tpl_map(IRPC_PRID_VEID_FMT, &vendor_id, &product_id); tpl_pack(tn, 0); tpl_dump(tn, TPL_FD, sock); tpl_free(tn); // Read libusb_open_device_with_vid_pid packet. tn = tpl_map(IRPC_DEV_HANDLE_FMT, handle); tpl_load(tn, TPL_FD, sock); tpl_unpack(tn, 0); tpl_free(tn); }
void irpc_send_usb_claim_interface(struct irpc_connection_info *ci) { tpl_node *tn = NULL; irpc_retval_t retval = IRPC_SUCCESS; irpc_device_handle handle; int sock = ci->client_sock; int intf; // Read irpc_device_handle and interface from client. tn = tpl_map(IRPC_DEV_HANDLE_INT_FMT, &handle, &intf); tpl_load(tn, TPL_FD, sock); tpl_unpack(tn, 0); tpl_free(tn); if (libusb_claim_interface(irpc_handle, intf) != 0) retval = IRPC_FAILURE; // Send libusb_claim_interface packet. tn = tpl_map(IRPC_INT_FMT, &retval); tpl_pack(tn, 0); tpl_dump(tn, TPL_FD, sock); tpl_free(tn); }
void irpc_send_usb_clear_halt(struct irpc_connection_info *ci) { tpl_node *tn = NULL; irpc_retval_t retval = IRPC_SUCCESS; irpc_device_handle handle; char endpoint; int sock = ci->client_sock; // Read irpc_device_handle, and endpoint to server. tn = tpl_map(IRPC_CLEAR_HALT_FMT, &handle, &endpoint); tpl_load(tn, TPL_FD, sock); tpl_unpack(tn, 0); tpl_free(tn); if (libusb_clear_halt(irpc_handle, endpoint) != 0) retval = IRPC_FAILURE; // Send libusb_clear_halt packet. tn = tpl_map(IRPC_INT_FMT, &retval); tpl_pack(tn, 0); tpl_dump(tn, TPL_FD, sock); tpl_free(tn); }
void irpc_send_usb_get_string_descriptor_ascii(struct irpc_connection_info *ci) { tpl_node *tn = NULL; int retval; irpc_device_handle handle; int length, idx; char data[IRPC_MAX_DATA]; int sock = ci->client_sock; // Read irpc_device_handle, and endpoint to server. tn = tpl_map(IRPC_STRING_DESC_FMT, &handle, &idx, &length); tpl_load(tn, TPL_FD, sock); tpl_unpack(tn, 0); tpl_free(tn); retval = libusb_get_string_descriptor_ascii(irpc_handle, idx, data, length); // Send libusb_clear_halt packet. tn = tpl_map(IRPC_STR_INT_FMT, &retval, &data, IRPC_MAX_DATA); tpl_pack(tn, 0); tpl_dump(tn, TPL_FD, sock); tpl_free(tn); }
int main(int argc, char *argv[]) { tpl_node *tn; int id; char *name; tn = tpl_map("A(is)", &id, &name); tpl_load(tn, TPL_FILE, "/tmp/test35.tpl"); while ( tpl_unpack(tn,1) > 0 ) { printf("id %d, user %s\n", id, name); free(name); } tpl_free(tn); return(0); }
int main(int argc, char *argv[]) { int i, n, a,b,l, w, p; SDL_Joystick *j; SDL_Event e; tpl_node *tn; tn = tpl_map("cccc",&R,&G,&B,&D); if (SDL_Init(SDL_INIT_EVERYTHING) == -1) { fprintf(stderr,"SDL init failed: %s\n", SDL_GetError()); return -1; } n = SDL_NumJoysticks(); if (n==0) {fprintf(stderr, "No joystick\n"); return 0;} j = SDL_JoystickOpen(0); // open the first one if (!j) {fprintf(stderr,"can't open joystick: %s\n", SDL_GetError()); return -1;} fprintf(stderr,"detecting motion. press joystick button to exit\n"); while ( (w=SDL_WaitEvent(&e)) != 0) { switch (e.type) { case SDL_JOYAXISMOTION: if ((e.jaxis.value < -3200) || (e.jaxis.value > 3200)) {// reduce tweakiness p = (int)(e.jaxis.value*100.0/JOYAXIS_MAX) + 100; switch (e.jaxis.axis) { case 0: /* left right */ R = p; break; case 1: /* up down */ G = p; break; case 2: /* twist */ B = p; break; case 3: /* throttle */ D = p; break; default: break; } assert(R>=0 && R<256); assert(G>=0 && G<256); assert(B>=0 && B<256); assert(D>=0 && D<256); tpl_pack(tn, 0); tpl_dump(tn,TPL_FD,1); } break; //case SDL_JOYBUTTONDOWN: fprintf(stderr,"button press\n"); goto done; break; case SDL_QUIT: goto done; break; } } done: tpl_free(tn); SDL_JoystickClose(j); }
/* encode a tpl (kv frame) as json. */ void *enc_worker(void *thread_id) { char buf[MAX_BUF], *key, *val; json_t *o = json_object(); int rc=-1, len, nc; tpl_node *tn; while (CF.shutdown == 0) { len = nn_recv(CF.ingress_socket_pull, buf, MAX_BUF, 0); if (len < 0) { fprintf(stderr,"nn_recv: %s\n", nn_strerror(errno)); goto done; } /* decode, then re-encode as json */ json_object_clear(o); tn = tpl_map("A(ss)",&key,&val); assert(tn); if (tpl_load(tn,TPL_MEM,buf,len) < 0) goto done; while(tpl_unpack(tn,1) > 0) { json_t *jval = json_string(val); json_object_set_new(o, key, jval); free(key); key=NULL; free(val); val=NULL; } tpl_free(tn); /* dump the json object, then newline-terminate it. */ if (CF.verbose>1) json_dumpf(o, stderr, JSON_INDENT(1)); char *dump = json_dumps(o, JSON_INDENT(0)); size_t dump_len = strlen(dump); /* give the buffer to nano, from here it goes to kaf thread */ nc = nn_send(CF.egress_socket_push, dump, dump_len, 0); free(dump); if (nc < 0) { fprintf(stderr,"nn_send: %s\n", nn_strerror(errno)); goto done; } } rc = 0; done: CF.shutdown = 1; json_decref(o); return NULL; }
/* this returns memory that caller must free */ int set_to_buf(void *set, char **buf, size_t *len) { int rc=-1; char *key, *val; tpl_node *tn = tpl_map("A(ss)",&key,&val); assert(tn); kv_t *kv = NULL; while (kv = kv_next(set,kv)) { key = kv->key; val = kv->val; tpl_pack(tn,1); } if (tpl_dump(tn,TPL_MEM,buf,len) < 0) goto done; tpl_free(tn); rc = 0; done: return rc; }
int tpl_cb(void *tpl, size_t tpllen, void*data) { int i; tpl_node *tn; tpl_hook.oops = printf; if (DEBUG) printf("obtained tpl of length %d\n", (int)tpllen); tn = tpl_map("A(i)", &i); tpl_load(tn, TPL_MEM, tpl, tpllen); num_tpls++; while (tpl_unpack(tn,1) > 0) sum_tpls += i; tpl_free(tn); /* this next line is a hack to test the callback's ability * to abort further tpl processing by returning < 0 */ if (num_tpls == 3) return -1; return 0; }
irpc_retval_t irpc_recv_usb_init(struct irpc_connection_info *ci) { tpl_node *tn = NULL; irpc_retval_t retval = IRPC_FAILURE; irpc_func_t func = IRPC_USB_INIT; int sock = ci->server_sock; irpc_send_func(func, sock); // Read usb_init packet. tn = tpl_map(IRPC_INT_FMT, &retval); tpl_load(tn, TPL_FD, sock); tpl_unpack(tn, 0); tpl_free(tn); return retval; }
void irpc_recv_usb_get_device_list(struct irpc_connection_info *ci, struct irpc_device_list *devlist) { tpl_node *tn = NULL; irpc_func_t func = IRPC_USB_GET_DEVICE_LIST; int sock = ci->server_sock; irpc_send_func(func, sock); // Read usb_get_device_list packet. tn = tpl_map(IRPC_DEVLIST_FMT, &devlist->n_devs, devlist->devs, IRPC_MAX_DEVS); tpl_load(tn, TPL_FD, sock); tpl_unpack(tn, 0); tpl_free(tn); }
int main() { tpl_node *tn; int i; tn = tpl_map("A(i)",&i); for(i=0;i<10;i++) tpl_pack(tn,1); /* test pack-then-unpack without dump/load; implicit dump/load*/ while (tpl_unpack(tn,1) > 0) printf("i is %d\n", i); /* implicit conversion back to output tpl (discards previous data in tpl */ for(i=0;i>-10;i--) tpl_pack(tn,1); /* one more implicit conversion */ while (tpl_unpack(tn,1) > 0) printf("i is %d\n", i); tpl_free(tn); return(0); }
int WriteMsg(int placeToWriteMsg, int msgType, unsigned long long sizeOfBlob, void * blob) { if (OUTPUT_ERROR) fprintf(stderr, "%d:started writing msg\n", _here()); tpl_node* tn; ProcessMsg(&tn, placeToWriteMsg, msgType, sizeOfBlob, blob); if (OUTPUT_ERROR) fprintf(stderr, "%d:Dumping to file Descriptor %d\n", _here(), placeToWriteMsg); int pthreadRet1; int pthreadRet2; pthread_mutex_t writeLock = getMutexLock(); pthreadRet1 = pthread_mutex_lock(&writeLock); int success = tpl_dump(tn, TPL_FD, placeToWriteMsg); pthreadRet2 = pthread_mutex_unlock(&writeLock); if(pthreadRet1==EXIT_FAILURE){ fprintf(stderr, "%d:Thread locked unsuccessful msg\n", _here()); }else if(pthreadRet2==EXIT_FAILURE){ fprintf(stderr, "%d:Thread unlocked unsuccessful\n", _here()); }else{ fprintf(stderr, "%d:thread locked and unlocked successful\n", _here()); } if (OUTPUT_ERROR) { if (success == 0) { fprintf(stderr, "%d:msg read on file descriptor %d\n", _here(), placeToWriteMsg); } else { fprintf(stderr, "%d:msg read on file descriptor %d FAILED\n", _here(), placeToWriteMsg); return EXIT_FAILURE; } } tpl_free(tn); if (success) { return EXIT_SUCCESS; } else { return EXIT_FAILURE; } }
int main(int argc, char **argv) { struct ftdi_context *ftdi; int f = 0; int vid = 0x403; /* USB vendor ID -- use 'lsusb' to see */ int pid = 0x6001; /* USB product ID */ tpl_node *tn; tn = tpl_map("cccc",&R,&G,&B,&D); if ((ftdi = ftdi_new()) == 0) { fprintf(stderr, "ftdi_new failed\n"); return -1; } ftdi_set_interface(ftdi, INTERFACE_ANY); f = ftdi_usb_open(ftdi, vid, pid); if (f < 0) { fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(ftdi)); fprintf(stderr, "you may need to run as root\n"); return -1; } f = ftdi_write_data(ftdi, enttec_msg, sizeof(enttec_msg)); while(tpl_load(tn, TPL_FD, 0) == 0) { tpl_unpack(tn,0); fprintf(stderr,"writing %d %d %d %d\n", R,G,B,D); enttec_msg[6] = R; enttec_msg[7] = G; enttec_msg[8] = B; enttec_msg[9] = 0; enttec_msg[10] = D; ftdi_write_data(ftdi, enttec_msg, sizeof(enttec_msg)); } ftdi_usb_close(ftdi); ftdi_free(ftdi); tpl_free(tn); return 0; }
int main() { int i; char c; tpl_node *tn; tn = tpl_map("A(i)c", &i, &c); /* pack index number 0 (char c) */ c = 'a'; tpl_pack(tn, 0); /* pack A(i) (that is, index number 1) a few times */ i = 3; tpl_pack(tn, 1); i = 4; tpl_pack(tn, 1); tpl_dump(tn, TPL_FILE, "/tmp/test78.tpl"); tpl_free(tn); return(0); }
int main(int argc, char *argv[]) { int rc = -1; void *buf=NULL; size_t sz; if (tpl_gather(TPL_GATHER_BLOCKING, STDIN_FILENO, &buf, &sz) <= 0) goto done; /* peek into the saved image to see how many samples it has in it */ uint32_t num_fxlens, *fxlens; char *fmt = tpl_peek(TPL_MEM|TPL_FXLENS, buf, sz, &num_fxlens, &fxlens); if ((!fmt) || (num_fxlens<1)) {fprintf(stderr,"invalid buffer\n"); goto done;} cfg.nsamples = fxlens[0]; free(fxlens); /* make a buffer to load the PCM data into */ /* TODO assert cfg.resolution == cfg.resolution in the image */ size_t pcmlen = cfg.resolution * cfg.nsamples; int16_t *pcm; pcm = (int16_t*)malloc(pcmlen); if (!pcm) {fprintf(stderr,"out of memory\n"); goto done;} tpl_node *tn = tpl_map("iiij#", &cfg.sample_rate, &cfg.duration, &cfg.resolution, pcm, cfg.nsamples); tpl_load(tn, TPL_MEM, buf, sz); tpl_unpack(tn,0); tpl_free(tn); if (cfg.verbose) fprintf(stderr,"read the PCM file: " "duration %u s, sample rate %u hz, resolution %u bits\n", cfg.duration, cfg.sample_rate, cfg.resolution*8); play_pcm(argc, argv, pcm, pcmlen, cfg.sample_rate, cfg.verbose); /* TODO cycle if requested, reusing buf? */ rc = 0; done: if (buf) free(buf); return rc; }
int main() { tpl_node *tn; /* some meaningless test data */ struct st s = {'z', {0.9, 0.8, 0.7, 0.6, 0.5 }}; int j; int i[ILEN] = {-1, -2, -3, -4, -5, -6, -7, -8, -9, -10}; int k[KLEN] = {100, 200, 300, 400, 500, 600, 700, 800}; char a = '&'; char b = 'x'; const char *fmt; uint32_t num_fxlens, *fxlens; tn = tpl_map("cA(i#)S(cf#)A(ci#)", &a, i, ILEN, &s, FLEN, &b, k, KLEN); tpl_pack(tn,0); tpl_pack(tn,1); for(j=0; j < ILEN; j++) i[j]--; tpl_pack(tn,1); for(j=0; j < ILEN; j++) i[j]--; tpl_pack(tn,1); tpl_pack(tn,2); b++; for(j=0; j < KLEN; j++) k[j] += 50; tpl_pack(tn,2); b++; for(j=0; j < KLEN; j++) k[j] += 50; tpl_pack(tn,2); tpl_dump(tn,TPL_FILE,filename); tpl_free(tn); /* now peek at the fxlens */ fmt = tpl_peek(TPL_FILE|TPL_FXLENS, filename, &num_fxlens, &fxlens); printf("format %s\n", fmt); printf("num_fxlens %u\n", num_fxlens); for(j=0; j<num_fxlens; j++) printf("fxlens[%u] %u\n", j, fxlens[j]); if (num_fxlens>0) free(fxlens); return(0); }
DLPSPEC_ERR_CODE dlpspec_serialize(const void* struct_p, void *pBuffer, const size_t buffer_size, BLOB_TYPES data_type) /** * Serializes a blob into @p pBuffer for the passed in struct pointer @p struct_p. * * @param[in] struct_p pointer to the struct to be serialized. * @param[out] pBuffer pointer to the buffer * @param[in] buffer_size size allocated to @p pBuffer * @param[in] data_type blob type to be serialized * * @return Error code * */ { tpl_node *tn; DLPSPEC_ERR_CODE ret_val = DLPSPEC_PASS; int tpl_err = 0; tn = map_data_to_tplnode(struct_p, data_type); if(tn != NULL) { tpl_err = tpl_pack(tn, 0); if (0 == tpl_err) { tpl_err = tpl_dump(tn, TPL_MEM|TPL_PREALLOCD, pBuffer, buffer_size); } if (0 != tpl_err) // TPL error in dumping { ret_val = ERR_DLPSPEC_TPL; } tpl_free(tn); } else { ret_val = ERR_DLPSPEC_TPL; } return ret_val; }
DLPSPEC_ERR_CODE dlpspec_get_serialize_dump_size(const void* struct_p, size_t *pBufSize, BLOB_TYPES data_type) /** * Serializes a blob into @p pBuffer for the passed in struct pointer @p struct_p. * * @param[in] struct_p pointer to the struct to be serialized. * @param[out] pBufSize size of buffer required to dump returned in this. * @param[in] data_type blob type to be serialized * * @return Error code * */ { tpl_node *tn; DLPSPEC_ERR_CODE ret_val = DLPSPEC_PASS; int tpl_err = 0; tn = map_data_to_tplnode(struct_p, data_type); if(tn != NULL) { tpl_err = tpl_pack(tn, 0); if (0 == tpl_err) { tpl_err = tpl_dump(tn, TPL_GETSIZE, pBufSize); } if (0 != tpl_err) // TPL error in dumping { ret_val = ERR_DLPSPEC_TPL; } tpl_free(tn); } else { ret_val = ERR_DLPSPEC_TPL; } return ret_val; }
static int tpl_deserialize_array(tpl_node *stn, tpl_node *rtn, int cb, char *c, char *buf) { if (cb > 1024) { fprintf(stderr, "big tpl_load %d\n", cb); if (tpl_load(rtn, TPL_MEM|TPL_EXCESS_OK, _big_buf + H_OFFSET, cb - H_OFFSET) < 0) { fprintf(stderr, "load failed\n"); tpl_free(stn); tpl_free(rtn); return 0; } } else { if (tpl_load(rtn, TPL_MEM|TPL_EXCESS_OK, _buf + H_OFFSET, sizeof(_buf) - H_OFFSET) < 0) { fprintf(stderr, "load failed\n"); tpl_free(stn); tpl_free(rtn); return 0; } } tpl_unpack(rtn, 0); int i = 0; while (tpl_unpack(rtn, 1) > 0) { buf[i] = *c; i++; } tpl_free(stn); tpl_free(rtn); if (cb > 1020) { free(_big_buf); } return i; }
int main(int argc, char *argv[]) { int sockfd, newsockfd, portno, clilen, pid; struct sockaddr_in serv_addr, cli_addr; char buf[1024]; int n = 0; #ifdef USE_TPL tpl_node *tn; struct struct_type { int x; char *string; char c; } local_struct; #endif struct timeval timeout; bzero(buf, sizeof(buf)); if (argc < 3) { fprintf(stderr,"usage: %s <server> <port>\n", argv[0]); exit(1); } portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("Error opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr(argv[1]); serv_addr.sin_port = htons(portno); timeout.tv_sec = 5; timeout.tv_usec = 0; if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) error("setsockopt failed\n"); if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0) error("setsockopt failed\n"); if (0 != connect(sockfd, (const struct sockaddr *) &serv_addr, sizeof(serv_addr))) { error("connect failed\n"); } printf(">> $helloworld*\n"); write(sockfd, "$helloworld*\n", sizeof("$helloworld*\n")); n = read(sockfd, buf, sizeof(buf)); printf("Read %d from server: %s\n", n, buf); #ifdef USE_TPL printf(">> $testbinary*\n"); write(sockfd, "$testbinary*\n", sizeof("$testbinary*\n")); n = read(sockfd, buf, sizeof(buf)); printf("Read %d from server: %s\n", n, buf); tn = tpl_map("S(isc)", &local_struct); tpl_load(tn, TPL_MEM|TPL_EXCESS_OK, buf, n); tpl_unpack(tn, 0); printf("S.i = %d, S.s = %s, S.c = %c\n", local_struct.x, local_struct.string, local_struct.c); tpl_free(tn); #endif #ifdef USE_LUA printf(">> $testlua*\n"); write(sockfd, "$testlua*\n", sizeof("$testlua*\n")); n = read(sockfd, buf, sizeof(buf)); printf("Read %d from server: %s\n", n, buf); #endif bzero(buf, sizeof(buf)); return 0; }
void make_article_index(struct env_t *_SERVER) { uint total; tpl_t *tpl; char *html; FILE *fp; int rc, i, type; uint limit[2]; sqlite3_stmt *stmt; tpl = tpl_alloc(); if (tpl_load(tpl, "./templets/blog/article_list.html") != TPL_OK) { puts("Content-type: text/html\r\n\r\n./templets/blog/article_list.html Error loading template file!"); tpl_free(tpl); return ; } //获取总数据集大小 total = dataset_count("SELECT COUNT(*) AS c FROM article"); tpl_set_field_int_global(tpl, "total", total); //分页 pager(tpl, total, conf.page.blog, 1, "/article-list-all", limit); //获取分类数据 assign_tpl_category(tpl); //加载推荐数据 assign_tpl_recommend(tpl); //加载友情链接 assign_tpl_friendlink(tpl); rc = sqlite3_prepare(db, "SELECT art.filename, art.comment_num, art.hit, art.art_id, art.title, substring(art.content, art.position) AS c, datetime(art.post_time, 'unixepoch') AS dt, cat.sortname, cat.sortdir FROM article AS art LEFT JOIN category AS cat ON cat.sortdir = art.catid ORDER BY art.art_id DESC LIMIT ?;", -1, &stmt, NULL); sqlite3_bind_int(stmt, 1, conf.page.blog); tpl_select_section(tpl, "data"); while((rc = sqlite3_step(stmt)) == SQLITE_ROW) { for(i=0; i<sqlite3_column_count(stmt); i++) { type = sqlite3_column_type(stmt, i); switch(type) { case SQLITE_INTEGER: tpl_set_field_uint(tpl, sqlite3_column_name(stmt,i), sqlite3_column_int(stmt, i)); break; case SQLITE_TEXT: tpl_set_field(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i))); break; } } tpl_append_section(tpl); } tpl_deselect_section(tpl); sqlite3_finalize(stmt); html = mspace_malloc(_SERVER->mp, tpl_length(tpl) + 1); tpl_get_content(tpl, html); //printf("Content-type: text/html\r\n\r\n%s", html); fp = fopen("./index.htm", "wb"); if(fp) { fwrite(html, sizeof(char), tpl_length(tpl), fp); fclose(fp); } chmod("./index.htm", S_IRWXU | S_IRWXG | S_IRWXO); tpl_free(tpl); mspace_free(_SERVER->mp, html); tpl = NULL; }
static void process_ac(int sock) { tpl_node *tn; struct msg_ac msg; wordexp_t flags; tn = msg_ac_node(&msg); tpl_load(tn, TPL_FD, sock); tpl_unpack(tn, 0); tpl_free(tn); struct CXUnsavedFile unsaved = { msg.filename, msg.buffer.addr, msg.buffer.sz }; change_dir(msg.filename); try_load_dotccode(&flags); str_t *partial = extract_partial(&msg); if (partial) msg.col -= partial->len; if (needs_reparsing(&flags, msg.filename)) { if (clang_tu) clang_disposeTranslationUnit(clang_tu); clang_tu = clang_parseTranslationUnit(clang_index, msg.filename, (char const * const *)flags.we_wordv, flags.we_wordc, &unsaved, 1, clang_defaultEditingTranslationUnitOptions()); if (last_filename) free(last_filename); if (last_wordexp.we_wordv) wordfree(&last_wordexp); last_filename = strdup(msg.filename); last_wordexp = flags; } // diag /* for (int i = 0, n = clang_getNumDiagnostics(clang_tu); i != n; ++i) { CXDiagnostic diag = clang_getDiagnostic(clang_tu, i); CXString string = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions()); fprintf(stderr, "%s\n", clang_getCString(string)); clang_disposeString(string); clang_disposeDiagnostic(diag); } */ CXCodeCompleteResults *results; results = clang_codeCompleteAt(clang_tu, msg.filename, msg.line, msg.col, &unsaved, 1, CXCodeComplete_IncludeMacros); free_msg_ac(&msg); // diag /* for (int i = 0, n = clang_codeCompleteGetNumDiagnostics(results); i != n; ++i) { CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i); CXString string = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions()); fprintf(stderr, "%s\n", clang_getCString(string)); clang_disposeString(string); clang_disposeDiagnostic(diag); } */ struct msg_ac_response msg_r = { (partial) ? partial->len : 0, 0, 0 }; if (results) { struct make_ac_ctx ctx; str_t *fmt; init_make_ac_ctx(&ctx); msg_r.proposals_n = filter_out_cc_results(results->Results, results->NumResults, partial, &fmt); sort_cc_results(results->Results, msg_r.proposals_n); if (msg_r.proposals_n > MAX_AC_RESULTS) msg_r.proposals_n = MAX_AC_RESULTS; msg_r.proposals = malloc(sizeof(struct ac_proposal) * msg_r.proposals_n); int cur = 0; for (int i = 0; i < msg_r.proposals_n; ++i) { int added; added = make_ac_proposal(&ctx, &msg_r.proposals[cur], &results->Results[i], fmt); if (added) cur++; } msg_r.proposals_n = cur; free_make_ac_ctx(&ctx); str_free(fmt); } if (partial) str_free(partial); clang_disposeCodeCompleteResults(results); msg_ac_response_send(&msg_r, sock); free_msg_ac_response(&msg_r); }
void panel_article_update(struct env_t *_SERVER) { tpl_t *tpl; TCLIST *arr; char *html, path[128], buf[128]; sqlite3_stmt *stmt; time_t visit; int rc, i, type, pos, len, n; const char *id, *title, *sortlevel, *content, *recommend, *keyword, *filename, *file, *post_time; if(tcmapget2(_SERVER->_POST, "Article_Update")) { file = tcmapget2(_SERVER->_COOKIE, "file"); id = tcmapget2(_SERVER->_POST, "id"); title = tcmapget2(_SERVER->_POST, "title"); content = tcmapget2(_SERVER->_POST, "content"); keyword = tcmapget2(_SERVER->_POST, "keyword"); filename = tcmapget2(_SERVER->_POST, "filename"); sortlevel = tcmapget2(_SERVER->_POST, "sortlevel"); recommend = tcmapget2(_SERVER->_POST, "recommend"); post_time = tcmapget2(_SERVER->_POST, "post_time"); pos = strpos(content, "<!-- idx -->"); pos = (pos == -1) ? strlen(content) : pos; rc = sqlite3_prepare(db, "UPDATE article SET title = ?, content = ?, catid = ?, keyword = ?, filename = ?, recommend = ?, position = ? WHERE art_id = ?;", -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, title, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 2, content, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 3, sortlevel, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 4, keyword, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 5, filename, -1, SQLITE_STATIC); sqlite3_bind_int(stmt, 6, atoi(recommend)); sqlite3_bind_int(stmt, 7, pos); sqlite3_bind_int(stmt, 8, atoi(id)); sqlite3_step(stmt); sqlite3_finalize(stmt); visit = atoi(post_time); if(file) { memset(buf, 0, sizeof(buf)); memset(path, 0, sizeof(path)); strftime(buf, sizeof(buf), "%Y/%m/%d", localtime(&visit)); //如果有上传的文件,就把上传的文件,从临时目录移动目标目录 len = snprintf(path, sizeof(path), "./attachment/%s/%llu/", buf, (long long unsigned int)id); if(!is_dir(path)) mkpath(_SERVER->mp, path, 0777); if(!strchr(file, '|')) { memset(buf, 0, sizeof(buf)); snprintf(buf, sizeof(buf), "./files/%s", file); strcat(path, file); // log_debug("panel_article_insert buf = %s\tpath = %s\r\n", buf, path); if(file_exists(buf)) rename(buf, path); } else { arr = explode("|", (char *)file); n = tclistnum(arr); for(i=0; i<n; i++) { memset(buf, 0, sizeof(buf)); filename = tclistval2(arr, i); snprintf(buf, sizeof(buf), "./files/%s", filename); path[len] = '\0'; strcat(path, filename); // log_debug("panel_article_insert explode buf = %s\tpath = %s\r\n", buf, path); if(file_exists(buf)) rename(buf, path); } tclistdel(arr); } path[len] = '\0'; //更新图片附件的 路径 rc = sqlite3_prepare(db, "UPDATE article SET content = replace(content, '/files/', ?) WHERE art_id = ?;", -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, path+1, -1, SQLITE_STATIC); sqlite3_bind_int(stmt, 2, atoi(id)); sqlite3_step(stmt); sqlite3_finalize(stmt); } #ifdef _BUILD_HTML memset(path, 0, sizeof(path)); snprintf(path, sizeof(path), "./html/article/%s/%s.htm", sortlevel, id); if(file_exists(path)) remove(path); memset(path, 0, sizeof(path)); snprintf(path, sizeof(path), "./html/list/%s", sortlevel); ftw(path, fn, 500); #endif printf("Content-type: text/html\r\n\r\n<script>alert('编辑成功!');window.location.href='/panel-article-list-%s.html';</script>", sortlevel); return ; } id = tclistval2(_SERVER->_GET, 3); if(id == NULL || !is_digit(id)) { puts("Content-type: text/html\r\n\r\n<script>alert('请您选择要更新的文章');window.location.href='/panel-article-list-all.html';</script>"); return ; } tpl = tpl_alloc(); if (tpl_load(tpl, "./templets/panel/article_update.html") != TPL_OK) { printf("Content-type: text/html\r\n\r\n./templets/panel/article_update.html Error loading template file!"); tpl_free(tpl); return ; } //加载分类的数据 rc = sqlite3_prepare(db, "SELECT sortname, sortdir FROM category", -1, &stmt, NULL); tpl_select_section(tpl, "classic"); while((rc = sqlite3_step(stmt)) == SQLITE_ROW) { for(i=0; i<sqlite3_column_count(stmt); i++) { tpl_set_field(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i))); } tpl_append_section(tpl); } tpl_deselect_section(tpl); sqlite3_finalize(stmt); //加载需要编辑的数据 rc = sqlite3_prepare(db, "SELECT * FROM article WHERE art_id = ?", -1, &stmt, NULL); sqlite3_bind_int(stmt, 1, atoi(id)); while((rc = sqlite3_step(stmt)) == SQLITE_ROW) { for(i=0; i<sqlite3_column_count(stmt); i++) { type = sqlite3_column_type(stmt, i); switch(type) { case SQLITE_INTEGER: tpl_set_field_uint_global(tpl, sqlite3_column_name(stmt,i), sqlite3_column_int(stmt, i)); break; case SQLITE_TEXT: tpl_set_field_global(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i))); break; } } } sqlite3_finalize(stmt); html = mspace_malloc(_SERVER->mp, tpl_length(tpl) + 1); tpl_get_content(tpl, html); printf("Content-type: text/html\r\n\r\n%s", html); tpl_free(tpl); mspace_free(_SERVER->mp, html); tpl = NULL; }
void *_faninany_start(void* _rec_from_ptr) { int _rec_from = (int)_rec_from_ptr; int exit = 1; //writeDebug("thread faninany started at relay"); while (exit) { struct Msg* msgStruct = (struct Msg*) malloc(sizeof(struct Msg)); int fdToReadFrom = _rec_from; tpl_node * tn; tpl_bin tb; tn = tpl_map("S(iiU)B", msgStruct, &tb); //writeDebug("MSG Mapped"); int validity = (fcntl(fdToReadFrom, F_GETFL) != -1); if (validity) { writeDebugExtraPlace("File descriptor is accessible", fdToReadFrom); } else { writeErrorExtraPlace("File descriptor is not accessible", fdToReadFrom); } //writeDebug("started trying to load msg"); int success = tpl_load(tn, TPL_FD, fdToReadFrom); //writeDebug("Finished loading"); if (success == 0) { writeDebugExtraPlace("msg read on file descriptor", fdToReadFrom); } else { writeErrorExtraPlace("msg failed to read on file descriptor", fdToReadFrom); // return EXIT_FAILURE; } tpl_unpack(tn, 0); tpl_pack(tn, 0); int fdToWrite = 99;//_get_write_fd(_write_to); //writeDebug("unpacking reading msg"); int pthreadRet1; int pthreadRet2; pthread_mutex_t writeLock = getMutexLock(); pthreadRet1 = pthread_mutex_lock(&writeLock); success = tpl_dump(tn, TPL_FD, fdToWrite); pthreadRet2 = pthread_mutex_unlock(&writeLock); if (pthreadRet1 == EXIT_FAILURE) { writeError("Thread locked unsuccessful msg"); } else if (pthreadRet2 == EXIT_FAILURE) { writeError("Thread unlocked unsuccessful"); } else { writeDebug("thread locked and unlocked successful"); } if(msgStruct->msgType == TERMINATE){ exit = 0; } //writeDebug("tpl will be freed"); tpl_free(tn); _deallocate_msg(msgStruct); //writeDebug("tpl freed"); if (success == 0) { writeDebugExtraPlace("msg written on file descriptor", fdToReadFrom); } else { writeErrorExtraPlace("msg failed to read on file descriptor", fdToReadFrom); } } }
int32_t DecodeMsg(struct Msg* messageStruct, place_t _rec_from) { int32_t fdToReadFrom = _get_read_fd(_rec_from); tpl_node * tn; tpl_bin tb; //struct MsgRead* msgStruct = (struct MsgRead*)GC_MALLOC(sizeof(struct MsgRead)); tn = tpl_map("S(iiiU)B", messageStruct, &tb); //writeDebug("MSG Mapped"); /*int32_t validity = (fcntl(fdToReadFrom, F_GETFL) != -1); if (validity) { //writeDebugExtraPlace("File descriptor is accessible", //fdToReadFrom); } else { writeErrorExtraPlace("File descriptor is not accessible", fdToReadFrom); } */ MPI_Status status; int32_t count=0; //writeDebug("started trying to load msg"); //int32_t success = tpl_load(tn, TPL_FD, fdToReadFrom); fprintf(stderr, "%d:Waiting for probe message\n", _here()); MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); fprintf(stderr, "%d:Waiting for get count message\n", _here()); MPI_Get_count(&status, MPI_BYTE, &count); fprintf(stderr, "%d:Count message is %d\n", _here(), count); //int32_t success = status -> ; void * temp = malloc(count); fprintf(stderr, "%d:Waiting for recv message\n", _here()); MPI_Recv(temp, count, MPI_BYTE, status.MPI_SOURCE, 1, MPI_COMM_WORLD, &status); fprintf(stderr, "%d:Msg received \n", _here()); tpl_load(tn, TPL_MEM|TPL_UFREE, temp, count); //writeDebug("Finished loading"); // if (success == 0) { //writeDebugExtraPlace("msg read on file descriptor", //fdToReadFrom); // } else { // writeErrorExtraPlace("msg failed to read on file descriptor", // fdToReadFrom); // return EXIT_FAILURE; // } //writeDebug("unpacking reading msg"); tpl_unpack(tn, 0); fprintf(stderr, "%d:Unpack successful\n", _here()); //writeDebug("msg unpacked succesfully"); //messageStruct->msgType = msgStruct->msgType; //messageStruct->placeFrom = msgStruct->placeFrom; //messageStruct->size = msgStruct->size; //messageStruct->placeTo = msgStruct->placeTo; messageStruct->tb.addr = tb.addr; messageStruct->tb.sz = tb.sz; // uint64_t temp2 = getMicroTime(); // int64_t temp = (temp2-(messageStruct->time)); // fprintf(stderr, "%d GOING TO %d TOTAL TIME THIS MESSAGE TOOK TIME: %lld, %llu, %llu \n", messageStruct->placeFrom, messageStruct->placeTo, temp, temp2, messageStruct->time); // writeDebugMsg(messageStruct); //fprintf(stderr, "%d:blob READ iuuubefore %s make sure msg is correct \n", _here(), (char *)tb.addr); //writeDebug("tpl will be freed"); tpl_free(tn); //free(temp); //writeDebug("tpl freed"); //if (success) { return EXIT_SUCCESS; //} else { // return EXIT_FAILURE; //} }
void irpc_send_usb_get_device_descriptor(struct irpc_connection_info *ci) { tpl_node *tn = NULL; irpc_retval_t retval = IRPC_SUCCESS; libusb_device *f = NULL; libusb_device **list = NULL; irpc_device idev; struct irpc_device_descriptor idesc; struct libusb_device_descriptor desc; int sock = ci->client_sock; bzero(&idesc, sizeof(struct irpc_device_descriptor)); // Read irpc_device from client. tn = tpl_map(IRPC_DEV_FMT, &idev); tpl_load(tn, TPL_FD, sock); tpl_unpack(tn, 0); tpl_free(tn); // Find corresponding usb_device. int i; ssize_t cnt = libusb_get_device_list(irpc_ctx, &list); for (i = 0; i < cnt; i++) { libusb_device *dev = list[i]; if (dev->session_data == idev.session_data) { f = dev; break; } } if (!f) { retval = IRPC_FAILURE; goto send; } if (libusb_get_device_descriptor(f, &desc) < 0) { retval = IRPC_FAILURE; goto send; } libusb_free_device_list(list, 1); // Success, build descriptor idesc.bLength = desc.bLength; idesc.bDescriptorType = desc.bDescriptorType; idesc.bcdUSB = desc.bcdUSB; idesc.bDeviceClass = desc.bDeviceClass; idesc.bDeviceSubClass = desc.bDeviceSubClass; idesc.bDeviceProtocol = desc.bDeviceProtocol; idesc.bMaxPacketSize0 = desc.bMaxPacketSize0; idesc.idVendor = desc.idVendor; idesc.idProduct = desc.idProduct; idesc.bcdDevice = desc.bcdDevice; idesc.iManufacturer = desc.iManufacturer; idesc.iProduct = desc.iProduct; idesc.iSerialNumber = desc.iSerialNumber; idesc.bNumConfigurations = desc.bNumConfigurations; send: // Send libusb_get_device_descriptor packet. tn = tpl_map(IRPC_DESC_FMT, &idesc, &retval); tpl_pack(tn, 0); tpl_dump(tn, TPL_FD, sock); tpl_free(tn); }
static int tpl_rpc_call(tpl_node *stn, tpl_node *rtn) { char *sbuf = NULL; size_t nread, nnread, sz = -1; tpl_pack(stn, 0); tpl_dump(stn, TPL_GETSIZE, &sz); sz += H_OFFSET; printf("sz to send %d\n", sz); if (sz < 1) { fprintf(stderr, "error dump size %d\n", sz); tpl_free(stn); return -1; } else if (sz > 1020) { printf("doing malloc\n"); sbuf = malloc(sz); memcpy(sbuf, _buf, H_OFFSET); } else { sbuf = _buf; } tpl_dump(stn, TPL_MEM|TPL_PREALLOCD, sbuf + H_OFFSET, sz); uint32_t *sz_ptr = (uint32_t *)sbuf; *sz_ptr = sz; int idx = sz, i = 0, nsend = 0; while (idx > 1) { if ((nsend = send(tcp_sock, sbuf + i, idx, 0)) < 1) { fprintf(stderr, "send failed\n"); tpl_free(stn); close(tcp_sock); return -1; } idx -= nsend; i += nsend; printf("idx %d i %d\n", idx, i); } printf("done sent %d\n", i); if ((nread = recv(tcp_sock, _buf, sizeof(_buf), 0)) < 1) { fprintf(stderr, "recv failed\n"); tpl_free(stn); close(tcp_sock); return -1; } printf("first recv %d\n", nread); uint32_t *len = (uint32_t *) _buf; int left = *len - nread; printf("len %d left %d\n", *len, left); if (left > 0) { _big_buf = malloc(*len); memcpy(_big_buf, _buf, nread); while ( left > 0) { if ((nnread = recv(tcp_sock, _buf, 1024, 0)) < 1) { fprintf(stderr, "recv large buffer failed\n"); close(tcp_sock); } memcpy(_big_buf + nread, _buf, nnread); nread += nnread; left -= nnread; //printf("left %d nread %d nnread %d\n", left, nread, nnread); } } printf("total nread %d\n", nread); if (sbuf != _buf) { free(sbuf); } return nread; }
void client_main(int argc, char **argv) { int sock; if (argc < 2) { printf("ccode client, commands:\n" " close\n" " ac <filename> <line> <col> (+ currently editted buffer as stdin)\n"); return; } if (strcmp(argv[1], "close") == 0) { sock = connect_or_die(); tpl_node *tn = msg_node_pack(MSG_CLOSE); tpl_dump(tn, TPL_FD, sock); tpl_free(tn); close(sock); } else if (strcmp(argv[1], "ac") == 0) { sock = connect_or_die(); char *end; size_t sz; struct msg_ac msg; if (argc != 5 && argc != 6) { fprintf(stderr, "Not enough arguments\n"); exit(1); } if (starts_with(argv[2], "/")) msg.filename = strdup(argv[2]); else msg.filename = prepend_cwd(argv[2]); msg.line = strtol(argv[3], &end, 10); if (*end != '\0') { fprintf(stderr, "Failed to parse an int from string: %s\n", argv[3]); exit(1); } msg.col = strtol(argv[4], &end, 10); if (*end != '\0') { fprintf(stderr, "Failed to parse an int from string: %s\n", argv[4]); exit(1); } // if there is a fifth argument, load currently editted buffer // from a file, otherwise use stdin if (argc == 6) { const char *fn = argv[5]; if (read_file(&msg.buffer.addr, &sz, fn) == -1) { fprintf(stderr, "Error! Failed to read from file: %s\n", fn); exit(1); } msg.buffer.sz = (uint32_t)sz; } else { if (read_stdin(&msg.buffer.addr, &sz) == -1) { fprintf(stderr, "Error! Failed to read from stdin\n"); exit(1); } msg.buffer.sz = (uint32_t)sz; } // send msg type tpl_node *tn = msg_node_pack(MSG_AC); tpl_dump(tn, TPL_FD, sock); tpl_free(tn); // send ac msg itself tn = msg_ac_node(&msg); tpl_pack(tn, 0); tpl_dump(tn, TPL_FD, sock); tpl_free(tn); struct msg_ac_response msg_r; msg_ac_response_recv(&msg_r, sock); printf("[%d, [", msg_r.partial); for (size_t i = 0; i < msg_r.proposals_n; ++i) { struct ac_proposal *p = &msg_r.proposals[i]; printf("{'word':'%s','abbr':'%s'}", p->word, p->abbr); if (i != msg_r.proposals_n - 1) printf(","); } printf("]]"); free_msg_ac_response(&msg_r); close(sock); } else { printf("ccode client, commands:\n" " close\n" " ac <filename> <line> <col> (+ currently editted buffer as stdin)\n"); } }