static int process_pop_client(struct pop_info *pop, char *data, int len) { struct buf *line, buf; int i; buf_init(&buf, data, len); while ((i = buf_index(&buf, "\r\n", 2)) >= 0) { line = buf_tok(&buf, NULL, i + 2); line->base[line->end] = '\0'; if (strncasecmp(buf_ptr(line), "RETR ", 5) == 0) { pop->state = POP_RETR; } else pop->state = POP_NONE; } return (len - buf_len(&buf)); }
static ssize_t smtp_parse(connection_t *c, int *code, char **reply) { char digits[4] = { 0, 0, 0, 0 }, *str; smtp_state_t fsm; int i, multi; unsigned char *p; size_t len; len = buf_len(c->buf); p = buf_peek(c->buf, 0, len); *code = -1; *reply = NULL; for(i = multi = fsm = 0; i < len && fsm != SMTP_DONE; i++) { if(fsm <= SMTP_DIGIT_3 && (*p < '0' || *p > '9')) return -1; else if(fsm == SMTP_MULTI && *p != ' ' && *p != '-') return -1; else switch(fsm++) { case SMTP_DIGIT_1: digits[0] = *p++; break; case SMTP_DIGIT_2: digits[1] = *p++; break; case SMTP_DIGIT_3: digits[2] = *p++; break; case SMTP_MULTI: multi = (*p++ == '-'); break; case SMTP_TEXT: if(*p++ != '\n') { fsm--; break; } /* fall through if newline */ case SMTP_CRLF: fsm++; if(multi) fsm = SMTP_DIGIT_1; /* fall through if not multiline reply */ case SMTP_DONE: break; } } if(fsm != SMTP_DONE) return 0; if(code) *code = atoi(digits); p = buf_read_next(c->buf, i, NULL); str = calloc(1, i + 1); if((*reply = str) != NULL) while(i--) { if(p[i] == '\r' || p[i] == '\n') str[i] = ' '; else str[i] = p[i]; } buf_read_done(c->buf); return 1; }
inline int buf_get(RingBuffer *buf, uint8_t *out, int maxlen) { int len = min(buf_len(buf), maxlen); int chunk, rlen; rlen = len; while (rlen) { chunk = buf->tail - buf->head; if(chunk < 0) chunk = buf->size - buf->head; memcpy(out, buf->data + buf->head, chunk); out += chunk; rlen -= chunk; buf->head += chunk; if(buf->head == buf->size) buf->head = 0; } return len; }
void buf_appendf(Buf *buf, const char *format, ...) { assert(buf->list.length); va_list ap, ap2; va_start(ap, format); va_copy(ap2, ap); int len1 = vsnprintf(nullptr, 0, format, ap); assert(len1 >= 0); size_t required_size = len1 + 1; size_t orig_len = buf_len(buf); buf_resize(buf, orig_len + len1); int len2 = vsnprintf(buf_ptr(buf) + orig_len, required_size, format, ap2); assert(len2 == len1); va_end(ap2); va_end(ap); }
ErrorMsg *err_msg_create_with_line(Buf *path, int line, int column, Buf *source, ZigList<int> *line_offsets, Buf *msg) { ErrorMsg *err_msg = allocate<ErrorMsg>(1); err_msg->path = path; err_msg->line_start = line; err_msg->column_start = column; err_msg->msg = msg; int line_start_offset = line_offsets->at(line); int end_line = line + 1; int line_end_offset = (end_line >= line_offsets->length) ? buf_len(source) : line_offsets->at(line + 1); int len = line_end_offset - line_start_offset - 1; if (len < 0) { len = 0; } buf_init_from_mem(&err_msg->line_buf, buf_ptr(source) + line_start_offset, len); return err_msg; }
void STDCALL gesave_head( uint type, pubyte name, uint flag ) { uint ok = 0; pubyte cur; gesaveoff = buf_len( gesave ); flag &= 0xFFFFFF; if ( name && name[0] ) flag |= GHCOM_NAME; else flag &= ~GHCOM_NAME; if ( flag & GHCOM_NAME && _compile->flag & CMPL_OPTIMIZE && _compile->popti->flag & OPTI_NAME ) { cur = _compile->popti->nameson; while ( *cur ) { if ( ptr_wildcardignore( name, cur )) { ok = 1; break; } cur += mem_len( cur ) + 1; } if ( !ok ) flag &= ~GHCOM_NAME; } flag |= GHCOM_PACK; gesave_addubyte( type ); gesave_adduint( flag ); // The size will be inserted in gesave_finish // Now add just one byte gesave_addubyte( 0 ); if ( flag & GHCOM_NAME ) gesave_addptr( name ); }
uint STDCALL buf2file( pstr name, pbuf out ) { str filename; uint handle; str_init( &filename ); os_filefullname( name, &filename ); handle = os_fileopen( &filename, FOP_CREATE ); if ( !handle ) msg( MFileopen | MSG_STR | MSG_EXIT, &filename ); if ( !os_filewrite( handle, buf_ptr( out ), buf_len( out ) )) msg( MFileread | MSG_STR | MSG_EXIT, &filename ); os_fileclose( handle ); str_copy( name, &filename ); str_delete( &filename ); return 1; }
void STDCALL gesave_head( pvmEngine pThis, uint type, pubyte name, uint flag ) { pThis->gesaveoff = buf_len( pThis, pThis->gesave ); flag &= 0xFFFFFF; if ( name && name[0] ) flag |= GHCOM_NAME; else flag &= ~GHCOM_NAME; flag |= GHCOM_PACK; gesave_addubyte( pThis, type ); gesave_adduint( pThis, flag ); // The size will be inserted in gesave_finish // Now add just one byte gesave_addubyte( pThis, 0 ); if ( flag & GHCOM_NAME ) gesave_addptr( pThis, name ); }
int decode_ftp(u_char *buf, int len, u_char *obuf, int olen) { struct buf *line, inbuf, outbuf; int i, n; if ((len = strip_telopts(buf, len)) == 0) return (0); buf_init(&inbuf, buf, len); buf_init(&outbuf, obuf, olen); if (!buf_isascii(&inbuf)) return (0); n = 0; while ((i = buf_index(&inbuf, "\n", 1)) != -1) { line = buf_tok(&inbuf, NULL, i); buf_skip(&inbuf, 1); if (i > 0 && line->base[i - 1] == '\r') line->end--; line->base[line->end] = '\0'; if (strncasecmp(buf_ptr(line), "USER ", 5) == 0 || strncasecmp(buf_ptr(line), "ACCT ", 5) == 0 || strncasecmp(buf_ptr(line), "PASS ", 5) == 0) { buf_putf(&outbuf, "%s\n", buf_ptr(line)); n++; } } if (n < 2) return (0); buf_end(&outbuf); return (buf_len(&outbuf)); }
static int process_pop_server(struct pop_info *pop, char *data, int len) { struct buf *line, *body, buf; int i; buf_init(&buf, data, len); if (pop->state == POP_NONE) return (len); if (pop->state == POP_RETR) { if ((i = buf_index(&buf, "\r\n", 2)) < 0) return (0); line = buf_tok(&buf, NULL, i + 2); if (buf_cmp(line, "+OK", 3) == 0) { pop->state = POP_DATA; } else pop->state = POP_NONE; } if (pop->state == POP_DATA) { if ((i = buf_index(&buf, "\r\n.\r\n", 5)) >= 0) { body = buf_tok(&buf, NULL, i); buf_skip(&buf, 5); body->base[body->end] = '\0'; if (regex_match(buf_ptr(body))) print_mbox_msg(NULL, buf_ptr(body)); pop->state = POP_NONE; } } return (len - buf_len(&buf)); }
int decode_aim(u_char *buf, int len, u_char *obuf, int olen) { struct buf *msg, inbuf, outbuf; struct flap *flap; u_char c, *p; int i, j; buf_init(&inbuf, buf, len); buf_init(&outbuf, obuf, olen); if (buf_cmp(&inbuf, "FLAPON\r\n\r\n", 10) == 0) buf_skip(&inbuf, 10); while (buf_len(&inbuf) > sizeof(*flap)) { flap = (struct flap *)buf_ptr(&inbuf); flap->datalen = ntohs(flap->datalen); i = sizeof(*flap) + flap->datalen; if ((msg = buf_tok(&inbuf, NULL, i)) == NULL) break; buf_skip(msg, sizeof(*flap)); if (buf_cmp(msg, "toc_signon ", 11) == 0) { msg->base[msg->end - 1] = '\0'; p = buf_ptr(msg); for (i = 0; i < 4; i++) { if ((j = strcspn(p, " ")) > 0) p += (j + 1); } if (strtok(p, " ") == NULL) continue; buf_putf(&outbuf, "%s ", buf_ptr(msg)); i = strlen(p); j = hex_decode(p, i, p, i); for (i = 0; i < j; i++) p[i] = p[i] ^ aim_xor1[i % 7]; p[i] = '\0'; buf_putf(&outbuf, "[%s]\n", p); } else if (flap->start == 0x2a && flap->channel == 0x01 && buf_cmp(msg, "\x00\x00\x00\x01", 4) == 0) { buf_skip(msg, 7); buf_get(msg, &c, 1); p = buf_ptr(msg); if (c == 0 || buf_skip(msg, c + 3) < 0) continue; p[c] = '\0'; buf_get(msg, &c, 1); if (buf_len(msg) < c + 1) continue; buf_putf(&outbuf, "%s\n", p); p = buf_ptr(msg); for (i = 0; i < c; i++) { p[i] = p[i] ^ aim_xor2[i % sizeof(aim_xor2)]; } p[i] = '\0'; buf_putf(&outbuf, "%s\n", p); break; } } buf_end(&outbuf); return (buf_len(&outbuf)); }
int decode_mmxp(u_char *buf, int len, u_char *obuf, int olen) { struct buf inbuf, outbuf; u_char *p, c; u_int32_t i; int encrypt; buf_init(&inbuf, buf, len); buf_init(&outbuf, obuf, len); while ((i = buf_index(&inbuf, "\x00\x00\x24\x55", 4)) != -1) { buf_skip(&inbuf, i + 4); if (buf_cmp(&inbuf, "\x7f\xff", 2) == 0) encrypt = 1; else if (buf_cmp(&inbuf, "\xff\xff", 2) == 0) encrypt = 0; else continue; buf_skip(&inbuf, 4); /* LPPPg? */ if (buf_get(&inbuf, &i, sizeof(i)) < 0) break; i = ntohl(i); if (buf_skip(&inbuf, i + 4 + 4) < 0) continue; /* Server. */ if (buf_get(&inbuf, &c, 1) != 1) break; if (buf_len(&inbuf) < c) break; buf_put(&outbuf, buf_ptr(&inbuf), c); buf_put(&outbuf, "\n", 1); buf_skip(&inbuf, c + 4); /* Username. */ if (buf_get(&inbuf, &c, 1) != 1) break; if (buf_len(&inbuf) < c) break; buf_put(&outbuf, buf_ptr(&inbuf), c); buf_put(&outbuf, "\n", 1); buf_skip(&inbuf, c + 4); /* Password. */ if (buf_get(&inbuf, &c, 1) != 1) break; if (buf_len(&inbuf) < c) break; p = buf_ptr(&inbuf); if (encrypt) { for (i = 0; i < c; i++) p[i] ^= mm_xor[i % (sizeof(MM_SECRET) - 1)]; } buf_put(&outbuf, p, c); buf_put(&outbuf, "\n", 1); } buf_end(&outbuf); return (buf_len(&outbuf)); }
static void rcsclean_file(char *fname, const char *rev_str) { int fd, match; RCSFILE *file; char fpath[PATH_MAX], numb[RCS_REV_BUFSZ]; RCSNUM *rev; BUF *b1, *b2; time_t rcs_mtime = -1; b1 = b2 = NULL; file = NULL; rev = NULL; if ((fd = rcs_choosefile(fname, fpath, sizeof(fpath))) < 0) goto out; if ((file = rcs_open(fpath, fd, RCS_RDWR)) == NULL) goto out; if (flags & PRESERVETIME) rcs_mtime = rcs_get_mtime(file); rcs_kwexp_set(file, kflag); if (rev_str == NULL) rev = file->rf_head; else if ((rev = rcs_getrevnum(rev_str, file)) == NULL) { warnx("%s: Symbolic name `%s' is undefined.", fpath, rev_str); goto out; } if ((b1 = rcs_getrev(file, rev)) == NULL) { warnx("failed to get needed revision"); goto out; } if ((b2 = buf_load(fname)) == NULL) { warnx("failed to load `%s'", fname); goto out; } /* If buffer lengths are the same, compare contents as well. */ if (buf_len(b1) != buf_len(b2)) match = 0; else { size_t len, n; len = buf_len(b1); match = 1; for (n = 0; n < len; ++n) if (buf_getc(b1, n) != buf_getc(b2, n)) { match = 0; break; } } if (match == 1) { if (uflag == 1 && !TAILQ_EMPTY(&(file->rf_locks))) { if (!(flags & QUIET) && nflag == 0) { printf("rcs -u%s %s\n", rcsnum_tostr(rev, numb, sizeof(numb)), fpath); } (void)rcs_lock_remove(file, locker, rev); } if (TAILQ_EMPTY(&(file->rf_locks))) { if (!(flags & QUIET)) printf("rm -f %s\n", fname); if (nflag == 0) (void)unlink(fname); } } rcs_write(file); if (flags & PRESERVETIME) rcs_set_mtime(file, rcs_mtime); out: if (b1 != NULL) buf_free(b1); if (b2 != NULL) buf_free(b2); if (file != NULL) rcs_close(file); }
inline int buf_isfull(RingBuffer *buf) { return buf_len(buf) == (buf->size-1); }
int process_http_request(struct tuple4 *addr, u_char *data, int len) { struct buf *msg, buf; char *p, *req, *uri, *user, *vhost, *referer, *agent; int i; buf_init(&buf, data, len); while ((i = buf_index(&buf, "\r\n\r\n", 4)) >= 0) { msg = buf_tok(&buf, NULL, i); msg->base[msg->end] = '\0'; buf_skip(&buf, 4); if (!regex_match(buf_ptr(msg))) continue; if ((req = strtok(buf_ptr(msg), "\r\n")) == NULL) continue; if (strncmp(req, "GET ", 4) != 0 && strncmp(req, "POST ", 5) != 0 && strncmp(req, "CONNECT ", 8) != 0) continue; if ((uri = strchr(req, ' ')) == NULL) continue; *uri++ = '\0'; user = vhost = referer = agent = NULL; while ((p = strtok(NULL, "\r\n")) != NULL) { if (strncasecmp(p, "Authorization: Basic ", 21) == 0) { p += 21; i = base64_pton(p, p, strlen(p)); p[i] = '\0'; user = p; if ((p = strchr(p, ':')) != NULL) *p = '\0'; } else if (strncasecmp(p, "Host: ", 6) == 0) { vhost = p + 6; } else if (strncasecmp(p, "Referer: ", 9) == 0) { referer = p + 9; } else if (strncasecmp(p, "User-Agent: ", 12) == 0) { agent = p + 12; } else if (strncasecmp(p, "Content-length: ", 16) == 0) { i = atoi(p + 16); buf_tok(NULL, NULL, i); } } if (user == NULL) user = "******"; if (vhost == NULL) vhost = "none";// libnet_host_lookup(addr->daddr, Opt_dns); if (referer == NULL) referer = "-"; if (agent == NULL) agent = "-"; printf("%s - %s [%s] \"%s http://%s%s\" - - \"%s\" \"%s\"\n", //"0.0.0.0", libnet_addr2name4(addr->saddr, Opt_dns), user, timestamp(), req, vhost, uri, referer, agent); } fflush(stdout); return (len - buf_len(&buf)); }
static int buf_isfull(RingBuffer *buf) { return buf_len(buf) == (RINGBUF_SIZE-1); }
int mesh_face_count(const struct mesh *mesh) { return buf_len(mesh->faces); }
int mesh_normal_buffer(const struct mesh *mesh, const float **buf) { if (buf) *buf = mesh->nbuf; return buf_len(mesh->nbuf) / 3; }
static workout_t * workout_extract(BUF *buf, S725_HRM_Type type) { workout_t *w = NULL; int ok = 1; if ((w = calloc(1, sizeof(workout_t))) == NULL) { log_info("workout_extract: calloc: %s", strerror(errno)); return NULL; } /* Define the type of the HRM */ w->type = type; /* Now extract the header data */ workout_read_preamble(w, buf); workout_read_date(w, buf); workout_read_duration(w, buf, 15); if (buf_get_readerr(buf)) { log_info("workout_extract: readerr after header (%d > %d)", buf_get_readerr_offset(buf), buf_len(buf)); workout_free(w); return NULL; } w->avg_hr = buf_getc(buf, 19); w->max_hr = buf_getc(buf, 20); w->laps = buf_getbcd(buf, 21); w->manual_laps = buf_getbcd(buf, 22); w->interval_mode = buf_getc(buf, 23); w->user_id = buf_getbcd(buf, 24); workout_read_units(w, buf); if (buf_get_readerr(buf)) { log_info("workout_extract: readerr after units (%d > %d)", buf_get_readerr_offset(buf), buf_len(buf)); workout_free(w); return NULL; } /* recording mode and interval */ if (w->type == S725_HRM_S610) { w->mode = 0; workout_read_recording_interval (w, buf, 26); workout_read_hr_limits (w, buf, 28); workout_read_bestlap_split (w, buf, 65); workout_read_energy (w, buf, 69); workout_read_cumulative_exercise (w, buf, 75); } else { w->mode = buf_getc(buf, 26); workout_read_recording_interval (w, buf, 27); workout_read_hr_limits (w, buf, 29); workout_read_bestlap_split (w, buf, 66); workout_read_energy (w, buf, 70); workout_read_cumulative_exercise (w, buf, 76); workout_read_ride_info (w, buf, 79); } if (buf_get_readerr(buf)) { log_info("workout_extract: readerr after mode (%d > %d)", buf_get_readerr_offset(buf), buf_len(buf)); workout_free(w); return NULL; } ok = workout_read_laps(w, buf); if (buf_get_readerr(buf)) { log_info("workout_extract: readerr after read laps (%d > %d)", buf_get_readerr_offset(buf), buf_len(buf)); workout_free(w); return NULL; } if (!ok) { workout_free(w); return NULL; } ok = workout_read_samples(w, buf); if (buf_get_readerr(buf)) { log_info("workout_extract: readerr after read samples (%d > %d)", buf_get_readerr_offset(buf), buf_len(buf)); workout_free(w); return NULL; } if (!ok) { workout_free(w); return NULL; } workout_compute_speed_info(w); return w; }
bool tls_crypt_unwrap(const struct buffer *src, struct buffer *dst, struct crypto_options *opt) { static const char error_prefix[] = "tls-crypt unwrap error"; const struct key_ctx *ctx = &opt->key_ctx_bi.decrypt; struct gc_arena gc; gc_init(&gc); ASSERT(opt); ASSERT(src->len > 0); ASSERT(ctx->cipher); ASSERT(packet_id_initialized(&opt->packet_id) || (opt->flags & CO_IGNORE_PACKET_ID)); dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP FROM: %s", format_hex(BPTR(src), BLEN(src), 80, &gc)); if (buf_len(src) < TLS_CRYPT_OFF_CT) { CRYPT_ERROR("packet too short"); } /* Decrypt cipher text */ { int outlen = 0; /* Buffer overflow check (should never fail) */ if (!buf_safe(dst, BLEN(src) - TLS_CRYPT_OFF_CT + TLS_CRYPT_BLOCK_SIZE)) { CRYPT_ERROR("potential buffer overflow"); } if (!cipher_ctx_reset(ctx->cipher, BPTR(src) + TLS_CRYPT_OFF_TAG)) { CRYPT_ERROR("cipher reset failed"); } if (!cipher_ctx_update(ctx->cipher, BPTR(dst), &outlen, BPTR(src) + TLS_CRYPT_OFF_CT, BLEN(src) - TLS_CRYPT_OFF_CT)) { CRYPT_ERROR("cipher update failed"); } ASSERT(buf_inc_len(dst, outlen)); if (!cipher_ctx_final(ctx->cipher, BPTR(dst), &outlen)) { CRYPT_ERROR("cipher final failed"); } ASSERT(buf_inc_len(dst, outlen)); } /* Check authentication */ { const uint8_t *tag = BPTR(src) + TLS_CRYPT_OFF_TAG; uint8_t tag_check[TLS_CRYPT_TAG_SIZE] = { 0 }; dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP AD: %s", format_hex(BPTR(src), TLS_CRYPT_OFF_TAG, 0, &gc)); dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP TO: %s", format_hex(BPTR(dst), BLEN(dst), 80, &gc)); hmac_ctx_reset(ctx->hmac); hmac_ctx_update(ctx->hmac, BPTR(src), TLS_CRYPT_OFF_TAG); hmac_ctx_update(ctx->hmac, BPTR(dst), BLEN(dst)); hmac_ctx_final(ctx->hmac, tag_check); if (memcmp_constant_time(tag, tag_check, sizeof(tag_check))) { dmsg(D_CRYPTO_DEBUG, "tag : %s", format_hex(tag, sizeof(tag_check), 0, &gc)); dmsg(D_CRYPTO_DEBUG, "tag_check: %s", format_hex(tag_check, sizeof(tag_check), 0, &gc)); CRYPT_ERROR("packet authentication failed"); } } /* Check replay */ if (!(opt->flags & CO_IGNORE_PACKET_ID)) { struct packet_id_net pin; struct buffer tmp = *src; ASSERT(buf_advance(&tmp, TLS_CRYPT_OFF_PID)); ASSERT(packet_id_read(&pin, &tmp, true)); if (!crypto_check_replay(opt, &pin, error_prefix, &gc)) { CRYPT_ERROR("packet replay"); } } gc_free(&gc); return true; error_exit: crypto_clear_error(); dst->len = 0; gc_free(&gc); return false; }
void STDCALL gesave_bytecode( povmbcode bcode ) { pvartype pvar; uint i, count = 0, cmd, val, k; puint end, ptr; gesave_var( bcode->vmf.ret ); gesave_varlist( bcode->vmf.params, bcode->vmf.parcount ); gesave_bwdi( bcode->setcount ); for ( i = 0; i < bcode->setcount; i++ ) { gesave_bwdi( bcode->sets[i].count ); count += bcode->sets[i].count; } pvar = bcode->vars; for ( i = 0; i < count; i++ ) gesave_var( pvar++ ); ptr = ( puint )bcode->vmf.func; if ( ptr ) { end = ( puint )( ( pubyte )ptr + bcode->bcsize ); while ( ptr < end ) { cmd = gesave_bwdc( *ptr++ ); if ( cmd >= CNop && cmd < CNop + STACK_COUNT ) switch ( cmd ) { case CQwload: gesave_adduint( *ptr++ ); gesave_adduint( *ptr++ ); break; case CDwload: val = *ptr++; if ( val <= 0xFF ) { buf_ptr( gesave )[ buf_len( gesave ) - 1 ] = CByload; gesave_addubyte( val ); } else if ( val <= 0xFFFF ) { buf_ptr( gesave )[ buf_len( gesave ) - 1 ] = CShload; gesave_addushort( val ); } else gesave_adduint( val ); break; case CDwsload: i = gesave_bwdi( *ptr++ ); for ( k = 0; k < i; k++ ) gesave_cmdflag( *ptr++ ); break; case CAsm: i = gesave_bwdi( *ptr++ ); gesave_adddata( ( pubyte )ptr, i << 2 ); ptr += i; break; case CResload: case CCmdload: case CPtrglobal: gesave_bwdc( *ptr++ ); break; case CDatasize: i = gesave_bwdi( *ptr++ ); gesave_adddata( ( pubyte )ptr, i ); ptr += ( i >> 2 ) + ( i & 3 ? 1 : 0 ); break; default: switch ( shifts[ cmd - CNop ] ) { case SH1_3: case SH2_3: cmd = gesave_bwdi( *ptr++ ); case SHN1_2: case SH0_2: case SH1_2: cmd = gesave_bwdi( *ptr++ ); break; } } } } }
static int login(struct backend *s, const char *userid, sasl_callback_t *cb, const char **status, int noauth __attribute__((unused))) { int r = 0; socklen_t addrsize; struct sockaddr_storage saddr_l, saddr_r; char remoteip[60], localip[60]; static struct buf buf = BUF_INITIALIZER; sasl_security_properties_t secprops = { 0, 0xFF, PROT_BUFSIZE, 0, NULL, NULL }; /* default secprops */ const char *mech_conf, *pass, *clientout = NULL; struct auth_scheme_t *scheme = NULL; unsigned need_tls = 0, tls_done = 0, auth_done = 0, clientoutlen; hdrcache_t hdrs = NULL; if (status) *status = NULL; /* set the IP addresses */ addrsize = sizeof(struct sockaddr_storage); if (getpeername(s->sock, (struct sockaddr *) &saddr_r, &addrsize) || iptostring((struct sockaddr *) &saddr_r, addrsize, remoteip, 60)) { if (status) *status = "Failed to get remote IP address"; return SASL_FAIL; } addrsize = sizeof(struct sockaddr_storage); if (getsockname(s->sock, (struct sockaddr *) &saddr_l, &addrsize) || iptostring((struct sockaddr *) &saddr_l, addrsize, localip, 60)) { if (status) *status = "Failed to get local IP address"; return SASL_FAIL; } /* Create callbacks, if necessary */ if (!cb) { buf_setmap(&buf, s->hostname, strcspn(s->hostname, ".")); buf_appendcstr(&buf, "_password"); pass = config_getoverflowstring(buf_cstring(&buf), NULL); if (!pass) pass = config_getstring(IMAPOPT_PROXY_PASSWORD); cb = mysasl_callbacks(NULL, /* userid */ config_getstring(IMAPOPT_PROXY_AUTHNAME), config_getstring(IMAPOPT_PROXY_REALM), pass); s->sasl_cb = cb; } /* Create SASL context */ r = sasl_client_new(s->prot->sasl_service, s->hostname, localip, remoteip, cb, SASL_USAGE_FLAGS, &s->saslconn); if (r != SASL_OK) goto done; r = sasl_setprop(s->saslconn, SASL_SEC_PROPS, &secprops); if (r != SASL_OK) goto done; /* Get SASL mechanism list. We can force a particular mechanism using a <shorthost>_mechs option */ buf_setmap(&buf, s->hostname, strcspn(s->hostname, ".")); buf_appendcstr(&buf, "_mechs"); if (!(mech_conf = config_getoverflowstring(buf_cstring(&buf), NULL))) { mech_conf = config_getstring(IMAPOPT_FORCE_SASL_CLIENT_MECH); } do { unsigned code; const char **hdr, *errstr, *serverin; char base64[BASE64_BUF_SIZE+1]; unsigned int serverinlen; struct body_t resp_body; #ifdef SASL_HTTP_REQUEST sasl_http_request_t httpreq = { "OPTIONS", /* Method */ "*", /* URI */ (u_char *) "", /* Empty body */ 0, /* Zero-length body */ 0 }; /* Persistent cxn? */ #endif /* Base64 encode any client response, if necessary */ if (clientout && scheme && (scheme->flags & AUTH_BASE64)) { r = sasl_encode64(clientout, clientoutlen, base64, BASE64_BUF_SIZE, &clientoutlen); if (r != SASL_OK) break; clientout = base64; } /* Send Authorization and/or Upgrade request to server */ prot_puts(s->out, "OPTIONS * HTTP/1.1\r\n"); prot_printf(s->out, "Host: %s\r\n", s->hostname); prot_printf(s->out, "User-Agent: %s\r\n", buf_cstring(&serverinfo)); if (scheme) { prot_printf(s->out, "Authorization: %s %s\r\n", scheme->name, clientout ? clientout : ""); prot_printf(s->out, "Authorize-As: %s\r\n", userid ? userid : "anonymous"); } else { prot_printf(s->out, "Upgrade: %s\r\n", TLS_VERSION); if (need_tls) { prot_puts(s->out, "Connection: Upgrade\r\n"); need_tls = 0; } prot_puts(s->out, "Authorization: \r\n"); } prot_puts(s->out, "\r\n"); prot_flush(s->out); serverin = clientout = NULL; serverinlen = clientoutlen = 0; /* Read response(s) from backend until final response or error */ do { resp_body.flags = BODY_DISCARD; r = http_read_response(s, METH_OPTIONS, &code, NULL, &hdrs, &resp_body, &errstr); if (r) { if (status) *status = errstr; break; } if (code == 101) { /* Switching Protocols */ if (tls_done) { r = HTTP_BAD_GATEWAY; if (status) *status = "TLS already active"; break; } else if (backend_starttls(s, NULL, NULL, NULL)) { r = HTTP_SERVER_ERROR; if (status) *status = "Unable to start TLS"; break; } else tls_done = 1; } } while (code < 200); switch (code) { default: /* Failure */ if (!r) { r = HTTP_BAD_GATEWAY; if (status) { buf_reset(&buf); buf_printf(&buf, "Unexpected status code from backend: %u", code); *status = buf_cstring(&buf); } } break; case 426: /* Upgrade Required */ if (tls_done) { r = HTTP_BAD_GATEWAY; if (status) *status = "TLS already active"; } else need_tls = 1; break; case 200: /* OK */ if (scheme->recv_success && (serverin = scheme->recv_success(hdrs))) { /* Process success data */ serverinlen = strlen(serverin); goto challenge; } break; case 401: /* Unauthorized */ if (auth_done) { r = SASL_BADAUTH; break; } if (!serverin) { int i = 0; hdr = spool_getheader(hdrs, "WWW-Authenticate"); if (!scheme) { unsigned avail_auth_schemes = 0; const char *mech = NULL; size_t len; /* Compare authentication schemes offered in * WWW-Authenticate header(s) to what we support */ buf_reset(&buf); for (i = 0; hdr && hdr[i]; i++) { len = strcspn(hdr[i], " "); for (scheme = auth_schemes; scheme->name; scheme++) { if (!strncmp(scheme->name, hdr[i], len) && !((scheme->flags & AUTH_NEED_PERSIST) && (resp_body.flags & BODY_CLOSE))) { /* Tag the scheme as available */ avail_auth_schemes |= (1 << scheme->idx); /* Add SASL-based schemes to SASL mech list */ if (scheme->saslmech) { if (buf_len(&buf)) buf_putc(&buf, ' '); buf_appendcstr(&buf, scheme->saslmech); } break; } } } /* If we have a mech_conf, use it */ if (mech_conf && buf_len(&buf)) { char *conf = xstrdup(mech_conf); char *newmechlist = intersect_mechlists(conf, (char *) buf_cstring(&buf)); if (newmechlist) { buf_setcstr(&buf, newmechlist); free(newmechlist); } else { syslog(LOG_DEBUG, "%s did not offer %s", s->hostname, mech_conf); buf_reset(&buf); } free(conf); } #ifdef SASL_HTTP_REQUEST /* Set HTTP request as specified above (REQUIRED) */ httpreq.non_persist = (resp_body.flags & BODY_CLOSE); sasl_setprop(s->saslconn, SASL_HTTP_REQUEST, &httpreq); #endif /* Try to start SASL exchange using available mechs */ r = sasl_client_start(s->saslconn, buf_cstring(&buf), NULL, /* no prompts */ NULL, NULL, /* no initial resp */ &mech); if (mech) { /* Find auth scheme associated with chosen SASL mech */ for (scheme = auth_schemes; scheme->name; scheme++) { if (scheme->saslmech && !strcmp(scheme->saslmech, mech)) break; } } else { /* No matching SASL mechs - try Basic */ scheme = &auth_schemes[AUTH_BASIC]; if (!(avail_auth_schemes & (1 << scheme->idx))) { need_tls = !tls_done; break; /* case 401 */ } } /* Find the associated WWW-Authenticate header */ for (i = 0; hdr && hdr[i]; i++) { len = strcspn(hdr[i], " "); if (!strncmp(scheme->name, hdr[i], len)) break; } } /* Get server challenge, if any */ if (hdr) { const char *p = strchr(hdr[i], ' '); serverin = p ? ++p : ""; serverinlen = strlen(serverin); } } challenge: if (serverin) { /* Perform the next step in the auth exchange */ if (scheme->idx == AUTH_BASIC) { /* Don't care about "realm" in server challenge */ const char *authid = callback_getdata(s->saslconn, cb, SASL_CB_AUTHNAME); pass = callback_getdata(s->saslconn, cb, SASL_CB_PASS); buf_reset(&buf); buf_printf(&buf, "%s:%s", authid, pass); clientout = buf_cstring(&buf); clientoutlen = buf_len(&buf); auth_done = 1; } else { /* Base64 decode any server challenge, if necessary */ if (serverin && (scheme->flags & AUTH_BASE64)) { r = sasl_decode64(serverin, serverinlen, base64, BASE64_BUF_SIZE, &serverinlen); if (r != SASL_OK) break; /* case 401 */ serverin = base64; } /* SASL mech (Digest, Negotiate, NTLM) */ r = sasl_client_step(s->saslconn, serverin, serverinlen, NULL, /* no prompts */ &clientout, &clientoutlen); if (r == SASL_OK) auth_done = 1; } } break; /* case 401 */ } } while (need_tls || clientout); done: if (hdrs) spool_free_hdrcache(hdrs); if (r && status && !*status) *status = sasl_errstring(r, NULL, NULL); return r; }
static void _endline(struct vparse_target *tgt) { buf_appendcstr(tgt->buf, "\r\n"); tgt->last = buf_len(tgt->buf); }
static void screenshot_process(void *task) { pixmap_t *pm = task; if(pm == NULL) { screenshot_response(NULL, "Screenshot not supported on this platform"); return; } TRACE(TRACE_DEBUG, "Screenshot", "Processing image %d x %d", pm->pm_width, pm->pm_height); int codecid = AV_CODEC_ID_PNG; if(screenshot_connection) codecid = AV_CODEC_ID_MJPEG; buf_t *b = screenshot_compress(pm, codecid); pixmap_release(pm); if(b == NULL) { screenshot_response(NULL, "Unable to compress image"); return; } if(!screenshot_connection) { char path[512]; char errbuf[512]; snprintf(path, sizeof(path), "%s/screenshot.png", gconf.cache_path); fa_handle_t *fa = fa_open_ex(path, errbuf, sizeof(errbuf), FA_WRITE, NULL); if(fa == NULL) { TRACE(TRACE_ERROR, "SCREENSHOT", "Unable to open %s -- %s", path, errbuf); buf_release(b); return; } fa_write(fa, buf_data(b), buf_len(b)); fa_close(fa); TRACE(TRACE_INFO, "SCREENSHOT", "Written to %s", path); buf_release(b); return; } buf_t *result = NULL; htsbuf_queue_t hq; htsbuf_queue_init(&hq, 0); htsbuf_append(&hq, "image=", 6); htsbuf_append_and_escape_url_len(&hq, buf_cstr(b), buf_len(b)); char errbuf[256]; int ret = http_req("https://api.imgur.com/3/upload", HTTP_FLAGS(FA_CONTENT_ON_ERROR), HTTP_REQUEST_HEADER("Authorization", "Client-ID 7c79b311d4797ed"), HTTP_RESULT_PTR(&result), HTTP_POSTDATA(&hq, "application/x-www-form-urlencoded"), HTTP_ERRBUF(errbuf, sizeof(errbuf)), NULL); if(ret) { screenshot_response(NULL, errbuf); } else { htsmsg_t *response = htsmsg_json_deserialize(buf_cstr(result)); if(response == NULL) { screenshot_response(NULL, "Unable to parse imgur response"); } else { if(htsmsg_get_u32_or_default(response, "success", 0)) { const char *url = htsmsg_get_str_multi(response, "data", "link", NULL); screenshot_response(url, "No link in imgur response"); } else { const char *msg = htsmsg_get_str_multi(response, "data", "error", NULL); if(msg == NULL) { screenshot_response(NULL, "Unkown imgur error"); } else { snprintf(errbuf, sizeof(errbuf), "Imgur error: %s", msg); screenshot_response(NULL, errbuf); } } htsmsg_release(response); } buf_release(result); } buf_release(b); }
uint STDCALL ge_save( pbuf out ) { gehead head; pgehead phead; uint i, count, off = 0; pvmobj pvmo; gesave = out; buf_reserve( out, 0x1ffff ); if ( _compile->flag & CMPL_OPTIMIZE ) ge_optimize(); *( puint )&head.idname = GE_STRING;//0x00004547; // строка GE head.flags = 0; head.crc = 0; head.headsize = sizeof( gehead ); head.size = 0; head.vermajor = GEVER_MAJOR; head.verminor = GEVER_MINOR; buf_append( out, ( pubyte )&head, sizeof( gehead )); // Save resources at the first ! gesave_resource(); count = arr_count( &_vm.objtbl ); // Settings new id depending on GHRT_SKIP gecodes = ( puint )mem_alloc( count * sizeof( uint )); for ( i = KERNEL_COUNT; i < count ; i++ ) { pvmo = ( pvmobj )PCMD( i ); if ( pvmo->flag & GHRT_SKIP ) { gecodes[ i ] = 0; off++; } else gecodes[ i ] = i - off; } for ( i = KERNEL_COUNT; i < count ; i++ ) { pvmo = ( pvmobj )PCMD( i ); if ( pvmo->flag & GHRT_SKIP ) continue; // print("i=%i name=%s\n", i, ((pvmobj)PCMD( i ))->name ); gesave_head( pvmo->type, pvmo->flag & GHCOM_NAME ? pvmo->name : NULL, pvmo->flag ); switch ( pvmo->type ) { case OVM_NONE: break; case OVM_BYTECODE: gesave_bytecode( ( povmbcode )pvmo ); break; case OVM_EXFUNC: gesave_exfunc( ( povmfunc )pvmo ); break; case OVM_TYPE: gesave_type( ( povmtype )pvmo ); break; case OVM_GLOBAL: gesave_var( (( povmglobal )pvmo)->type ); break; case OVM_DEFINE: gesave_define( ( povmdefine )pvmo ); break; case OVM_IMPORT: gesave_import( ( povmimport )pvmo ); break; case OVM_ALIAS: gesave_bwdc( (( povmalias )pvmo)->idlink ); break; } gesave_finish(); } mem_free( gecodes ); // Specify the full size and crc phead = ( pgehead )buf_ptr( out ); phead->size = buf_len( out ); phead->crc = crc( ( pubyte )phead + 12, phead->size - 12, 0xFFFFFFFF ); return 1; }
static void write_hrm_data(BUF *files, const char* directory, int format) { const char *suffix; workout_t *w; FILE* f; BUF *buf; time_t ft; int offset; int count; suffix = format_to_str(format); buf = buf_alloc(0); offset = 0; count = 0; while (files_split(files, &offset, buf)) { char tmbuf[128]; char fnbuf[BUFSIZ]; count++; ft = files_timestamp(buf, 0); strftime(tmbuf, sizeof(tmbuf), "%Y%m%dT%H%M%S", localtime(&ft)); snprintf(fnbuf, sizeof(fnbuf), "%s/%s.%s", directory, tmbuf, suffix); if (format == FORMAT_SRD) { f = fopen(fnbuf, "w"); if (f) { log_writeln("File %02d: Saved as %s", count, fnbuf); fwrite(buf_get(buf), buf_len(buf), 1, f); fclose(f); } else { log_writeln("File %02d: Unable to save %s: %s", count, fnbuf, strerror(errno)); } } else { w = workout_read_buf(buf); if (w) { f = fopen(fnbuf, "w"); if (f) { log_writeln("File %02d: Saved as %s", count, fnbuf); if (format == FORMAT_HRM) { workout_print_hrm(w, f); } else if (format == FORMAT_TCX) { workout_print_tcx(w, f); } else if (format == FORMAT_TXT) { workout_print_txt(w, f, S725_WORKOUT_FULL); } fclose(f); } else { log_writeln("File %02d: Unable to save %s: %s", count, fnbuf, strerror(errno)); } workout_free(w); } else { log_writeln("Failed to parse workout for %s", fnbuf); } } } buf_free(buf); }
static bool tls_crypt_v2_unwrap_client_key(struct key2 *client_key, struct buffer *metadata, struct buffer wrapped_client_key, struct key_ctx *server_key) { const char *error_prefix = __func__; bool ret = false; struct gc_arena gc = gc_new(); /* The crypto API requires one extra cipher block of buffer head room when * decrypting, which nicely matches the tag size of WKc. So * TLS_CRYPT_V2_MAX_WKC_LEN is always large enough for the plaintext. */ uint8_t plaintext_buf_data[TLS_CRYPT_V2_MAX_WKC_LEN] = { 0 }; struct buffer plaintext = { 0 }; dmsg(D_TLS_DEBUG_MED, "%s: unwrapping client key (len=%d): %s", __func__, BLEN(&wrapped_client_key), format_hex(BPTR(&wrapped_client_key), BLEN(&wrapped_client_key), 0, &gc)); if (TLS_CRYPT_V2_MAX_WKC_LEN < BLEN(&wrapped_client_key)) { CRYPT_ERROR("wrapped client key too big"); } /* Decrypt client key and metadata */ uint16_t net_len = 0; const uint8_t *tag = BPTR(&wrapped_client_key); if (BLEN(&wrapped_client_key) < sizeof(net_len)) { CRYPT_ERROR("failed to read length"); } memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len), sizeof(net_len)); if (ntohs(net_len) != BLEN(&wrapped_client_key)) { dmsg(D_TLS_DEBUG_LOW, "%s: net_len=%u, BLEN=%i", __func__, ntohs(net_len), BLEN(&wrapped_client_key)); CRYPT_ERROR("invalid length"); } buf_inc_len(&wrapped_client_key, -(int)sizeof(net_len)); if (!buf_advance(&wrapped_client_key, TLS_CRYPT_TAG_SIZE)) { CRYPT_ERROR("failed to read tag"); } if (!cipher_ctx_reset(server_key->cipher, tag)) { CRYPT_ERROR("failed to initialize IV"); } buf_set_write(&plaintext, plaintext_buf_data, sizeof(plaintext_buf_data)); int outlen = 0; if (!cipher_ctx_update(server_key->cipher, BPTR(&plaintext), &outlen, BPTR(&wrapped_client_key), BLEN(&wrapped_client_key))) { CRYPT_ERROR("could not decrypt client key"); } ASSERT(buf_inc_len(&plaintext, outlen)); if (!cipher_ctx_final(server_key->cipher, BEND(&plaintext), &outlen)) { CRYPT_ERROR("cipher final failed"); } ASSERT(buf_inc_len(&plaintext, outlen)); /* Check authentication */ uint8_t tag_check[TLS_CRYPT_TAG_SIZE] = { 0 }; hmac_ctx_reset(server_key->hmac); hmac_ctx_update(server_key->hmac, (void *)&net_len, sizeof(net_len)); hmac_ctx_update(server_key->hmac, BPTR(&plaintext), BLEN(&plaintext)); hmac_ctx_final(server_key->hmac, tag_check); if (memcmp_constant_time(tag, tag_check, sizeof(tag_check))) { dmsg(D_CRYPTO_DEBUG, "tag : %s", format_hex(tag, sizeof(tag_check), 0, &gc)); dmsg(D_CRYPTO_DEBUG, "tag_check: %s", format_hex(tag_check, sizeof(tag_check), 0, &gc)); CRYPT_ERROR("client key authentication error"); } if (buf_len(&plaintext) < sizeof(client_key->keys)) { CRYPT_ERROR("failed to read client key"); } memcpy(&client_key->keys, BPTR(&plaintext), sizeof(client_key->keys)); ASSERT(buf_advance(&plaintext, sizeof(client_key->keys))); if (!buf_copy(metadata, &plaintext)) { CRYPT_ERROR("metadata too large for supplied buffer"); } ret = true; error_exit: if (!ret) { secure_memzero(client_key, sizeof(*client_key)); } buf_clear(&plaintext); gc_free(&gc); return ret; }
void mesh_begin_face(struct mesh *mesh) { buf_push(mesh->faces, buf_len(mesh->ibuf)); }
static int hc_image(http_connection_t *hc, const char *remain, void *opaque, http_cmd_t method) { htsbuf_queue_t out; image_t *img; char errbuf[200]; const char *content; image_meta_t im = {0}; im.im_no_decoding = 1; rstr_t *url; const char *u = http_arg_get_req(hc, "url"); if(u != NULL) { url = rstr_alloc(u); url_deescape(rstr_data(url)); } else { if(remain == NULL) { return 404; } url = rstr_alloc(remain); } img = backend_imageloader(url, &im, NULL, errbuf, sizeof(errbuf), NULL, NULL); rstr_release(url); if(img == NULL) return http_error(hc, 404, "Unable to load image %s : %s", remain, errbuf); const image_component_t *ic = image_find_component(img, IMAGE_CODED); if(ic == NULL) { image_release(img); return http_error(hc, 404, "Unable to load image %s : Original data not available", remain); } const image_component_coded_t *icc = &ic->coded; htsbuf_queue_init(&out, 0); htsbuf_append(&out, buf_cstr(icc->icc_buf), buf_len(icc->icc_buf)); switch(icc->icc_type) { case IMAGE_JPEG: content = "image/jpeg"; break; case IMAGE_PNG: content = "image/png"; break; case IMAGE_GIF: content = "image/gif"; break; default: content = "image"; break; } image_release(img); return http_send_reply(hc, 0, content, NULL, NULL, 0, &out); }
int mesh_vertex_buffer(const struct mesh *mesh, const float **buf) { if (buf) *buf = mesh->vbuf; return buf_len(mesh->vbuf) / 3; }