int client(int argc, char* argv[]) { cxxtools::Arg<unsigned short> port(argc, argv, 'p', 1234); cxxtools::Arg<const char*> ip(argc, argv, 'i'); cxxtools::Arg<unsigned> secs(argc, argv, 't', 1); cxxtools::Arg<unsigned> bufsize(argc, argv, 't', BUFSIZE); cxxtools::Arg<unsigned> B(argc, argv, 'B', 0); cxxtools::net::TcpSocket conn(ip.getValue(), port); std::vector<char> buffer(bufsize); std::generate(&buffer[0], &buffer[bufsize], rand); std::cout << "test" << std::endl; if (B.isSet()) run_test(conn, B, &buffer[0], secs); else { for (unsigned bs=256; bs <= bufsize.getValue(); bs <<= 1) run_test(conn, bs, &buffer[0], secs); } return 0; }
int client(int argc, char* argv[]) { cxxtools::Arg<unsigned short> port(argc, argv, 'p', 1234); cxxtools::Arg<const char*> ip(argc, argv, 'i', "127.0.0.1"); cxxtools::Arg<unsigned> secs(argc, argv, 't', 1); cxxtools::Arg<unsigned> bufsize(argc, argv, 't', BUFSIZE); cxxtools::Arg<unsigned> B(argc, argv, 'B', 0); cxxtools::net::Stream conn(ip.getValue(), port); cxxtools::Dynbuffer<char> buffer(bufsize); std::generate(buffer.begin(), buffer.end(), rand); std::cout << "test" << std::endl; if (B.isSet()) run_test(conn, B, buffer.data(), secs); else { for (unsigned bs=256; bs <= bufsize.getValue(); bs <<= 1) run_test(conn, bs, buffer.data(), secs); } return 0; }
struct buffer_head *blockdirty(struct buffer_head *buffer, unsigned newdelta) { map_t *map = buffer->map; assert(buffer->state < BUFFER_STATES); buftrace("---- before: fork buffer %p ----", buffer); if (buffer_dirty(buffer)) { if (buffer_already_dirty(buffer, newdelta)) return buffer; /* Buffer can't modify already, we have to fork buffer */ buftrace("---- fork buffer %p ----", buffer); struct buffer_head *clone = new_buffer(map); if (IS_ERR(clone)) return clone; /* Create the cloned buffer */ memcpy(bufdata(clone), bufdata(buffer), bufsize(buffer)); clone->index = buffer->index; /* Replace the buffer by cloned buffer. */ remove_buffer_hash(buffer); insert_buffer_hash(clone); /* * The refcount of buffer is used for backend. So, the * backend has to free this buffer (blockput(buffer)) */ buffer = clone; } __tux3_mark_buffer_dirty(buffer, newdelta); return buffer; }
bool CHttpConnection::chunkedFileTransfer(const std::string &filename, const CHttpResponse &response) { CBTRACELN("Uebertragung in Chunks beginnt..."); /* ** Datei auf lokalem Datenträger zum Schreiben öffnen */ CFile file; if(!file.open(filename,true,true)) { m_lastError="FEHLER! Lokale Datei konnte nicht zum Schreiben geoeffnet werden!"; CBTRACELN("FEHLER! Lokale Datei konnte nicht zum Schreiben geoeffnet werden!"); return(false); } CMemory<char> buf(10000); unsigned int amount; CHugeNumber totallyRead, bufsize("10000"); /* ** Größe des ersten Chunks einlesen */ CHugeNumber length=hexToValue(m_iconn->receiveLine()); /* ** Solange eingelesene Chunk-Größe != 0 */ while(length!=0) { CBTRACELN("Chungroesse : "+length.getAsPointedNumber()+" Bytes"); do { /* ** Darauf achten, dass nicht mehr Daten empfangen ** werden als Chunk groß ist */ if(length>=bufsize) amount=m_iconn->receive(buf,10000); else amount=m_iconn->receive(buf,length.getAsUnsignedLong()); file.writeBlock(buf,amount); totallyRead+=static_cast<unsigned long>(amount); length-=static_cast<unsigned long>(amount); CBTRACE("Bisher uebertragen: "+totallyRead.getAsPointedNumber()+" Bytes\r"); if((totallyRead==0)&&(length!=0)) { m_lastError="chunkedTransfer: Übertragung abgebrochen"; CBTRACE("chunkedTransfer: Übertragung abgebrochen"); return(false); } } while(length!=0); CBTRACELN(""); /* ** CRLF hinter Chunk-Datn einlesen */ m_iconn->receiveLine(); /* ** Größe des nächsten Chunks einlesen */ length=hexToValue(m_iconn->receiveLine()); } CBTRACELN("\nErfolg!"); return(true); }
static inline void bnode_buffer_init(struct buffer_head *buffer) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct bnode *bnode = bufdata(buffer); memset(bnode, 0, bufsize(buffer)); bnode->magic = cpu_to_be16(TUX3_MAGIC_BNODE); }
struct buffer_head *new_leaf(struct btree *btree) { struct buffer_head *buffer = new_block(btree); if (!IS_ERR(buffer)) { memset(bufdata(buffer), 0, bufsize(buffer)); (btree->ops->leaf_init)(btree, bufdata(buffer)); mark_buffer_dirty_atomic(buffer); } return buffer; }
static void level_redirect_blockput(struct cursor *cursor, int level, struct buffer_head *clone) { struct buffer_head *buffer = cursor->path[level].buffer; struct index_entry *next = cursor->path[level].next; /* If this level has ->next, update ->next to the clone buffer */ if (next) next = ptr_redirect(next, bufdata(buffer), bufdata(clone)); memcpy(bufdata(clone), bufdata(buffer), bufsize(clone)); level_replace_blockput(cursor, level, clone, next); }
int bufstrcat(buffer_t *dst, char *src, int size){ assert(dst != NULL && src != NULL); while(dst->siz < dst->use + size){ bufsize(dst, 2*dst->siz); } strncat(dst->ptr, src, size); dst->use += size; dst->ptr[dst->use] = '\0'; return 0; }
int bufcat(buffer_t *dst, buffer_t *src){ assert(dst != NULL && src != NULL && dst->ptr != NULL && src->ptr != NULL); while(dst->siz < dst->use + src->use){ bufsize(dst, 2*dst->siz); } strncat(dst->ptr, src->ptr, src->use); dst->use += src->use; dst->ptr[dst->use] = '\0'; return 0; }
// desperately need ERR_PTR return here to distinguish between // ENOMEM, which should be impossible but when it happens we // need to do something reasonable, or ENOSPC which we must // just report and keep going without a fuss. static struct buffer_head *new_block(struct btree *btree) { block_t block; int err = btree->ops->balloc(btree->sb, 1, &block); if (err) return NULL; // ERR_PTR me!!! struct buffer_head *buffer = sb_getblk(vfs_sb(btree->sb), block); if (!buffer) return NULL; memset(bufdata(buffer), 0, bufsize(buffer)); mark_buffer_dirty(buffer); return buffer; }
buffer_t bufinit(buffer_t *dst, int size, char *str, int sizeStr){ if(dst == NULL){ buffer_t buf = {NULL, 0, 0}; dst = &buf; } if(sizeStr > size){ sizeStr = size; } bufsize(dst, size); bufstrcpy(dst, str, sizeStr); return *dst; }
struct buffer_head *new_leaf(struct btree *btree) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct buffer_head *buffer = new_block(btree); if (!IS_ERR(buffer)) { memset(bufdata(buffer), 0, bufsize(buffer)); (btree->ops->leaf_init)(btree, bufdata(buffer)); mark_buffer_dirty_atomic(buffer); } return buffer; }
static void level_redirect_blockput(struct cursor *cursor, int level, struct buffer_head *clone) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct buffer_head *buffer = cursor->path[level].buffer; struct index_entry *next = cursor->path[level].next; /* If this level has ->next, update ->next to the clone buffer */ if (next) next = ptr_redirect(next, bufdata(buffer), bufdata(clone)); memcpy(bufdata(clone), bufdata(buffer), bufsize(clone)); level_replace_blockput(cursor, level, clone, next); }
int main(int argc, char* argv[]) { try { log_init(); cxxtools::Arg<const char*> ip(argc, argv, 'i', "0.0.0.0"); cxxtools::Arg<unsigned short> port(argc, argv, 'p', 1234); cxxtools::Arg<unsigned> bufsize(argc, argv, 'b', 8192); cxxtools::Arg<bool> listen(argc, argv, 'l'); cxxtools::Arg<bool> read_reply(argc, argv, 'r'); if (listen) { // I'm a server // listen to a port cxxtools::net::Server server(ip.getValue(), port); // accept a connetion cxxtools::net::iostream worker(server, bufsize); // copy to stdout std::cout << worker.rdbuf(); } else { // I'm a client // connect to server cxxtools::net::iostream peer(ip, port, bufsize); // copy stdin to server peer << std::cin.rdbuf() << std::flush; if (read_reply) // copy answer to stdout std::cout << peer.rdbuf() << std::flush; } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } }
static bool ocl_integral( InputArray _src, OutputArray _sum, OutputArray _sqsum, int sdepth, int sqdepth ) { bool doubleSupport = ocl::Device::getDefault().doubleFPConfig() > 0; if ( _src.type() != CV_8UC1 || (!doubleSupport && (sdepth == CV_64F || sqdepth == CV_64F)) ) return false; static const int tileSize = 16; String build_opt = format("-D SUM_SQUARE -D sumT=%s -D sumSQT=%s -D LOCAL_SUM_SIZE=%d%s", ocl::typeToStr(sdepth), ocl::typeToStr(sqdepth), tileSize, doubleSupport ? " -D DOUBLE_SUPPORT" : ""); ocl::Kernel kcols("integral_sum_cols", ocl::imgproc::integral_sum_oclsrc, build_opt); if (kcols.empty()) return false; UMat src = _src.getUMat(); Size src_size = src.size(); Size bufsize(((src_size.height + tileSize - 1) / tileSize) * tileSize, ((src_size.width + tileSize - 1) / tileSize) * tileSize); UMat buf(bufsize, sdepth); UMat buf_sq(bufsize, sqdepth); kcols.args(ocl::KernelArg::ReadOnly(src), ocl::KernelArg::WriteOnlyNoSize(buf), ocl::KernelArg::WriteOnlyNoSize(buf_sq)); size_t gt = src.cols, lt = tileSize; if (!kcols.run(1, >, <, false)) return false; ocl::Kernel krows("integral_sum_rows", ocl::imgproc::integral_sum_oclsrc, build_opt); if (krows.empty()) return false; Size sumsize(src_size.width + 1, src_size.height + 1); _sum.create(sumsize, sdepth); UMat sum = _sum.getUMat(); _sqsum.create(sumsize, sqdepth); UMat sum_sq = _sqsum.getUMat(); krows.args(ocl::KernelArg::ReadOnlyNoSize(buf), ocl::KernelArg::ReadOnlyNoSize(buf_sq), ocl::KernelArg::WriteOnly(sum), ocl::KernelArg::WriteOnlyNoSize(sum_sq)); gt = src.rows; return krows.run(1, >, <, false); }
int AudioConnect (const char *init_string, const char *client, int *handle, int rate, int format, int *data_size, int *byte_order, const char **signature, char *cepslan_data) { static char temp[20]; audio.rate = rate; audio.buflen = bufsize(rate); audio.blocklen = audio.buflen + BLOCK_HEADER_SIZE; audio.recsock = NULL; audio.playsock = NULL; *data_size = audio.buflen; *byte_order = AUDIO_LITTLE_ENDIAN; sprintf (temp, "PCM%02d ", (rate/1000)); *signature = temp; *handle = -1; return 0; }
static wxString wxTarGroupName(int gid) { struct group *pgr; #ifdef HAVE_GETGRGID_R #if defined HAVE_SYSCONF && defined _SC_GETGR_R_SIZE_MAX long grsize = sysconf(_SC_GETGR_R_SIZE_MAX); size_t bufsize(wxMin(wxMax(1024l, grsize), 32768l)); #else size_t bufsize = 1024; #endif wxCharBuffer buf(bufsize); struct group gr; memset(&gr, 0, sizeof(gr)); if (getgrgid_r(gid, &gr, buf.data(), bufsize, &pgr) == 0 && gr.gr_name) return wxString(gr.gr_name, wxConvLibc); #else if ((pgr = getgrgid(gid)) != NULL) return wxString(pgr->gr_name, wxConvLibc); #endif return _("unknown"); }
static wxString wxTarUserName(int uid) { struct passwd *ppw; #ifdef HAVE_GETPWUID_R #if defined HAVE_SYSCONF && defined _SC_GETPW_R_SIZE_MAX long pwsize = sysconf(_SC_GETPW_R_SIZE_MAX); size_t bufsize(wxMin(wxMax(1024l, pwsize), 32768l)); #else size_t bufsize = 1024; #endif wxCharBuffer buf(bufsize); struct passwd pw; memset(&pw, 0, sizeof(pw)); if (getpwuid_r(uid, &pw, buf.data(), bufsize, &ppw) == 0 && pw.pw_name) return wxString(pw.pw_name, wxConvLibc); #else if ((ppw = getpwuid(uid)) != NULL) return wxString(ppw->pw_name, wxConvLibc); #endif return _("unknown"); }
int alloc_empty_btree(struct btree *btree) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct sb *sb = btree->sb; struct buffer_head *rootbuf = new_node(btree); if (IS_ERR(rootbuf)) goto error; struct buffer_head *leafbuf = new_leaf(btree); if (IS_ERR(leafbuf)) goto error_leafbuf; assert(!has_root(btree)); struct bnode *rootnode = bufdata(rootbuf); block_t rootblock = bufindex(rootbuf); block_t leafblock = bufindex(leafbuf); trace("root at %Lx", rootblock); trace("leaf at %Lx", leafblock); bnode_init_root(rootnode, 1, leafblock, 0, 0); log_bnode_root(sb, rootblock, 1, leafblock, 0, 0); log_balloc(sb, leafblock, 1); mark_buffer_unify_non(rootbuf); blockput(rootbuf); mark_buffer_dirty_non(leafbuf); blockput(leafbuf); btree->root = (struct root){ .block = rootblock, .depth = 1 }; tux3_mark_btree_dirty(btree); return 0; error_leafbuf: (btree->ops->bfree)(sb, bufindex(rootbuf), 1); blockput(rootbuf); rootbuf = leafbuf; error: return PTR_ERR(rootbuf); } /* FIXME: right? and this should be done by btree_chop()? */ int free_empty_btree(struct btree *btree) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct btree_ops *ops = btree->ops; if (!has_root(btree)) return 0; assert(btree->root.depth == 1); struct sb *sb = btree->sb; struct buffer_head *rootbuf = vol_bread(sb, btree->root.block); if (!rootbuf) return -EIO; assert(bnode_sniff(bufdata(rootbuf))); /* Make btree has no root */ btree->root = no_root; tux3_mark_btree_dirty(btree); struct bnode *rootnode = bufdata(rootbuf); assert(bcount(rootnode) == 1); block_t leaf = be64_to_cpu(rootnode->entries[0].block); struct buffer_head *leafbuf = vol_find_get_block(sb, leaf); if (leafbuf && !leaf_need_redirect(sb, leafbuf)) { /* * This is redirected leaf. So, in here, we can just * cancel leaf_redirect by bfree(), instead of * defered_bfree(). */ bfree(sb, leaf, 1); log_leaf_free(sb, leaf); assert(ops->leaf_can_free(btree, bufdata(leafbuf))); blockput_free(sb, leafbuf); } else { defer_bfree(&sb->defree, leaf, 1); log_bfree(sb, leaf, 1); if (leafbuf) { assert(ops->leaf_can_free(btree, bufdata(leafbuf))); blockput(leafbuf); } } if (!bnode_need_redirect(sb, rootbuf)) { /* * This is redirected bnode. So, in here, we can just * cancel bnode_redirect by bfree(), instead of * defered_bfree(). */ bfree(sb, bufindex(rootbuf), 1); log_bnode_free(sb, bufindex(rootbuf)); blockput_free_unify(sb, rootbuf); } else { defer_bfree(&sb->deunify, bufindex(rootbuf), 1); log_bfree_on_unify(sb, bufindex(rootbuf), 1); blockput(rootbuf); } return 0; } int replay_bnode_redirect(struct replay *rp, block_t oldblock, block_t newblock) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct sb *sb = rp->sb; struct buffer_head *newbuf, *oldbuf; int err = 0; newbuf = vol_getblk(sb, newblock); if (!newbuf) { err = -ENOMEM; /* FIXME: error code */ goto error; } oldbuf = vol_bread(sb, oldblock); if (!oldbuf) { err = -EIO; /* FIXME: error code */ goto error_put_newbuf; } assert(bnode_sniff(bufdata(oldbuf))); memcpy(bufdata(newbuf), bufdata(oldbuf), bufsize(newbuf)); mark_buffer_unify_atomic(newbuf); blockput(oldbuf); error_put_newbuf: blockput(newbuf); error: return err; } int replay_bnode_root(struct replay *rp, block_t root, unsigned count, block_t left, block_t right, tuxkey_t rkey) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct sb *sb = rp->sb; struct buffer_head *rootbuf; rootbuf = vol_getblk(sb, root); if (!rootbuf) return -ENOMEM; bnode_buffer_init(rootbuf); bnode_init_root(bufdata(rootbuf), count, left, right, rkey); mark_buffer_unify_atomic(rootbuf); blockput(rootbuf); return 0; } /* * Before this replay, replay should already dirty the buffer of src. * (e.g. by redirect) */ int replay_bnode_split(struct replay *rp, block_t src, unsigned pos, block_t dst) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct sb *sb = rp->sb; struct buffer_head *srcbuf, *dstbuf; int err = 0; srcbuf = vol_getblk(sb, src); if (!srcbuf) { err = -ENOMEM; /* FIXME: error code */ goto error; } dstbuf = vol_getblk(sb, dst); if (!dstbuf) { err = -ENOMEM; /* FIXME: error code */ goto error_put_srcbuf; } bnode_buffer_init(dstbuf); bnode_split(bufdata(srcbuf), pos, bufdata(dstbuf)); mark_buffer_unify_non(srcbuf); mark_buffer_unify_atomic(dstbuf); blockput(dstbuf); error_put_srcbuf: blockput(srcbuf); error: return err; } /* * Before this replay, replay should already dirty the buffer of bnodeblock. * (e.g. by redirect) */ static int replay_bnode_change(struct sb *sb, block_t bnodeblock, u64 val1, u64 val2, void (*change)(struct bnode *, u64, u64)) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct buffer_head *bnodebuf; bnodebuf = vol_getblk(sb, bnodeblock); if (!bnodebuf) return -ENOMEM; /* FIXME: error code */ struct bnode *bnode = bufdata(bnodebuf); change(bnode, val1, val2); mark_buffer_unify_non(bnodebuf); blockput(bnodebuf); return 0; } static void add_func(struct bnode *bnode, u64 child, u64 key) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct index_entry *entry = bnode_lookup(bnode, key) + 1; bnode_add_index(bnode, entry, child, key); } int replay_bnode_add(struct replay *rp, block_t parent, block_t child, tuxkey_t key) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } return replay_bnode_change(rp->sb, parent, child, key, add_func); } static void update_func(struct bnode *bnode, u64 child, u64 key) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct index_entry *entry = bnode_lookup(bnode, key); assert(be64_to_cpu(entry->key) == key); entry->block = cpu_to_be64(child); } int replay_bnode_update(struct replay *rp, block_t parent, block_t child, tuxkey_t key) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } return replay_bnode_change(rp->sb, parent, child, key, update_func); } int replay_bnode_merge(struct replay *rp, block_t src, block_t dst) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct sb *sb = rp->sb; struct buffer_head *srcbuf, *dstbuf; int err = 0, ret; srcbuf = vol_getblk(sb, src); if (!srcbuf) { err = -ENOMEM; /* FIXME: error code */ goto error; } dstbuf = vol_getblk(sb, dst); if (!dstbuf) { err = -ENOMEM; /* FIXME: error code */ goto error_put_srcbuf; } ret = bnode_merge_nodes(sb, bufdata(dstbuf), bufdata(srcbuf)); assert(ret == 1); mark_buffer_unify_non(dstbuf); mark_buffer_unify_non(srcbuf); blockput(dstbuf); error_put_srcbuf: blockput(srcbuf); error: return err; } static void del_func(struct bnode *bnode, u64 key, u64 count) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct index_entry *entry = bnode_lookup(bnode, key); assert(be64_to_cpu(entry->key) == key); bnode_remove_index(bnode, entry, count); } int replay_bnode_del(struct replay *rp, block_t bnode, tuxkey_t key, unsigned count) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } return replay_bnode_change(rp->sb, bnode, key, count, del_func); } static void adjust_func(struct bnode *bnode, u64 from, u64 to) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } struct index_entry *entry = bnode_lookup(bnode, from); assert(be64_to_cpu(entry->key) == from); entry->key = cpu_to_be64(to); } int replay_bnode_adjust(struct replay *rp, block_t bnode, tuxkey_t from, tuxkey_t to) { if(DEBUG_MODE_K==1) { printf("\t\t\t\t%25s[K] %25s %4d #in\n",__FILE__,__func__,__LINE__); } return replay_bnode_change(rp->sb, bnode, from, to, adjust_func); }
size_t capacity() const { return bufsize(); }
static inline void bnode_buffer_init(struct buffer_head *buffer) { struct bnode *bnode = bufdata(buffer); memset(bnode, 0, bufsize(buffer)); bnode->magic = cpu_to_be16(TUX3_MAGIC_BNODE); }
int main(int argc, char* argv[]) { try { log_init(); cxxtools::Arg<std::string> ip(argc, argv, 'i'); cxxtools::Arg<unsigned short> port(argc, argv, 'p', 1234); cxxtools::Arg<unsigned> bufsize(argc, argv, 'b', 8192); cxxtools::Arg<bool> listen(argc, argv, 'l'); cxxtools::Arg<bool> read_reply(argc, argv, 'r'); cxxtools::Arg<bool> ssl(argc, argv, 's'); cxxtools::Arg<std::string> cert(argc, argv, "--cert"); cxxtools::Arg<std::string> ca(argc, argv, "--CA"); if (listen) { // I'm a server // listen to a port cxxtools::net::TcpServer server(ip.getValue(), port); // accept a connetion cxxtools::net::TcpStream worker(server, bufsize); if (ssl) { if (cert.isSet()) worker.loadSslCertificateFile(cert); if (ca.isSet()) worker.setSslVerify(2, ca); worker.sslAccept(); } // copy to stdout std::cout << worker.rdbuf(); } else { // I'm a client // connect to server cxxtools::net::TcpStream peer(ip, port, bufsize); if (ssl) { if (cert.isSet()) peer.loadSslCertificateFile(cert); peer.sslConnect(); } if (argc > 1) { for (int a = 1; a < argc; ++a) { std::ifstream in(argv[a]); peer << in.rdbuf() << std::flush; } } else { // copy stdin to server peer << std::cin.rdbuf() << std::flush; } if (read_reply) // copy answer to stdout std::cout << peer.rdbuf() << std::flush; } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } }
bool CHttpConnection::normalFileTransfer(const std::string &filename, const CHttpResponse &response) { /* ** Datei auf lokalem Datenträger zum Schreiben öffnen */ CFile file; if(!file.open(filename,true,true)) { m_lastError="FEHLER! Lokale Datei konnte nicht zum Schreiben geoeffnet werden!"; CBTRACELN("FEHLER! Lokale Datei konnte nicht zum Schreiben geoeffnet werden!"); return(false); } CMemory<char> buf(10000); unsigned int amount; CHugeNumber totallyRead, bufsize("10000"); /* ** Wenn Content-Length verfügbar, dann werden abgezählte ** Daten empfangen */ if(response.isContenLengthAvailable()) { CHugeNumber length=response.getContentLength(); CBTRACELN("Abgezaehlte Daten ("+length.getAsPointedNumber()+") werden gelesen!"); do { /* ** Darauf achten, dass nicht mehr Daten empfangen ** werden sollen als benötigt werden (weil read sonst ** blockiert.) */ if(length>=bufsize) amount=m_iconn->receive(buf,10000); else amount=m_iconn->receive(buf,length.getAsUnsignedLong()); file.writeBlock(buf,amount); totallyRead+=static_cast<unsigned long>(amount); length-=static_cast<unsigned long>(amount); CBTRACE("Bisher uebertragen: "+totallyRead.getAsPointedNumber()+" Bytes\r"); /* ** Keine Daten mehr empfangen, obwohl noch nicht alle Daten ** angekommen sind? ** => Fehler! */ if((totallyRead==0)&&(length!=0)) { m_lastError="chunkedTransfer: Übertragung abgebrochen"; CBTRACE("chunkedTransfer: Übertragung abgebrochen"); return(false); } } while(length!=0); } /* ** Wenn keine Content-Length verfügbar, dann Daten ** empfangen, bis der Server die Verbindung trennt */ else { CBTRACELN("Daten lesen bis zum Ende!"); do { amount=m_iconn->receive(buf,10000); file.writeBlock(buf,amount); totallyRead+=static_cast<unsigned long>(amount); CBTRACE("Bisher uebertragen: "+totallyRead.getAsPointedNumber()+" Bytes\r"); } while(amount); } CBTRACELN("\nErfolg!"); return(true); }
static void print_results(SQLHSTMT hStmt) { static const char dashes[] = "----------------------------------------------------------------" /* each line is 64 */ "----------------------------------------------------------------" "----------------------------------------------------------------" "----------------------------------------------------------------"; struct METADATA *metadata = NULL; struct DATA *data = NULL; SQLSMALLINT ncols = 0; RETCODE erc; int c, ret; /* * Process each resultset */ do { /* free metadata, in case it was previously allocated */ free_metadata(metadata, data, ncols); metadata = NULL; data = NULL; ncols = 0; /* * Allocate memory for metadata and bound columns */ if ((erc = SQLNumResultCols(hStmt, &ncols)) != SQL_SUCCESS){ odbc_perror(hStmt, erc, "SQLNumResultCols", "failed"); exit(EXIT_FAILURE); } metadata = (struct METADATA*) calloc(ncols, sizeof(struct METADATA)); assert(metadata); data = (struct DATA*) calloc(ncols, sizeof(struct DATA)); assert(data); /* * For each column, get its name, type, and size. * Allocate a buffer to hold the data, and bind the buffer to the column. * "bind" here means to give the address of the buffer we want filled as each row is fetched. */ fprintf(options.verbose, "Metadata\n"); fprintf(options.verbose, "%-6s %-30s %-10s %-18s %-6s %-6s \n", "col", "name", "type value", "type name", "size", "varies"); fprintf(options.verbose, "%.6s %.30s %.10s %.18s %.6s %.6s \n", dashes, dashes, dashes, dashes, dashes, dashes); for (c=0; c < ncols; c++) { /* Get and print the metadata. Optional: get only what you need. */ SQLCHAR name[512]; SQLSMALLINT namelen, ndigits, fnullable; if ((erc = SQLDescribeCol(hStmt, c+1, name, sizeof(name), &namelen, &metadata[c].type, &metadata[c].size, &ndigits, &fnullable)) != SQL_SUCCESS) { odbc_perror(hStmt, erc, "SQLDescribeCol", "failed"); exit(EXIT_FAILURE); } assert(namelen < sizeof(name)); name[namelen] = '\0'; metadata[c].name = strdup((char *) name); metadata[c].width = (ndigits > metadata[c].size)? ndigits : metadata[c].size; if (is_character_data(metadata[c].type)) { SQLHDESC hDesc; SQLINTEGER buflen; metadata[c].nchars = metadata[c].size; if ((erc = SQLAllocHandle(SQL_HANDLE_DESC, hStmt, &hDesc)) != SQL_SUCCESS) { odbc_perror(hStmt, erc, "SQLAllocHandle", "failed"); exit(EXIT_FAILURE); } if ((erc = SQLGetDescField(hDesc, c+1, SQL_DESC_OCTET_LENGTH, &metadata[c].size, sizeof(metadata[c].size), &buflen)) != SQL_SUCCESS) { odbc_perror(hStmt, erc, "SQLGetDescField", "failed"); exit(EXIT_FAILURE); } if ((erc = SQLFreeHandle(SQL_HANDLE_DESC, hStmt)) != SQL_SUCCESS) { odbc_perror(hStmt, erc, "SQLFreeHandle", "failed"); exit(EXIT_FAILURE); } } fprintf(options.verbose, "%6d %30s %10d %18s %6lu %6d \n", c+1, metadata[c].name, (int)metadata[c].type, prtype(metadata[c].type), (long unsigned int) metadata[c].size, -1); #if 0 fprintf(options.verbose, "%6d %30s %30s %15s %6d %6d \n", c+1, metadata[c].name, metadata[c].source, dbprtype(metadata[c].type), metadata[c].size, dbvarylen(dbproc, c+1)); metadata[c].width = get_printable_size(metadata[c].type, metadata[c].size); if (metadata[c].width < strlen(metadata[c].name)) metadata[c].width = strlen(metadata[c].name); #endif /* * Build the column header format string, based on the column width. * This is just one solution to the question, "How wide should my columns be when I print them out?" */ ret = set_format_string(&metadata[c], (c+1 < ncols)? options.colsep : "\n"); if (ret <= 0) { fprintf(stderr, "%s:%d: asprintf(), column %d failed\n", options.appname, __LINE__, c+1); return; } /* * Bind the column to our variable. * We bind everything to strings, because we want to convert everything to strings for us. * If you're performing calculations on the data in your application, you'd bind the numeric data * to C integers and floats, etc. instead. * * It is not necessary to bind to every column returned by the query. * Data in unbound columns are simply never copied to the user's buffers and are thus * inaccesible to the application. */ data[c].buffer = calloc(1, bufsize(&metadata[c])); assert(data[c].buffer); if ((erc = SQLBindCol(hStmt, c+1, SQL_C_CHAR, (SQLPOINTER)data[c].buffer, bufsize(&metadata[c]), &data[c].len)) != SQL_SUCCESS){ odbc_perror(hStmt, erc, "SQLBindCol", "failed"); exit(EXIT_FAILURE); } } if (!options.fquiet) { /* Print the column headers to stderr to keep them separate from the data. */ for (c=0; c < ncols; c++) { fprintf(options.headers, metadata[c].format_string, metadata[c].name); } /* Underline the column headers. */ for (c=0; c < ncols; c++) { fprintf(options.headers, metadata[c].format_string, dashes); } } /* * Print the data to stdout. */ while (ncols > 0 && (erc = SQLFetch(hStmt)) != SQL_NO_DATA) { switch(erc) { case SQL_SUCCESS_WITH_INFO: print_error_message(SQL_HANDLE_STMT, hStmt); case SQL_SUCCESS: break; default: odbc_perror(hStmt, erc, "SQLFetch", "failed"); exit(EXIT_FAILURE); } for (c=0; c < ncols; c++) { char *s; switch (data[c].len) { /* handle nulls */ case SQL_NULL_DATA: /* is null */ fprintf(stdout, metadata[c].format_string, "NULL"); break; default: assert(data[c].len > 0); s = calloc(1, 1 + data[c].len); assert(s); memcpy(s, data[c].buffer, data[c].len); fprintf(stdout, metadata[c].format_string, s); free(s); break; } } } if (ncols > 0 && erc == SQL_NO_DATA) print_error_message(SQL_HANDLE_STMT, hStmt); erc = SQLMoreResults(hStmt); fprintf(options.verbose, "SQLMoreResults returned %s\n", prret(erc)); switch (erc) { case SQL_NO_DATA: print_error_message(SQL_HANDLE_STMT, hStmt); break; case SQL_SUCCESS_WITH_INFO: print_error_message(SQL_HANDLE_STMT, hStmt); case SQL_SUCCESS: continue; default: odbc_perror(hStmt, erc, "SQLMoreResults", "failed"); exit(EXIT_FAILURE); } } while (erc != SQL_NO_DATA); if (erc != SQL_NO_DATA) { assert(erc != SQL_STILL_EXECUTING); odbc_perror(hStmt, erc, "SQLMoreResults", "failed"); exit(EXIT_FAILURE); } }
/* * Read a word and advance pointer. * Also processes quoting, variable substituting, and \ escapes. */ char *getword(char **s) { unsigned int len; int f; int idx = 0; const char *t = *s; int sawesc = 0; int sawq = 0; const char *env; char envbuf[32]; if (**s == 0) return NULL; for (len = 0; ; len++) { if (sawesc && t[len]) { sawesc = 0; if (t[len] <= '7' && t[len] >= '0') { buf_wr(idx, 0); for (f = 0; f < 4 && len < bufsize() && t[len] <= '7' && t[len] >= '0'; f++) buf_wr(idx, 8 * buf_rd(idx) + t[len++] - '0'); if (buf_rd(idx) == 0) buf_wr(idx, NULL_CHARACTER); idx++; len--; continue; } switch (t[len]) { case 'r': buf_wr(idx++, '\r'); break; case 'n': buf_wr(idx++, '\n'); break; case 'b': buf_wr(idx++, '\b'); break; case 'a': buf_wr(idx++, '\a'); break; case 'f': buf_wr(idx++, '\f'); break; case 'c': buf_wr(idx++, SKIP_NEWLINE); break; default: buf_wr(idx++, t[len]); break; } sawesc = 0; continue; } if (t[len] == '\\') { sawesc = 1; continue; } if (t[len] == '"') { if (sawq == 1) { sawq = 0; len++; break; } sawq = 1; continue; } if (t[len] == '$' && t[len + 1] == '(') { for(f = len; t[f] && t[f] != ')'; f++) ; if (t[f] == ')') { strncpy(envbuf, &t[len + 2], f - len - 2); envbuf[f - len - 2] = 0; len = f; env = mygetenv(envbuf); if (env == NULL) env = ""; while (*env) buf_wr(idx++, *env++); continue; } } /* ^ prefix for control chars - jl 3.2002 */ if (sawq == 1 && t[len] == '^' && t[len + 1] != 0) { char c = toupper(t[len + 1]); if (c >= 'A' && c <= '_') { len++; buf_wr(idx++, c - 'A' + 1); continue; } } if ((!sawq && (t[len] == ' ' || t[len] == '\t')) || t[len] == 0) break; buf_wr(idx++, t[len]); } buf_wr(idx, 0); *s += len; skipspace(s); if (sawesc || sawq) syntaxerr(_("(word contains ESC or quote)")); return buf(); }
TCPStream::TCPStream(TCPSocket &server, bool throwflag, timeout_t to) : streambuf(), Socket(accept(server.getSocket(), NULL, NULL)), #ifdef OLD_IOSTREAM iostream() #else iostream((streambuf *)this) #endif ,bufsize(0) ,gbuf(NULL) ,pbuf(NULL) { tpport_t port; family = IPV4; #ifdef OLD_IOSTREAM init((streambuf *)this); #endif timeout = to; setError(throwflag); IPV4Host host = getPeer(&port); if(!server.onAccept(host, port)) { endSocket(); error(errConnectRejected); iostream::clear(ios::failbit | rdstate()); return; } segmentBuffering(server.getSegmentSize()); Socket::state = CONNECTED; } #ifdef CCXX_IPV6 TCPStream::TCPStream(TCPV6Socket &server, bool throwflag, timeout_t to) : streambuf(), Socket(accept(server.getSocket(), NULL, NULL)), #ifdef OLD_IOSTREAM iostream() #else iostream((streambuf *)this) #endif ,bufsize(0) ,gbuf(NULL) ,pbuf(NULL) { tpport_t port; family = IPV6; #ifdef OLD_IOSTREAM init((streambuf *)this); #endif timeout = to; setError(throwflag); IPV6Host host = getIPV6Peer(&port); if(!server.onAccept(host, port)) { endSocket(); error(errConnectRejected); iostream::clear(ios::failbit | rdstate()); return; } segmentBuffering(server.getSegmentSize()); Socket::state = CONNECTED; } #endif TCPStream::TCPStream(const IPV4Host &host, tpport_t port, unsigned size, bool throwflag, timeout_t to) : streambuf(), Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP), #ifdef OLD_IOSTREAM iostream(), #else iostream((streambuf *)this), #endif bufsize(0),gbuf(NULL),pbuf(NULL) { #ifdef OLD_IOSTREAM init((streambuf *)this); #endif family = IPV4; timeout = to; setError(throwflag); connect(host, port, size); } #ifdef CCXX_IPV6 TCPStream::TCPStream(const IPV6Host &host, tpport_t port, unsigned size, bool throwflag, timeout_t to) : streambuf(), Socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP), #ifdef OLD_IOSTREAM iostream(), #else iostream((streambuf *)this), #endif bufsize(0),gbuf(NULL),pbuf(NULL) { family = IPV6; #ifdef OLD_IOSTREAM init((streambuf *)this); #endif timeout = to; setError(throwflag); connect(host, port, size); } #endif TCPStream::~TCPStream() { #ifdef CCXX_EXCEPTIONS try { endStream(); } catch( ... ) { if ( ! std::uncaught_exception()) throw;}; #else endStream(); #endif } #ifdef HAVE_GETADDRINFO void TCPStream::connect(const char *target, unsigned mss) { char namebuf[128]; char *cp; struct addrinfo hint, *list = NULL, *next, *first; bool connected = false; snprintf(namebuf, sizeof(namebuf), "%s", target); cp = strrchr(namebuf, '/'); if(!cp) cp = strrchr(namebuf, ':'); if(!cp) { endStream(); connectError(); return; } *(cp++) = 0; memset(&hint, 0, sizeof(hint)); hint.ai_family = family; hint.ai_socktype = SOCK_STREAM; hint.ai_protocol = IPPROTO_TCP; if(getaddrinfo(namebuf, cp, &hint, &list) || !list) { endStream(); connectError(); return; } first = list; #ifdef TCP_MAXSEG if(mss) setsockopt(so, IPPROTO_TCP, TCP_MAXSEG, (char *)&mss, sizeof(mss)); #endif while(list) { if(!::connect(so, list->ai_addr, (socklen_t)list->ai_addrlen)) { connected = true; break; } next = list->ai_next; list = next; } freeaddrinfo(first); if(!connected) { endStream(); connectError(); return; } segmentBuffering(mss); Socket::state = CONNECTED; }