/* only called for live migration */ int xc_tmem_save_extra(xc_interface *xch, int dom, int io_fd, int field_marker) { struct tmem_handle handle; int marker = field_marker; uint32_t minusone; int count = 0, checksum = 0; if ( write_exact(io_fd, &marker, sizeof(marker)) ) return -1; while ( xc_tmem_control(xch, 0, XEN_SYSCTL_TMEM_OP_SAVE_GET_NEXT_INV, dom, sizeof(handle),0,&handle) > 0 ) { if ( write_exact(io_fd, &handle.pool_id, sizeof(handle.pool_id)) ) return -1; if ( write_exact(io_fd, &handle.oid, sizeof(handle.oid)) ) return -1; if ( write_exact(io_fd, &handle.index, sizeof(handle.index)) ) return -1; count++; checksum += handle.pool_id + handle.oid.oid[0] + handle.oid.oid[1] + handle.oid.oid[2] + handle.index; } if ( count ) DPRINTF("needed %d tmem invalidates, check=%d\n",count,checksum); minusone = -1; if ( write_exact(io_fd, &minusone, sizeof(minusone)) ) return -1; return 0; }
int write_cmd(const byte *buf, int len) { int big_len = SWAP_ENDIAN_INT32(len); write_exact((byte*)&big_len, 4); return write_exact(buf, len); }
static int handler_tcp_tun_to_net(int fd, const struct worker_struct *ws, char *buff, size_t len) { int dfd, keep = 1; char *cbuff; ssize_t rlen, err, clen; struct ct_proto *hdr; struct curve25519_proto *p; socklen_t nlen; size_t off = sizeof(struct ct_proto) + crypto_box_zerobytes; if (!buff || len <= off) return 0; memset(buff, 0, len); while ((rlen = read(fd, buff + off, len - off)) > 0) { dfd = -1; p = NULL; hdr = (struct ct_proto *) buff; memset(hdr, 0, sizeof(*hdr)); hdr->flags = 0; trie_addr_lookup(buff + off, rlen, ws->parent.ipv4, &dfd, NULL, (size_t *) &nlen); if (unlikely(dfd < 0)) { memset(buff, 0, len); continue; } err = get_user_by_socket(dfd, &p); if (unlikely(err || !p)) { memset(buff, 0, len); continue; } clen = curve25519_encode(ws->c, p, (unsigned char *) (buff + off - crypto_box_zerobytes), (rlen + crypto_box_zerobytes), (unsigned char **) &cbuff); if (unlikely(clen <= 0)) { memset(buff, 0, len); continue; } hdr->payload = htons((uint16_t) clen); set_tcp_cork(dfd); write_exact(dfd, hdr, sizeof(struct ct_proto), 0); write_exact(dfd, cbuff, clen, 0); set_tcp_uncork(dfd); memset(buff, 0, len); } return keep; }
int text_to_speech(byte *buf, int len) { const char* sess_id = NULL; char *obuf = NULL; unsigned int audio_len = 0; unsigned int olen = 0; int synth_status = 1; int ret = 0; byte erlret = 0; debug("Texting to speech %d bytes, %s", len, buf); ret = MSPLogin(NULL, NULL, login_configs); if ( ret != MSP_SUCCESS ) { debug("MSPLogin failed: %d", ret); return ret; } sess_id = QTTSSessionBegin(tts_params, &ret); if ( ret != MSP_SUCCESS ) { debug("QTTSSessionBegin failed: %d", ret); return ret; } ret = QTTSTextPut(sess_id, buf, len, NULL ); if ( ret != MSP_SUCCESS ) { debug("QTTSTextPut failed: %d", ret); QTTSSessionEnd(sess_id, "TextPutError"); return ret; } while (1) { const void *data = QTTSAudioGet(sess_id, &audio_len, &synth_status, &ret); if (NULL != data) { obuf = realloc(obuf, olen+audio_len); memcpy(obuf+olen, data, audio_len); olen += audio_len; } usleep(15000); if (synth_status == 2 || ret != 0) break; } debug("got %d bytes speech", olen); write_head(sizeof(erlret)+olen); write_exact(&erlret, sizeof(erlret)); write_exact(obuf, olen); free(obuf); QTTSSessionEnd(sess_id, NULL); MSPLogout(); return 0; }
static void* update_request_thread( void *obj ) { filter_t* p_filter = (filter_t*)obj; filter_sys_t *p_sys = p_filter->p_sys; msg_Dbg( p_filter, "VNC update request thread started" ); rfbFramebufferUpdateRequestMsg udr; udr.type = rfbFramebufferUpdateRequest; udr.incremental = 0; udr.x = 0; udr.y = 0; udr.w = htons(p_sys->i_vnc_width); udr.h = htons(p_sys->i_vnc_height); int w; vlc_cleanup_push( update_request_thread_cleanup, p_filter ); w = write_exact(p_filter, p_sys->i_socket, (char*)&udr, sz_rfbFramebufferUpdateRequestMsg); vlc_cleanup_pop(); if( !w ) { msg_Err( p_filter, "Could not write rfbFramebufferUpdateRequestMsg." ); update_request_thread_cleanup( p_filter ); return NULL; } udr.incremental = 1; mtime_t i_poll_interval_microsec = p_sys->i_vnc_poll_interval * 1000; if( p_sys->b_vnc_poll) { vlc_cleanup_push( update_request_thread_cleanup, p_filter ); for( ;; ) { msleep( i_poll_interval_microsec ); if( !write_exact(p_filter, p_sys->i_socket, (char*)&udr, sz_rfbFramebufferUpdateRequestMsg)) { msg_Err( p_filter, "Could not write rfbFramebufferUpdateRequestMsg." ); break; } } vlc_cleanup_run(); } else { msg_Dbg( p_filter, "VNC polling disabled." ); } msg_Dbg( p_filter, "VNC update request thread ended" ); return NULL; }
void sipe_core_ft_incoming_start(struct sipe_file_transfer *ft, gsize total_size) { static const guchar VER[] = "VER MSN_SECURE_FTP\r\n"; static const guchar TFR[] = "TFR\r\n"; const gsize BUFFER_SIZE = 50; const gsize FILE_SIZE_OFFSET = 4; struct sipe_file_transfer_private *ft_private = SIPE_FILE_TRANSFER_PRIVATE; guchar buf[BUFFER_SIZE]; gchar *request; gsize file_size; if (!write_exact(ft_private, VER, sizeof(VER) - 1)) { raise_ft_socket_read_error_and_cancel(ft_private); return; } if (!read_line(ft_private, buf, BUFFER_SIZE)) { raise_ft_socket_read_error_and_cancel(ft_private); return; } request = g_strdup_printf("USR %s %u\r\n", ft_private->sipe_private->username, ft_private->auth_cookie); if (!write_exact(ft_private, (guchar *)request, strlen(request))) { raise_ft_socket_write_error_and_cancel(ft_private); g_free(request); return; } g_free(request); if (!read_line(ft_private, buf, BUFFER_SIZE)) { raise_ft_socket_read_error_and_cancel(ft_private); return; } file_size = g_ascii_strtoull((gchar *) buf + FILE_SIZE_OFFSET, NULL, 10); if (file_size != total_size) { raise_ft_error_and_cancel(ft_private, _("File size is different from the advertised value.")); return; } if (!sipe_backend_ft_write(SIPE_FILE_TRANSFER_PUBLIC, TFR, sizeof(TFR) - 1)) { raise_ft_socket_write_error_and_cancel(ft_private); return; } ft_private->bytes_remaining_chunk = 0; ft_private->cipher_context = sipe_cipher_context_init(ft_private->encryption_key); ft_private->hmac_context = sipe_hmac_context_init(ft_private->hash_key); }
int main(void) { char msg[100]; int msg_len; #ifdef __WIN32__ _setmode(_fileno( stdin), _O_BINARY); _setmode(_fileno( stdout), _O_BINARY); #endif msg_len = read_exact(msg, 100); write_exact("Content-type: text/plain\r\n\r\n", 28); write_exact(msg, msg_len); exit(EXIT_SUCCESS); }
static void* update_request_thread( vlc_object_t *p_thread_obj ) { filter_t* p_filter = (filter_t*)(p_thread_obj->p_parent); filter_sys_t *p_sys = p_filter->p_sys; int canc = vlc_savecancel (); msg_Dbg( p_filter, "VNC update request thread started" ); rfbFramebufferUpdateRequestMsg udr; udr.type = rfbFramebufferUpdateRequest; udr.incremental = 0; udr.x = 0; udr.y = 0; udr.w = htons(p_sys->i_vnc_width); udr.h = htons(p_sys->i_vnc_height); if( !write_exact(p_filter, p_sys->i_socket, (char*)&udr, sz_rfbFramebufferUpdateRequestMsg) ) { msg_Err( p_filter, "Could not write rfbFramebufferUpdateRequestMsg." ); p_sys->b_continue = false; return NULL; } udr.incremental = 1; mtime_t i_poll_interval_microsec = p_sys->i_vnc_poll_interval * 1000; if( p_sys->b_vnc_poll) { while( vlc_object_alive( p_thread_obj ) ) { msleep( i_poll_interval_microsec ); if( !write_exact(p_filter, p_sys->i_socket, (char*)&udr, sz_rfbFramebufferUpdateRequestMsg)) { msg_Err( p_filter, "Could not write rfbFramebufferUpdateRequestMsg." ); break; } } p_sys->b_continue = false; } else { msg_Dbg( p_filter, "VNC polling disabled." ); } msg_Dbg( p_filter, "VNC update request thread ended" ); vlc_restorecancel (canc); return NULL; }
static void eadf_close(struct disk *d) { struct disk_info *di = d->di; struct track_info *ti; struct disk_header dhdr; struct track_header thdr; struct track_raw *raw[di->nr_tracks]; unsigned int i, j; lseek(d->fd, 0, SEEK_SET); if (ftruncate(d->fd, 0) < 0) err(1, NULL); memset(&dhdr, 0, sizeof(dhdr)); strncpy(dhdr.sig, "UAE-1ADF", sizeof(dhdr.sig)); dhdr.nr_tracks = htobe16(di->nr_tracks); write_exact(d->fd, &dhdr, sizeof(dhdr)); memset(raw, 0, sizeof(raw)); memset(&thdr, 0, sizeof(thdr)); thdr.type = htobe16(1); for (i = 0; i < di->nr_tracks; i++) { ti = &di->track[i]; if (ti->type == TRKTYP_unformatted) { thdr.len = thdr.bitlen = 0; } else { raw[i] = track_alloc_raw_buffer(d); track_read_raw(raw[i], i); thdr.len = htobe32((raw[i]->bitlen+7)/8); thdr.bitlen = htobe32(raw[i]->bitlen); for (j = 0; j < (raw[i]->bitlen+7)/8; j++) { if (raw[i]->speed[j] == 1000) continue; printf("*** T%u: Variable-density track cannot be correctly " "written to an Ext-ADF file\n", i); break; } } write_exact(d->fd, &thdr, sizeof(thdr)); } for (i = 0; i < di->nr_tracks; i++) { if (raw[i] == NULL) continue; write_exact(d->fd, raw[i]->bits, (raw[i]->bitlen+7)/8); track_free_raw_buffer(raw[i]); } }
static int lock_suspend_event(xc_interface *xch, int domid) { int fd, rc; mode_t mask; char buf[128]; char suspend_file[256]; snprintf(suspend_file, sizeof(suspend_file), "%s_%d_lock.d", SUSPEND_LOCK_FILE, domid); clean_obsolete_lock(domid); mask = umask(022); fd = open(suspend_file, O_CREAT | O_EXCL | O_RDWR, 0666); if (fd < 0) { ERROR("Can't create lock file for suspend event channel %s\n", suspend_file); return -EINVAL; } umask(mask); snprintf(buf, sizeof(buf), "%10ld", (long)getpid()); rc = write_exact(fd, buf, strlen(buf)); close(fd); if(rc) unlink(suspend_file); return rc; }
gboolean sipe_core_ft_outgoing_stop(struct sipe_file_transfer *ft) { gsize BUFFER_SIZE = 50; struct sipe_file_transfer_private *ft_private = SIPE_FILE_TRANSFER_PRIVATE; guchar buffer[BUFFER_SIZE]; gchar *mac; gsize mac_len; /* BYE */ if (!read_line(ft_private, buffer, BUFFER_SIZE)) { raise_ft_socket_read_error_and_cancel(ft_private); return FALSE; } mac = sipe_hmac_finalize(ft_private->hmac_context); g_sprintf((gchar *)buffer, "MAC %s \r\n", mac); g_free(mac); mac_len = strlen((gchar *)buffer); /* There must be this zero byte between mac and \r\n */ buffer[mac_len - 3] = 0; if (!write_exact(ft_private, buffer, mac_len)) { raise_ft_socket_write_error_and_cancel(ft_private); return FALSE; } return TRUE; }
void scp_send( struct scp_handle *scp, uint8_t cmd, void *dat, uint8_t len) { uint8_t *buf = memalloc(len + 3); unsigned int i; buf[0] = cmd; buf[1] = len; memcpy(buf + 2, dat, len); buf[len + 2] = 0x4a; for (i = 0; i < len + 2; i++) buf[len + 2] += buf[i]; write_exact(scp->fd, buf, len + 3); if (cmd == SCPCMD_SENDRAM_USB) read_exact(scp->fd, dat, 512*1024); read_exact(scp->fd, buf, 2); if (buf[0] != cmd) errx(1, "Mismatch command echo: sent %02x (%s), received %02x (%s)", cmd, scp_cmdstr(cmd), buf[0], scp_cmdstr(buf[0])); if (buf[1] != 0x4f) errx(1, "Command %02x (%s) failed: %02x (%s)", cmd, scp_cmdstr(cmd), buf[1], scp_errstr(buf[1])); memfree(buf); }
/* length, cmd and payload must be filled in */ static int send_frame(int serialfd, struct sfl_frame *frame) { unsigned short int crc; int retry; char reply; crc = crc16(&frame->cmd, frame->length+1); frame->crc[0] = (crc & 0xff00) >> 8; frame->crc[1] = (crc & 0x00ff); retry = 0; do { if(!write_exact(serialfd, (char *)frame, frame->length+4)) { perror("[FLTERM] Unable to write to serial port."); return 0; } /* Get the reply from the device */ read(serialfd, &reply, 1); /* TODO: timeout */ switch(reply) { case SFL_ACK_SUCCESS: retry = 0; break; case SFL_ACK_CRCERROR: retry = 1; break; default: fprintf(stderr, "[FLTERM] Got unknown reply '%c' from the device, aborting.\n", reply); return 0; } } while(retry); return 1; }
static void answer_magic(int serialfd, const char *kernel_image, unsigned int kernel_address, const char *cmdline, unsigned int cmdline_address, const char *initrd_image, unsigned int initrd_address) { int kernelfd, initrdfd; struct sfl_frame frame; printf("[FLTERM] Received firmware download request from the device.\n"); kernelfd = open(kernel_image, O_RDONLY); if(kernelfd == -1) { perror("[FLTERM] Unable to open kernel image (request ignored)."); return; } initrdfd = -1; if(initrd_image != NULL) { initrdfd = open(initrd_image, O_RDONLY); if(initrdfd == -1) { perror("[FLTERM] Unable to open initrd image (request ignored)."); close(kernelfd); return; } } write_exact(serialfd, sfl_magic_ack, SFL_MAGIC_LEN); upload_fd(serialfd, "kernel", kernelfd, kernel_address); if(cmdline != NULL) { int len; printf("[FLTERM] Setting kernel command line: '%s'.\n", cmdline); len = strlen(cmdline)+1; if(len > (254-4)) { fprintf(stderr, "[FLTERM] Kernel command line too long, load aborted.\n"); close(initrdfd); close(kernelfd); return; } frame.length = len+4; frame.cmd = SFL_CMD_LOAD; frame.payload[0] = (cmdline_address & 0xff000000) >> 24; frame.payload[1] = (cmdline_address & 0x00ff0000) >> 16; frame.payload[2] = (cmdline_address & 0x0000ff00) >> 8; frame.payload[3] = (cmdline_address & 0x000000ff); strcpy((char *)&frame.payload[4], cmdline); send_frame(serialfd, &frame); frame.length = 4; frame.cmd = SFL_CMD_CMDLINE; frame.payload[0] = (cmdline_address & 0xff000000) >> 24; frame.payload[1] = (cmdline_address & 0x00ff0000) >> 16; frame.payload[2] = (cmdline_address & 0x0000ff00) >> 8; frame.payload[3] = (cmdline_address & 0x000000ff); send_frame(serialfd, &frame); }
static void handler_udp_tun_to_net(int sfd, int dfd, struct curve25519_proto *p, struct curve25519_struct *c, char *buff, size_t len) { char *cbuff; ssize_t rlen, clen; struct ct_proto *hdr; size_t off = sizeof(struct ct_proto) + crypto_box_zerobytes; if (!buff || len <= off) return; memset(buff, 0, len); while ((rlen = read(sfd, buff + off, len - off)) > 0) { hdr = (struct ct_proto *) buff; memset(hdr, 0, sizeof(*hdr)); hdr->flags = 0; clen = curve25519_encode(c, p, (unsigned char *) (buff + off - crypto_box_zerobytes), (rlen + crypto_box_zerobytes), (unsigned char **) &cbuff); if (unlikely(clen <= 0)) goto close; hdr->payload = htons((uint16_t) clen); set_udp_cork(dfd); write_exact(dfd, hdr, sizeof(struct ct_proto), 0); write_exact(dfd, cbuff, clen, 0); set_udp_uncork(dfd); memset(buff, 0, len); } return; close: closed_by_server = 1; }
static void notify_close(int fd) { struct ct_proto hdr; memset(&hdr, 0, sizeof(hdr)); hdr.flags |= PROTO_FLAG_EXIT; hdr.payload = 0; write_exact(fd, &hdr, sizeof(hdr), 0); }
static void *worker(void *self) { int fd, old_state; ssize_t ret; size_t blen = TUNBUFF_SIZ; //FIXME const struct worker_struct *ws = self; struct pollfd fds; char *buff; fds.fd = ws->efd[0]; fds.events = POLLIN; ret = curve25519_alloc_or_maybe_die(ws->c); if (ret < 0) syslog_panic("Cannot init curve25519!\n"); buff = xmalloc_aligned(blen, 64); syslog(LOG_INFO, "curvetun thread on CPU%u up!\n", ws->cpu); pthread_cleanup_push(xfree_func, ws->c); pthread_cleanup_push(curve25519_free, ws->c); pthread_cleanup_push(xfree_func, buff); while (likely(!sigint)) { poll(&fds, 1, -1); if ((fds.revents & POLLIN) != POLLIN) continue; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state); while ((ret = read_exact(ws->efd[0], &fd, sizeof(fd), 1)) > 0) { if (ret != sizeof(fd)) { sched_yield(); continue; } ret = ws->handler(fd, ws, buff, blen); if (ret) write_exact(ws->parent.refd, &fd, sizeof(fd), 1); } pthread_setcancelstate(old_state, NULL); } syslog(LOG_INFO, "curvetun thread on CPU%u down!\n", ws->cpu); pthread_cleanup_pop(1); pthread_cleanup_pop(1); pthread_cleanup_pop(1); pthread_exit((void *) ((long) ws->cpu)); }
static void adf_close(struct disk *d) { struct disk_info *di = d->di; unsigned int i; lseek(d->fd, 0, SEEK_SET); if (ftruncate(d->fd, 0) < 0) err(1, NULL); for (i = 0; i < di->nr_tracks; i++) write_exact(d->fd, di->track[i].dat, 11*512); }
/* * MiniOS's libc doesn't know about writev(). Implement it as multiple write()s. */ int writev_exact(int fd, const struct iovec *iov, int iovcnt) { int rc, i; for ( i = 0; i < iovcnt; ++i ) { rc = write_exact(fd, iov[i].iov_base, iov[i].iov_len); if ( rc ) return rc; } return 0; }
static int write_packet (int fd, unsigned int header_bytes, char* buf, size_t len) { char header[header_bytes]; char *tmp; unsigned int tmplen; for (tmp = header + header_bytes, tmplen = len; tmp > header; tmplen >>= 8) { *--tmp = tmplen & 0xff; } if (write_exact (fd, header, header_bytes) != header_bytes) { return -1; } return write_exact (fd, buf, len); }
static void img_close(struct disk *d) { unsigned int i; struct disk_info *di = d->di; struct track_sectors *sectors; lseek(d->fd, 0, SEEK_SET); if (ftruncate(d->fd, 0) < 0) err(1, NULL); sectors = track_alloc_sector_buffer(d); for (i = 0; i < di->nr_tracks; i++) { if (track_read_sectors(sectors, i) != 0) continue; write_exact(d->fd, sectors->data, sectors->nr_bytes); } track_free_sector_buffer(sectors); }
static int write_update_request(filter_t *p_filter, bool incremental) { filter_sys_t *p_sys = p_filter->p_sys; rfbFramebufferUpdateRequestMsg udr; udr.type = rfbFramebufferUpdateRequest; udr.incremental = incremental; udr.x = 0; udr.y = 0; udr.w = htons(p_sys->i_vnc_width); udr.h = htons(p_sys->i_vnc_height); int w = write_exact(p_filter, p_sys->i_socket, &udr, sz_rfbFramebufferUpdateRequestMsg); if( !w ) msg_Err( p_filter, "Could not write rfbFramebufferUpdateRequestMsg." ); return w; }
void debug0(char *file, int line, char *format, ...) { /* TODO: put timezone or use UTC */ time_t t; struct tm tm[1]; struct timeval tv[1]; va_list valist1; char buf[0x7fff]; int n; long usec; va_start(valist1, format); get_current_timeval(tv); t = tv->tv_sec; usec = tv->tv_usec; assert(localtime_r(&t, tm) == tm); /* the time resolution (1/100 of millisecond) below is the * same used by svlogd with -ttt option */ n = 0; n = snprintf(buf+n, SOZ(sizeof(buf),n), "%u-%.2u-%.2uT%.2u:%.2u:%.2u.%.5u: %s:%i: ", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (unsigned int)(usec/10), file, line ); n += vsnprintf(buf+n, SOZ(sizeof(buf),n), format, valist1); n += snprintf(buf+n, SOZ(sizeof(buf),n), "\n"); write_exact(STDERR_FILENO, buf, n); va_end(valist1); }
int xenevtchn_unmask(xenevtchn_handle *xce, evtchn_port_t port) { int fd = xce->fd; return write_exact(fd, (char *)&port, sizeof(port)); }
void sipe_core_ft_outgoing_start(struct sipe_file_transfer *ft, gsize total_size) { static const guchar VER[] = "VER MSN_SECURE_FTP\r\n"; const gsize BUFFER_SIZE = 50; struct sipe_file_transfer_private *ft_private = SIPE_FILE_TRANSFER_PRIVATE; guchar buf[BUFFER_SIZE]; gchar **parts; unsigned auth_cookie_received; gboolean users_match; if (!read_line(ft_private, buf, BUFFER_SIZE)) { raise_ft_socket_read_error_and_cancel(ft_private); return; } if (!sipe_strequal((gchar *)buf, (gchar *)VER)) { raise_ft_error_and_cancel(ft_private, _("File transfer initialization failed.")); SIPE_DEBUG_INFO("File transfer VER string incorrect, received: %s expected: %s", buf, VER); return; } if (!write_exact(ft_private, VER, sizeof(VER) - 1)) { raise_ft_socket_write_error_and_cancel(ft_private); return; } if (!read_line(ft_private, buf, BUFFER_SIZE)) { raise_ft_socket_read_error_and_cancel(ft_private); return; } parts = g_strsplit((gchar *)buf, " ", 3); auth_cookie_received = g_ascii_strtoull(parts[2], NULL, 10); /* dialog->with has 'sip:' prefix, skip these four characters */ users_match = sipe_strcase_equal(parts[1], (ft_private->dialog->with + 4)); g_strfreev(parts); SIPE_DEBUG_INFO("File transfer authentication: %s Expected: USR %s %u", buf, ft_private->dialog->with + 4, ft_private->auth_cookie); if (!users_match || (ft_private->auth_cookie != auth_cookie_received)) { raise_ft_error_and_cancel(ft_private, _("File transfer authentication failed.")); return; } g_sprintf((gchar *)buf, "FIL %" G_GSIZE_FORMAT "\r\n", total_size); if (!write_exact(ft_private, buf, strlen((gchar *)buf))) { raise_ft_socket_write_error_and_cancel(ft_private); return; } /* TFR */ if (!read_line(ft_private ,buf, BUFFER_SIZE)) { raise_ft_socket_read_error_and_cancel(ft_private); return; } ft_private->bytes_remaining_chunk = 0; ft_private->cipher_context = sipe_cipher_context_init(ft_private->encryption_key); ft_private->hmac_context = sipe_hmac_context_init(ft_private->hash_key); }
static void notify_init(int fd, int udp, struct curve25519_proto *p, struct curve25519_struct *c, char *home) { int fd2, i; ssize_t err, clen; size_t us_len, msg_len, pad; struct ct_proto hdr; char username[256], path[PATH_MAX], *us, *cbuff, *msg; unsigned char auth[crypto_auth_hmacsha512256_BYTES], *token; mt_init_by_random_device(); memset(&hdr, 0, sizeof(hdr)); hdr.flags |= PROTO_FLAG_INIT; memset(path, 0, sizeof(path)); slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM); fd2 = open_or_die(path, O_RDONLY); memset(username, 0, sizeof(username)); err = read(fd2, username, sizeof(username)); username[sizeof(username) - 1] = 0; close(fd2); token = get_serv_store_entry_auth_token(); if (!token) syslog_panic("Cannot find auth token for server!\n"); us_len = sizeof(struct username_struct) + crypto_box_zerobytes; us = xzmalloc(us_len); err = username_msg(username, strlen(username) + 1, us + crypto_box_zerobytes, us_len - crypto_box_zerobytes); if (unlikely(err)) syslog_panic("Cannot create init message!\n"); clen = curve25519_encode(c, p, (unsigned char *) us, us_len, (unsigned char **) &cbuff); if (unlikely(clen <= 0)) syslog_panic("Init encrypt error!\n"); err = crypto_auth_hmacsha512256(auth, (unsigned char *) cbuff, clen, token); if (unlikely(err)) syslog_panic("Cannot create init hmac message!\n"); pad = mt_rand_int32() % 200; msg_len = clen + sizeof(auth) + pad; msg = xzmalloc(msg_len); memcpy(msg, auth, sizeof(auth)); memcpy(msg + sizeof(auth), cbuff, clen); for (i = sizeof(auth) + clen; i < msg_len; ++i) msg[i] = (uint8_t) mt_rand_int32(); hdr.payload = htons((uint16_t) msg_len); set_sock_cork(fd, udp); write_exact(fd, &hdr, sizeof(struct ct_proto), 0); write_exact(fd, msg, msg_len, 0); set_sock_uncork(fd, udp); xfree(msg); xfree(us); }
int server_main(char *home, char *dev, char *port, int udp, int ipv4, int log) { int lfd = -1, kdpfd, nfds, nfd, curfds, efd[2], refd[2], tunfd, i; unsigned int cpus = 0, threads, udp_cpu = 0; ssize_t ret; struct epoll_event *events; struct addrinfo hints, *ahead, *ai; auth_log = !!log; openlog("curvetun", LOG_PID | LOG_CONS | LOG_NDELAY, LOG_DAEMON); syslog(LOG_INFO, "curvetun server booting!\n"); syslog_maybe(!auth_log, LOG_INFO, "curvetun user logging disabled!\n"); parse_userfile_and_generate_user_store_or_die(home); memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = udp ? SOCK_DGRAM : SOCK_STREAM; hints.ai_protocol = udp ? IPPROTO_UDP : IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; ret = getaddrinfo(NULL, port, &hints, &ahead); if (ret < 0) syslog_panic("Cannot get address info!\n"); for (ai = ahead; ai != NULL && lfd < 0; ai = ai->ai_next) { lfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (lfd < 0) continue; if (ai->ai_family == AF_INET6) { #ifdef IPV6_V6ONLY ret = set_ipv6_only(lfd); if (ret < 0) { close(lfd); lfd = -1; continue; } #else close(lfd); lfd = -1; continue; #endif /* IPV6_V6ONLY */ } set_reuseaddr(lfd); set_mtu_disc_dont(lfd); ret = bind(lfd, ai->ai_addr, ai->ai_addrlen); if (ret < 0) { close(lfd); lfd = -1; continue; } if (!udp) { ret = listen(lfd, 5); if (ret < 0) { close(lfd); lfd = -1; continue; } } if (ipv4 == -1) { ipv4 = (ai->ai_family == AF_INET6 ? 0 : (ai->ai_family == AF_INET ? 1 : -1)); } syslog_maybe(auth_log, LOG_INFO, "curvetun on IPv%d via %s " "on port %s!\n", ai->ai_family == AF_INET ? 4 : 6, udp ? "UDP" : "TCP", port); syslog_maybe(auth_log, LOG_INFO, "Allowed overlay proto is " "IPv%d!\n", ipv4 ? 4 : 6); } freeaddrinfo(ahead); if (lfd < 0 || ipv4 < 0) syslog_panic("Cannot create socket!\n"); tunfd = tun_open_or_die(dev ? dev : DEVNAME_SERVER, IFF_TUN | IFF_NO_PI); pipe_or_die(efd, O_NONBLOCK); pipe_or_die(refd, O_NONBLOCK); set_nonblocking(lfd); events = xzmalloc(MAX_EPOLL_SIZE * sizeof(*events)); for (i = 0; i < MAX_EPOLL_SIZE; ++i) events[i].data.fd = -1; kdpfd = epoll_create(MAX_EPOLL_SIZE); if (kdpfd < 0) syslog_panic("Cannot create socket!\n"); set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, lfd, udp ? EPOLLIN | EPOLLET | EPOLLONESHOT : EPOLLIN); set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, efd[0], EPOLLIN); set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, refd[0], EPOLLIN); set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, tunfd, EPOLLIN | EPOLLET | EPOLLONESHOT); curfds = 4; trie_init(); cpus = get_number_cpus_online(); threads = cpus * THREADS_PER_CPU; if (!ispow2(threads)) syslog_panic("Thread number not power of two!\n"); threadpool = xzmalloc(sizeof(*threadpool) * threads); thread_spawn_or_panic(cpus, efd[1], refd[1], tunfd, ipv4, udp); init_cpusched(threads); register_socket(tunfd); register_socket(lfd); syslog(LOG_INFO, "curvetun up and running!\n"); while (likely(!sigint)) { nfds = epoll_wait(kdpfd, events, curfds, -1); if (nfds < 0) { syslog(LOG_ERR, "epoll_wait error: %s\n", strerror(errno)); break; } for (i = 0; i < nfds; ++i) { if (unlikely(events[i].data.fd < 0)) continue; if (events[i].data.fd == lfd && !udp) { int ncpu; char hbuff[256], sbuff[256]; struct sockaddr_storage taddr; socklen_t tlen; tlen = sizeof(taddr); nfd = accept(lfd, (struct sockaddr *) &taddr, &tlen); if (nfd < 0) { syslog(LOG_ERR, "accept error: %s\n", strerror(errno)); continue; } if (curfds + 1 > MAX_EPOLL_SIZE) { close(nfd); continue; } curfds++; ncpu = register_socket(nfd); memset(hbuff, 0, sizeof(hbuff)); memset(sbuff, 0, sizeof(sbuff)); getnameinfo((struct sockaddr *) &taddr, tlen, hbuff, sizeof(hbuff), sbuff, sizeof(sbuff), NI_NUMERICHOST | NI_NUMERICSERV); syslog_maybe(auth_log, LOG_INFO, "New connection " "from %s:%s (%d active client connections) - id %d on CPU%d", hbuff, sbuff, curfds-4, nfd, ncpu); set_nonblocking(nfd); set_socket_keepalive(nfd); set_tcp_nodelay(nfd); ret = set_epoll_descriptor2(kdpfd, EPOLL_CTL_ADD, nfd, EPOLLIN | EPOLLET | EPOLLONESHOT); if (ret < 0) { close(nfd); curfds--; continue; } } else if (events[i].data.fd == refd[0]) { int fd_one; ret = read_exact(refd[0], &fd_one, sizeof(fd_one), 1); if (ret != sizeof(fd_one) || fd_one <= 0) continue; ret = set_epoll_descriptor2(kdpfd, EPOLL_CTL_MOD, fd_one, EPOLLIN | EPOLLET | EPOLLONESHOT); if (ret < 0) { close(fd_one); continue; } } else if (events[i].data.fd == efd[0]) { int fd_del, test; ret = read_exact(efd[0], &fd_del, sizeof(fd_del), 1); if (ret != sizeof(fd_del) || fd_del <= 0) continue; ret = read(fd_del, &test, sizeof(test)); if (ret < 0 && errno == EBADF) continue; ret = set_epoll_descriptor2(kdpfd, EPOLL_CTL_DEL, fd_del, 0); if (ret < 0) { close(fd_del); continue; } close(fd_del); curfds--; unregister_socket(fd_del); syslog_maybe(auth_log, LOG_INFO, "Closed connection " "with id %d (%d active client connections remain)\n", fd_del, curfds-4); } else { int cpu, fd_work = events[i].data.fd; if (!udp) cpu = socket_to_cpu(fd_work); else udp_cpu = (udp_cpu + 1) & (threads - 1); write_exact(threadpool[udp ? udp_cpu : cpu].efd[1], &fd_work, sizeof(fd_work), 1); } } } syslog(LOG_INFO, "curvetun prepare shut down!\n"); close(lfd); close(efd[0]); close(efd[1]); close(refd[0]); close(refd[1]); close(tunfd); thread_finish(cpus); xfree(threadpool); xfree(events); unregister_socket(lfd); unregister_socket(tunfd); destroy_cpusched(); trie_cleanup(); destroy_user_store(); syslog(LOG_INFO, "curvetun shut down!\n"); closelog(); return 0; }
static int handler_tcp_net_to_tun(int fd, const struct worker_struct *ws, char *buff, size_t len) { int keep = 1, count = 0; char *cbuff; ssize_t rlen, err, clen; struct ct_proto *hdr; struct curve25519_proto *p; if (!buff || !len) return 0; while ((rlen = handler_tcp_read(fd, buff, len)) > 0) { p = NULL; hdr = (struct ct_proto *) buff; if (unlikely(rlen < sizeof(struct ct_proto))) goto close; if (unlikely(rlen - sizeof(*hdr) != ntohs(hdr->payload))) goto close; if (unlikely(ntohs(hdr->payload) == 0)) goto close; if (hdr->flags & PROTO_FLAG_EXIT) { close: remove_user_by_socket(fd); trie_addr_remove(fd); handler_tcp_notify_close(fd); rlen = write(ws->parent.efd, &fd, sizeof(fd)); keep = 0; return keep; } if (hdr->flags & PROTO_FLAG_INIT) { syslog_maybe(auth_log, LOG_INFO, "Got initial userhash " "from remote end!\n"); if (unlikely(rlen - sizeof(*hdr) < sizeof(struct username_struct))) goto close; err = try_register_user_by_socket(ws->c, buff + sizeof(struct ct_proto), rlen - sizeof(struct ct_proto), fd, auth_log); if (unlikely(err)) goto close; continue; } err = get_user_by_socket(fd, &p); if (unlikely(err || !p)) continue; clen = curve25519_decode(ws->c, p, (unsigned char *) buff + sizeof(struct ct_proto), rlen - sizeof(struct ct_proto), (unsigned char **) &cbuff, NULL); if (unlikely(clen <= 0)) continue; cbuff += crypto_box_zerobytes; clen -= crypto_box_zerobytes; err = trie_addr_maybe_update(cbuff, clen, ws->parent.ipv4, fd, NULL, 0); if (unlikely(err)) continue; err = write(ws->parent.tunfd, cbuff, clen); count++; if (count == 10) { write_exact(ws->efd[1], &fd, sizeof(fd), 1); /* Read later next data and let others process */ return keep; } } return keep; }
static int netbsd_evtchn_unmask(xc_evtchn *xce, xc_osdep_handle h, evtchn_port_t port) { int fd = (int)h; return write_exact(fd, (char *)&port, sizeof(port)); }
static int vnc_connect( filter_t *p_filter ) { filter_sys_t *p_sys = p_filter->p_sys; int port = var_InheritInteger( p_filter, RMTOSD_CFG "port" ); int fd = net_ConnectTCP( p_filter, p_sys->psz_host, port ); if( fd == -1 ) { msg_Err( p_filter, "Could not connect to VNC host" ); return -1; } msg_Dbg( p_filter, "Reading protocol version" ); rfbProtocolVersionMsg pv; if ( !read_exact( p_filter, fd, pv, sz_rfbProtocolVersionMsg ) ) { msg_Err( p_filter, "Could not read version message" ); goto error; } pv[sz_rfbProtocolVersionMsg] = '\0'; /* pv size is sz_rfbProtocolVersionMsg+1 */ msg_Dbg( p_filter, "Server version is %s", pv ); strncpy(pv, "RFB 003.003\n", sz_rfbProtocolVersionMsg); if( !write_exact(p_filter, fd, pv, sz_rfbProtocolVersionMsg) ) { msg_Err( p_filter, "Could not write version message" ); goto error; } msg_Dbg( p_filter, "Reading authentication scheme" ); uint32_t i_authScheme; if( !read_exact( p_filter, fd, &i_authScheme, 4 ) ) { msg_Err( p_filter, "Could not read authentication scheme" ); goto error; } i_authScheme = htonl(i_authScheme); msg_Dbg( p_filter, "Authentication scheme = %x", i_authScheme ); if ( i_authScheme == rfbConnFailed ) { msg_Err( p_filter, "Connection rejected by server" ); goto error; } if (i_authScheme == rfbVncAuth) { unsigned char challenge[CHALLENGESIZE]; if ( !read_exact( p_filter, fd, challenge, CHALLENGESIZE ) ) { msg_Err( p_filter, "Could not read password challenge" ); goto error; } vnc_encrypt_bytes( challenge, p_sys->psz_passwd ); if( !write_exact(p_filter, fd, challenge, CHALLENGESIZE ) ) { msg_Err( p_filter, "Could not write password" ); goto error; } uint32_t i_authResult; if( !read_exact( p_filter, fd, &i_authResult, 4 ) ) { msg_Err( p_filter, "Could not read authentication result" ); goto error; } i_authResult = htonl(i_authResult); if (i_authResult != rfbVncAuthOK) { msg_Err( p_filter, "VNC authentication failed" ); goto error; } } msg_Dbg( p_filter, "Writing client init message" ); rfbClientInitMsg ci; ci.shared = 1; if( !write_exact( p_filter, fd, &ci, sz_rfbClientInitMsg ) ) { msg_Err( p_filter, "Could not write client init message" ); goto error; } msg_Dbg( p_filter, "Reading server init message" ); rfbServerInitMsg si; if( !read_exact( p_filter, fd, &si, sz_rfbServerInitMsg ) ) { msg_Err( p_filter, "Could not read server init message" ); goto error; } si.framebufferWidth = htons(si.framebufferWidth); si.framebufferHeight = htons(si.framebufferHeight); si.format.redMax = htons(si.format.redMax); si.format.greenMax = htons(si.format.greenMax); si.format.blueMax = htons(si.format.blueMax); p_sys->i_vnc_width = si.framebufferWidth; p_sys->i_vnc_height = si.framebufferHeight; msg_Dbg( p_filter, "Servers preferred pixelformat: " "%ux%u, R(%u),G(%u),B(%u), %u bit, depht=%u, %s", si.framebufferWidth, si.framebufferHeight, si.format.redMax, si.format.greenMax, si.format.blueMax, si.format.bitsPerPixel, si.format.depth, si.format.trueColour ? "TrueColor" : "Not-TrueColor"); uint32_t i_nameLength = htonl(si.nameLength); if( i_nameLength > MAX_VNC_SERVER_NAME_LENGTH ) { msg_Err( p_filter, "Server name too long" ); goto error; } char s_ServerName[MAX_VNC_SERVER_NAME_LENGTH+1]; msg_Dbg( p_filter, "Reading server name with size = %u", i_nameLength ); if( !read_exact( p_filter, fd, s_ServerName, i_nameLength ) ) { msg_Err( p_filter, "Could not read server name" ); goto error; } s_ServerName[i_nameLength] = '\0'; if( strcmp( s_ServerName, "VDR-OSD") == 0 ) { msg_Dbg( p_filter, "Server is a VDR" ); p_sys->b_alpha_from_vnc = true; } else { msg_Dbg( p_filter, "Server is a normal VNC" ); p_sys->b_alpha_from_vnc = false; } msg_Dbg( p_filter, "Server init message read properly" ); msg_Dbg( p_filter, "Server name is %s", s_ServerName ); msg_Dbg( p_filter, "Writing SetPixelFormat message" ); rfbSetPixelFormatMsg sp; sp.type = rfbSetPixelFormat; sp.pad1 = sp.pad2 = 0; sp.format.bitsPerPixel = 8; sp.format.depth = 8 ; sp.format.bigEndian = 1; sp.format.trueColour = 0; sp.format.redMax = htons(31); sp.format.greenMax = htons(31); sp.format.blueMax = htons(31); sp.format.redShift = 10; sp.format.greenShift = 5; sp.format.blueShift = 0; sp.format.pad1 = sp.format.pad2 = 0; if( !write_exact( p_filter, fd, &sp, sz_rfbSetPixelFormatMsg) ) { msg_Err( p_filter, "Could not write SetPixelFormat message" ); goto error; } msg_Dbg( p_filter, "Writing SetEncodings message" ); rfbSetEncodingsMsg se; se.type = rfbSetEncodings; se.pad = 0; se.nEncodings = htons( p_sys->b_alpha_from_vnc ? 3 : 2 ); if( !write_exact( p_filter, fd, &se, sz_rfbSetEncodingsMsg) ) { msg_Err( p_filter, "Could not write SetEncodings message begin" ); goto error; } uint32_t i_encoding; msg_Dbg( p_filter, "Writing SetEncodings rfbEncodingCopyRect" ); i_encoding = htonl(rfbEncodingCopyRect); if( !write_exact( p_filter, fd, &i_encoding, 4) ) { msg_Err( p_filter, "Could not write encoding type rfbEncodingCopyRect." ); goto error; } msg_Dbg( p_filter, "Writing SetEncodings rfbEncodingRRE" ); i_encoding = htonl(rfbEncodingRRE); if( !write_exact(p_filter, fd, &i_encoding, 4) ) { msg_Err( p_filter, "Could not write encoding type rfbEncodingRRE." ); goto error; } if( p_sys->b_alpha_from_vnc ) { msg_Dbg( p_filter, "Writing SetEncodings rfbEncSpecialUseAlpha" ); i_encoding = 0x00F0FFFF; /* rfbEncSpecialUseAlpha is 0xFFFFF000 * before we swap it */ if( !write_exact(p_filter, fd, &i_encoding, 4) ) { msg_Err( p_filter, "Could not write encoding type rfbEncSpecialUseAlpha." ); goto error; } } return fd; error: net_Close( fd ); return -1; }