void xmlBuffer::print_raw(const char *str, size_t len) { #ifdef AZ_PROFILER int wlen = response()->write(str, len); assert0( (size_t)wlen == len ); #endif // AZ_PROFILER }
Json::Value CurlManager::execute() { if(!this->curl) { return 0; } if(this->headers) { curl_easy_setopt(this->curl, CURLOPT_HTTPHEADER, this->headers); } std::string URL = this->url + "/" + this->uri; std::vector<std::string>::iterator it = params.begin(); std::string parameters = ""; while(it != params.end()) { parameters += *it + "&"; ++it; } if(parameters.length()) { parameters.pop_back(); URL += "/" + parameters; } curl_easy_setopt(this->curl, CURLOPT_URL, URL.c_str()); // curl_easy_setopt(this->curl, CURLOPT_VERBOSE, 1L); char* postData = NULL; if(!bodyParams .empty()) { Json::FastWriter fast; std::string body = fast.write(this->bodyParams); static std::string bodySender; EscapeJSON(body, bodySender); postData = new char[bodySender.length()](); strcpy(postData, bodySender.c_str()); curl_easy_setopt(this->curl, CURLOPT_POSTFIELDS, postData); } struct cstring s; Json::Value val = Json::Value(); if(this->init_string(&s)) { curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s); CURLcode res; res = curl_easy_perform(this->curl); long responseCode; CURLcode info = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode); if(res != CURLE_OK) { val["error"] = std::string(curl_easy_strerror(res)); } else { std::string response(s.ptr); if(s.ptr) { free(s.ptr); s.ptr = NULL; } if(responseCode == 200 || responseCode == 201) { Json::Reader r = Json::Reader(); r.parse(response.c_str(), val); } else { val["error"] = response; } } if(info == CURLE_OK) { val["status"] = (int)responseCode; } else { val["status"] = 500; } } else { val["status"] = 500; val["error"] = "Internal Error with cstring struct init"; } if(postData != NULL) { delete[] postData; } return val; }
void RouteRequestHandler::operator()() { std::string response(constructResponse()); _connection_data->respond(response); }
int main(int argc, char **argv) { int ch, fflag, tflag, status, n; char *targ, **newargv; const char *errstr; extern char *optarg; extern int optind; /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ sanitise_stdfd(); /* Copy argv, because we modify it */ newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv)); for (n = 0; n < argc; n++) newargv[n] = xstrdup(argv[n]); argv = newargv; __progname = ssh_get_progname(argv[0]); memset(&args, '\0', sizeof(args)); memset(&remote_remote_args, '\0', sizeof(remote_remote_args)); args.list = remote_remote_args.list = NULL; addargs(&args, "%s", ssh_program); addargs(&args, "-x"); addargs(&args, "-oForwardAgent=no"); addargs(&args, "-oPermitLocalCommand=no"); addargs(&args, "-oClearAllForwardings=yes"); fflag = tflag = 0; while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:zZ:")) != -1) switch (ch) { /* User-visible flags. */ case '1': case '2': case '4': case '6': case 'C': case 'z': addargs(&args, "-%c", ch); addargs(&remote_remote_args, "-%c", ch); break; case '3': throughlocal = 1; break; case 'o': case 'c': case 'i': case 'F': case 'Z': addargs(&remote_remote_args, "-%c", ch); addargs(&remote_remote_args, "%s", optarg); addargs(&args, "-%c", ch); addargs(&args, "%s", optarg); break; case 'P': addargs(&remote_remote_args, "-p"); addargs(&remote_remote_args, "%s", optarg); addargs(&args, "-p"); addargs(&args, "%s", optarg); break; case 'B': addargs(&remote_remote_args, "-oBatchmode=yes"); addargs(&args, "-oBatchmode=yes"); break; case 'l': limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024, &errstr); if (errstr != NULL) usage(); limit_kbps *= 1024; /* kbps */ bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN); break; case 'p': pflag = 1; break; case 'r': iamrecursive = 1; break; case 'S': ssh_program = xstrdup(optarg); break; case 'v': addargs(&args, "-v"); addargs(&remote_remote_args, "-v"); verbose_mode = 1; break; case 'q': addargs(&args, "-q"); addargs(&remote_remote_args, "-q"); showprogress = 0; break; /* Server options. */ case 'd': targetshouldbedirectory = 1; break; case 'f': /* "from" */ iamremote = 1; fflag = 1; break; case 't': /* "to" */ iamremote = 1; tflag = 1; #ifdef HAVE_CYGWIN setmode(0, O_BINARY); #endif break; default: usage(); } argc -= optind; argv += optind; if ((pwd = getpwuid(userid = getuid())) == NULL) fatal("unknown user %u", (u_int) userid); if (!isatty(STDOUT_FILENO)) showprogress = 0; remin = STDIN_FILENO; remout = STDOUT_FILENO; if (fflag) { /* Follow "protocol", send data. */ (void) response(); source(argc, argv); exit(errs != 0); } if (tflag) { /* Receive data. */ sink(argc, argv); exit(errs != 0); } if (argc < 2) usage(); if (argc > 2) targetshouldbedirectory = 1; remin = remout = -1; do_cmd_pid = -1; /* Command to be executed on remote system using "ssh". */ (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "", iamrecursive ? " -r" : "", pflag ? " -p" : "", targetshouldbedirectory ? " -d" : ""); (void) signal(SIGPIPE, lostconn); if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */ toremote(targ, argc, argv); else { if (targetshouldbedirectory) verifydir(argv[argc - 1]); tolocal(argc, argv); /* Dest is local host. */ } /* * Finally check the exit status of the ssh process, if one was forked * and no error has occurred yet */ if (do_cmd_pid != -1 && errs == 0) { if (remin != -1) (void) close(remin); if (remout != -1) (void) close(remout); if (waitpid(do_cmd_pid, &status, 0) == -1) errs = 1; else { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) errs = 1; } } exit(errs != 0); }
void source(int argc, char **argv) { struct stat stb; static BUF buffer; BUF *bp; off_t i, statbytes; size_t amt; int fd = -1, haderr, indx; char *last, *name, buf[2048], encname[MAXPATHLEN]; int len; for (indx = 0; indx < argc; ++indx) { name = argv[indx]; statbytes = 0; len = strlen(name); while (len > 1 && name[len-1] == '/') name[--len] = '\0'; if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0) goto syserr; if (strchr(name, '\n') != NULL) { strnvis(encname, name, sizeof(encname), VIS_NL); name = encname; } if (fstat(fd, &stb) < 0) { syserr: run_err("%s: %s", name, strerror(errno)); goto next; } if (stb.st_size < 0) { run_err("%s: %s", name, "Negative file size"); goto next; } unset_nonblock(fd); switch (stb.st_mode & S_IFMT) { case S_IFREG: break; case S_IFDIR: if (iamrecursive) { rsource(name, &stb); goto next; } /* FALLTHROUGH */ default: run_err("%s: not a regular file", name); goto next; } if ((last = strrchr(name, '/')) == NULL) last = name; else ++last; curfile = last; if (pflag) { /* * Make it compatible with possible future * versions expecting microseconds. */ (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n", (u_long) (stb.st_mtime < 0 ? 0 : stb.st_mtime), (u_long) (stb.st_atime < 0 ? 0 : stb.st_atime)); if (verbose_mode) { fprintf(stderr, "File mtime %ld atime %ld\n", (long)stb.st_mtime, (long)stb.st_atime); fprintf(stderr, "Sending file timestamps: %s", buf); } (void) atomicio(vwrite, remout, buf, strlen(buf)); if (response() < 0) goto next; } #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO) snprintf(buf, sizeof buf, "C%04o %lld %s\n", (u_int) (stb.st_mode & FILEMODEMASK), (long long)stb.st_size, last); if (verbose_mode) { fprintf(stderr, "Sending file modes: %s", buf); } (void) atomicio(vwrite, remout, buf, strlen(buf)); if (response() < 0) goto next; if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) { next: if (fd != -1) { (void) close(fd); fd = -1; } continue; } if (showprogress) start_progress_meter(curfile, stb.st_size, &statbytes); set_nonblock(remout); for (haderr = i = 0; i < stb.st_size; i += bp->cnt) { amt = bp->cnt; if (i + (off_t)amt > stb.st_size) amt = stb.st_size - i; if (!haderr) { if (atomicio(read, fd, bp->buf, amt) != amt) haderr = errno; } /* Keep writing after error to retain sync */ if (haderr) { (void)atomicio(vwrite, remout, bp->buf, amt); continue; } if (atomicio6(vwrite, remout, bp->buf, amt, scpio, &statbytes) != amt) haderr = errno; } unset_nonblock(remout); if (showprogress) stop_progress_meter(); if (fd != -1) { if (close(fd) < 0 && !haderr) haderr = errno; fd = -1; } if (!haderr) (void) atomicio(vwrite, remout, "", 1); else run_err("%s: %s", name, strerror(haderr)); (void) response(); } }
void toremote(char *targ, int argc, char *argv[]) { int i; size_t len; char *bp, *host, *src, *suser, *thost, *tuser; *targ++ = 0; if (*targ == 0) targ = dot; if ((thost = strchr(argv[argc - 1], '@')) != NULL) { /* user@host */ *thost++ = 0; tuser = argv[argc - 1]; if (*tuser == '\0') tuser = NULL; else if (!okname(tuser)) exit(1); } else { thost = argv[argc - 1]; tuser = NULL; } thost = unbracket(thost); for (i = 0; i < argc - 1; i++) { src = colon(argv[i]); if (src) { /* remote to remote */ *src++ = 0; if (*src == 0) src = dot; host = strchr(argv[i], '@'); len = strlen(_PATH_RSH) + strlen(argv[i]) + strlen(src) + (tuser ? strlen(tuser) : 0) + strlen(thost) + strlen(targ) + CMDNEEDS + 20; if (!(bp = malloc(len))) err(1, NULL); if (host) { *host++ = 0; host = unbracket(host); suser = argv[i]; if (*suser == '\0') suser = pwname; else if (!okname(suser)) { (void)free(bp); continue; } (void)snprintf(bp, len, "%s %s -l %s -n %s %s '%s%s%s:%s'", _PATH_RSH, host, suser, cmd, src, tuser ? tuser : "", tuser ? "@" : "", thost, targ); } else { host = unbracket(argv[i]); (void)snprintf(bp, len, "exec %s %s -n %s %s '%s%s%s:%s'", _PATH_RSH, argv[i], cmd, src, tuser ? tuser : "", tuser ? "@" : "", thost, targ); } (void)susystem(bp); (void)free(bp); } else { /* local to remote */ if (rem == -1) { len = strlen(targ) + CMDNEEDS + 20; if (!(bp = malloc(len))) err(1, NULL); (void)snprintf(bp, len, "%s -t %s", cmd, targ); host = thost; rem = rcmd_af(&host, port, pwname, tuser ? tuser : pwname, bp, NULL, family); if (rem < 0) exit(1); if (response() < 0) exit(1); (void)free(bp); } source(1, argv+i); } } }
void sink(int argc, char *argv[]) { static BUF buffer; struct stat stb; struct timeval tv[2]; enum { YES, NO, DISPLAYED } wrerr; BUF *bp; ssize_t j; off_t i; off_t amt; off_t count; int exists, first, ofd; mode_t mask; mode_t mode; mode_t omode; int setimes, targisdir; int wrerrno = 0; /* pacify gcc */ char ch, *cp, *np, *targ, *vect[1], buf[BUFSIZ]; const char *why; off_t size; #define atime tv[0] #define mtime tv[1] #define SCREWUP(str) { why = str; goto screwup; } setimes = targisdir = 0; mask = umask(0); if (!pflag) (void)umask(mask); if (argc != 1) { run_err("ambiguous target"); exit(1); } targ = *argv; if (targetshouldbedirectory) verifydir(targ); (void)write(rem, "", 1); if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode)) targisdir = 1; for (first = 1;; first = 0) { cp = buf; if (read(rem, cp, 1) <= 0) return; if (*cp++ == '\n') SCREWUP("unexpected <newline>"); do { if (read(rem, &ch, sizeof(ch)) != sizeof(ch)) SCREWUP("lost connection"); *cp++ = ch; } while (cp < &buf[BUFSIZ - 1] && ch != '\n'); *cp = 0; if (buf[0] == '\01' || buf[0] == '\02') { if (iamremote == 0) (void)write(STDERR_FILENO, buf + 1, strlen(buf + 1)); if (buf[0] == '\02') exit(1); ++errs; continue; } if (buf[0] == 'E') { (void)write(rem, "", 1); return; } if (ch == '\n') *--cp = 0; #define getnum(t) (t) = 0; while (isdigit((unsigned char)*cp)) (t) = (t) * 10 + (*cp++ - '0'); cp = buf; if (*cp == 'T') { setimes++; cp++; getnum(mtime.tv_sec); if (*cp++ != ' ') SCREWUP("mtime.sec not delimited"); getnum(mtime.tv_usec); if (*cp++ != ' ') SCREWUP("mtime.usec not delimited"); getnum(atime.tv_sec); if (*cp++ != ' ') SCREWUP("atime.sec not delimited"); getnum(atime.tv_usec); if (*cp++ != '\0') SCREWUP("atime.usec not delimited"); (void)write(rem, "", 1); continue; } if (*cp != 'C' && *cp != 'D') { /* * Check for the case "rcp remote:foo\* local:bar". * In this case, the line "No match." can be returned * by the shell before the rcp command on the remote is * executed so the ^Aerror_message convention isn't * followed. */ if (first) { run_err("%s", cp); exit(1); } SCREWUP("expected control record"); } mode = 0; for (++cp; cp < buf + 5; cp++) { if (*cp < '0' || *cp > '7') SCREWUP("bad mode"); mode = (mode << 3) | (*cp - '0'); } if (*cp++ != ' ') SCREWUP("mode not delimited"); for (size = 0; isdigit((unsigned char)*cp);) size = size * 10 + (*cp++ - '0'); if (*cp++ != ' ') SCREWUP("size not delimited"); if (targisdir) { static char *namebuf; static int cursize; size_t need; need = strlen(targ) + strlen(cp) + 250; if (need > cursize) { if (!(namebuf = malloc(need))) run_err("%s", strerror(errno)); } (void)snprintf(namebuf, need, "%s%s%s", targ, *targ ? "/" : "", cp); np = namebuf; } else np = targ; exists = stat(np, &stb) == 0; if (buf[0] == 'D') { int mod_flag = pflag; if (exists) { if (!S_ISDIR(stb.st_mode)) { errno = ENOTDIR; goto bad; } if (pflag) (void)chmod(np, mode); } else { /* Handle copying from a read-only directory */ mod_flag = 1; if (mkdir(np, mode | S_IRWXU) < 0) goto bad; } vect[0] = np; sink(1, vect); if (setimes) { setimes = 0; if (utimes(np, tv) < 0) run_err("%s: set times: %s", np, strerror(errno)); } if (mod_flag) (void)chmod(np, mode); continue; } omode = mode; mode |= S_IWRITE; if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) { bad: run_err("%s: %s", np, strerror(errno)); continue; } (void)write(rem, "", 1); if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) { (void)close(ofd); continue; } cp = bp->buf; wrerr = NO; count = 0; for (i = 0; i < size; i += BUFSIZ) { amt = BUFSIZ; if (i + amt > size) amt = size - i; count += amt; do { j = read(rem, cp, (size_t)amt); if (j == -1) { run_err("%s", j ? strerror(errno) : "dropped connection"); exit(1); } amt -= j; cp += j; } while (amt > 0); if (count == bp->cnt) { /* Keep reading so we stay sync'd up. */ if (wrerr == NO) { j = write(ofd, bp->buf, (size_t)count); if (j != count) { wrerr = YES; wrerrno = j >= 0 ? EIO : errno; } } count = 0; cp = bp->buf; } } if (count != 0 && wrerr == NO && (j = write(ofd, bp->buf, (size_t)count)) != count) { wrerr = YES; wrerrno = j >= 0 ? EIO : errno; } if (ftruncate(ofd, size)) { run_err("%s: truncate: %s", np, strerror(errno)); wrerr = DISPLAYED; } if (pflag) { if (exists || omode != mode) if (fchmod(ofd, omode)) run_err("%s: set mode: %s", np, strerror(errno)); } else { if (!exists && omode != mode) if (fchmod(ofd, omode & ~mask)) run_err("%s: set mode: %s", np, strerror(errno)); } #ifndef __SVR4 if (setimes && wrerr == NO) { setimes = 0; if (futimes(ofd, tv) < 0) { run_err("%s: set times: %s", np, strerror(errno)); wrerr = DISPLAYED; } } #endif (void)close(ofd); #ifdef __SVR4 if (setimes && wrerr == NO) { setimes = 0; if (utimes(np, tv) < 0) { run_err("%s: set times: %s", np, strerror(errno)); wrerr = DISPLAYED; } } #endif (void)response(); switch(wrerr) { case YES: run_err("%s: write: %s", np, strerror(wrerrno)); break; case NO: (void)write(rem, "", 1); break; case DISPLAYED: break; } } screwup: run_err("protocol error: %s", why); exit(1); /* NOTREACHED */ }
void TcpServer::listen() { serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (serverSocket == -1) { logError("Could not create socket"); return; } if (bind(serverSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0) { logError("Could not bind socket"); return; } ::listen(serverSocket, 1); logDebug("Waiting for incoming connections..."); serverInstance = this; int clientSocket; struct sockaddr_in client; int c = sizeof(client); while ((clientSocket = accept(serverSocket, (struct sockaddr *) &client, (socklen_t*) &c))) { const char* message = MessageConversion::getHandshakeInitiation(); bool connectionRefused = false; StatusResponse response(false, nullptr); if (numCurrentConnections < maxConnections && sendMessage(clientSocket, message)) { char* receivedMessage = receiveMessage(clientSocket); if (receivedMessage != nullptr) { if (MessageConversion::isHandshakeCorrect(receivedMessage)) { logDebug("Connection accepted"); response.setSuccess(true); message = MessageConversion::convertResponseToJson( &response); if (sendMessage(clientSocket, message)) { TcpConnection* connection = new TcpConnection( clientSocket, this, spotifyRunner); connection->start(); this->currentConnections.push_back(connection); numCurrentConnections++; } delete[] message; } else { response.setMessage("Handshake incorrect."); message = MessageConversion::convertResponseToJson( &response); sendMessage(clientSocket, message); delete[] message; connectionRefused = true; } delete[] receivedMessage; } else { response.setMessage("Error during receiving of message"); message = MessageConversion::convertResponseToJson(&response); sendMessage(clientSocket, message); delete[] message; connectionRefused = true; } } else { response.setMessage("Too many connections"); message = MessageConversion::convertResponseToJson(&response); sendMessage(clientSocket, message); delete[] message; connectionRefused = true; } if (connectionRefused) { logDebug("Connection refused"); shutdown(clientSocket, SHUT_RDWR); } } shutdown(serverSocket, SHUT_RDWR); }
json request( const std::string& url, bool retry ) { // If we've already cached a response for this URL, skip the HTTP request if( m_cache.find( url ) != m_cache.end() ) { json cached( 200 ); cached.parse( m_cache[url] ); return cached; } CURL* curl = curl_easy_init(); if( curl == NULL ) { throw dto_exception( dto_exception::REQUEST_EXCEPTION, "Failed to Send Request" ); } CURLcode result; long status_code = 0; std::string read_buffer, header_buffer; curl_easy_setopt( curl, CURLOPT_URL, url.c_str() ); curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 1 ); curl_easy_setopt( curl, CURLOPT_WRITEDATA, &read_buffer ); curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, request_write_callback ); curl_easy_setopt( curl, CURLOPT_HEADERFUNCTION, &request_header_callback ); // our static function curl_easy_setopt( curl, CURLOPT_WRITEHEADER, &header_buffer ); result = curl_easy_perform( curl ); curl_easy_getinfo( curl, CURLINFO_RESPONSE_CODE, &status_code ); json response( status_code ); if( result == CURLE_OK && status_code == 200 ) { response.parse( read_buffer ); // Add the response to the cache m_cache[url] = read_buffer; } else if( status_code == 400 ) { throw dto_exception( dto_exception::REQUEST_EXCEPTION, "Bad Request" ); } else if( status_code == 401 ) { throw dto_exception( dto_exception::AUTHORIZATION_EXCEPTION, "Authorization Error - Check API Key" ); } else if( status_code == 429 ) { auto headers = parse_headers( header_buffer ); if( headers.find( "Retry-After" ) != headers.end() ) { try { std::chrono::seconds wait_for( std::stoi( headers["Retry-After"] ) ); if( retry ) { std::this_thread::sleep_for( wait_for ); return request( url, retry ); } throw dto_rate_exception( wait_for ); } catch( std::invalid_argument e ) { std::cerr << "Failed to parse Retry-After header, aborting request..." << std::endl; } } throw dto_exception( dto_exception::RATE_LIMIT_EXCEPTION, "Rate Limit Exceeded" ); } curl_easy_cleanup( curl ); return response; }
void YesNoDialog::on_no_button_clicked() { response(Gtk::RESPONSE_NO); }
bool WebSocketHandshake(nsTArray<nsCString>& aProtocolString) { nsresult rv; bool isWebSocket = false; nsCString version; nsCString wsKey; nsCString protocol; // Validate WebSocket client request. if (aProtocolString.Length() == 0) return false; // Check that the HTTP method is GET const char* HTTP_METHOD = "GET "; if (strncmp(aProtocolString[0].get(), HTTP_METHOD, strlen(HTTP_METHOD)) != 0) { return false; } for (uint32_t i = 1; i < aProtocolString.Length(); ++i) { const char* line = aProtocolString[i].get(); const char* prop_pos = strchr(line, ':'); if (prop_pos != nullptr) { nsCString key(line, prop_pos - line); nsCString value(prop_pos + 2); if (key.EqualsIgnoreCase("upgrade") && value.EqualsIgnoreCase("websocket")) { isWebSocket = true; } else if (key.EqualsIgnoreCase("sec-websocket-version")) { version = value; } else if (key.EqualsIgnoreCase("sec-websocket-key")) { wsKey = value; } else if (key.EqualsIgnoreCase("sec-websocket-protocol")) { protocol = value; } } } if (!isWebSocket) { return false; } if (!(version.Equals("7") || version.Equals("8") || version.Equals("13"))) { return false; } if (!(protocol.EqualsIgnoreCase("binary"))) { return false; } // Client request is valid. Start to generate and send server response. nsAutoCString guid("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); nsAutoCString res; SHA1Sum sha1; nsCString combined(wsKey + guid); sha1.update(combined.get(), combined.Length()); uint8_t digest[SHA1Sum::HashSize]; // SHA1 digests are 20 bytes long. sha1.finish(digest); nsCString newString(reinterpret_cast<char*>(digest), SHA1Sum::HashSize); Base64Encode(newString, res); nsCString response("HTTP/1.1 101 Switching Protocols\r\n"); response.Append("Upgrade: websocket\r\n"); response.Append("Connection: Upgrade\r\n"); response.Append(nsCString("Sec-WebSocket-Accept: ") + res + nsCString("\r\n")); response.Append("Sec-WebSocket-Protocol: binary\r\n\r\n"); uint32_t written = 0; uint32_t size = response.Length(); while (written < size) { uint32_t cnt; rv = mOutputStream->Write(const_cast<char*>(response.get()) + written, size - written, &cnt); if (NS_FAILED(rv)) return false; written += cnt; } mOutputStream->Flush(); return true; }
void YesNoDialog::on_yes_button_clicked() { response(Gtk::RESPONSE_YES); }
/// <summary> /// Uploads a temporarily stored image to imgur. /// </summary> /// <returns>Direct link to the image if succeess, empty string otherwise</returns> std::string Uploader::imgur() { FILE *fp; // File pointer unsigned char *buffer; // our buffer, a buffer of BYTE[] long fileLen; // Just the file length in bytes. // Convert the CStringW to a char* for fopen CString absPath = this->getTempFile(); const size_t __path = (absPath.GetLength() + 1) * 2; char *absPathChar = new char[__path]; size_t convertedCharsw = 0; wcstombs_s(&convertedCharsw, absPathChar, __path, absPath, _TRUNCATE); // Open the file in binary mode fp = fopen(absPathChar, "rb"); if(!fp) { AfxMessageBox(_T("Failed to open the screenshot file.")); return _EMPTY; } fseek(fp, 0, SEEK_END); // Jump to the end of the file fileLen = ftell(fp); // Get the size rewind(fp); // Jump back to the beginning of the file // Allocate memory buffer = (unsigned char *)malloc((fileLen)*sizeof(unsigned char)); if(!buffer) { AfxMessageBox(_T("Failed to allocate memory.")); return _EMPTY; } fread(buffer, fileLen, 1, fp); // Read in the entire file fclose(fp); // Close CStringA Dest = this->ToBase64(buffer, fileLen); // Base64 encode // Now construct an HTTP request. CString requestHeaders = _T("Content-Type: application/x-www-form-urlencoded\r\nAuthorization: Client-ID 3c1a6553ba0bbe4"); // Cast it to a CStringA which can then be used to convert to a char * CStringA postData("image=" + Dest); // Convert to char* otherwise the server drops requests, time_wasted = ~10 hours. const size_t newsizea = (postData.GetLength() + 1); char *postDataChar = new char[newsizea]; strcpy_s(postDataChar, newsizea, postData); // Spawn a session here CInternetSession session(NULL, 1, PRE_CONFIG_INTERNET_ACCESS, NULL, NULL, 0); if(!session) return _EMPTY; // Look up for 10 seconds session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10000); session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 3); INTERNET_PORT port = 443; // We are demanded to use HTTPS so // Open up the connection CHttpConnection *pConnection = session.GetHttpConnection(_T("api.imgur.com"), port); // Some self-explanatory flags. DWORD dwRequestFlags = INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_SECURE | INTERNET_DEFAULT_HTTPS_PORT; // Open up a connection CHttpFile *pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T("/3/image.xml"), NULL, 1, NULL, NULL, dwRequestFlags); pFile->AddRequestHeaders(requestHeaders); // Send the request BOOL result = pFile->SendRequest(requestHeaders, (LPVOID)postDataChar, strlen(postDataChar)); DWORD retCode; pFile->QueryInfoStatusCode(retCode); if(retCode != HTTP_STATUS_OK) { // API Failed AfxMessageBox(_T("API did not return 200 OK. Request failed.")); delete[] postDataChar;free(buffer); return _EMPTY; } // Grab the request now char *szBuff = new char[1024]; pFile->Read(szBuff, 1024); // Check out if it's empty or not if(!szBuff) { AfxMessageBox(_T("Failed to retrieve a response.")); delete []postDataChar;delete []szBuff;free(buffer); return _EMPTY; } // Construct this into a std string std::string response(szBuff); response = InBetween(response, "<link>", "</link>"); // Grab the direct link. // Cleanup delete[] szBuff; delete[] postDataChar; pFile->Close(); delete pFile; delete pConnection; free(buffer); session.Close(); return response; }
// ======= FTP thread handler ========= static void _thread_ftp(void*inContext) { (void)inContext; fd_set readset, wrset; struct timeval_t t_val; int k; uint32_t timeout = 0; uint8_t recv_tmo = 0; t_val.tv_sec = 0; t_val.tv_usec = 5000; timeout = mico_get_time(); ftp_log("\r\n[FTP trd] FTP THREAD STARTED\r\n"); // *** First we have to get IP address and connect the cmd socket char pIPstr[16]={0}; int err; k = 3; do { err = gethostbyname((char *)pDomain4Dns, (uint8_t *)pIPstr, 16); if (err != kNoErr) { k--; mico_thread_msleep(50); } }while ((err != kNoErr) && (k > 0)); if ((err == kNoErr) && (ftpCmdSocket != NULL)) { ftpCmdSocket->addr.s_ip = inet_addr(pIPstr); ftpCmdSocket->clientFlag = NO_ACTION; free(pDomain4Dns); pDomain4Dns=NULL; // Connect socket! char ip[17]; memset(ip, 0x00, 17); inet_ntoa(ip, ftpCmdSocket->addr.s_ip); ftp_log("[FTP cmd] Got IP: %s, connecting...\r\n", ip); struct sockaddr_t *paddr = &(ftpCmdSocket->addr); int slen = sizeof(ftpCmdSocket->addr); // _micoNotify will be called if connected connect(ftpCmdSocket->socket, paddr, slen); } else { ftp_log("[FTP dns] Get IP error\r\n"); goto terminate; } if (recvBuf == NULL) { recvBuf = malloc(MAX_RECV_LEN+4); memset(recvBuf, 0, MAX_RECV_LEN+4); } recvLen = 0; // =========================================================================== // Main Thread loop while (1) { mico_thread_msleep(5); if (ftpCmdSocket == NULL) goto terminate; if ( ((mico_get_time() - timeout) > MAX_FTP_TIMEOUT) || (((mico_get_time() - timeout) > 8000) && (!(status & FTP_LOGGED))) ) { // ** TIMEOUT ** ftp_log("[FTP trd] Timeout\r\n"); timeout = mico_get_time(); if ((status & FTP_LOGGED)) ftpCmdSocket->clientFlag = REQ_ACTION_QUIT; else ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT; } // ========== stage #1, Check cmd socket action requests =================== //REQ_ACTION_DISCONNECT if (ftpCmdSocket->clientFlag == REQ_ACTION_DISCONNECT) { ftpCmdSocket->clientFlag = NO_ACTION; closeDataSocket(); ftp_log("[FTP cmd] Socket disconnected\r\n"); if (ftpCmdSocket->disconnect_cb != LUA_NOREF) { queue_msg_t msg; msg.L = gL; msg.source = onFTP; msg.para1 = 0; msg.para2 = ftpCmdSocket->disconnect_cb; mico_rtos_push_to_queue( &os_queue, &msg, 0); } closeCmdSocket(0); continue; } //REQ_ACTION_QUIT if (ftpCmdSocket->clientFlag == REQ_ACTION_QUIT) { if ((status & FTP_LOGGED)) { ftpCmdSocket->clientFlag = NO_ACTION; ftp_log("[FTP cmd] Quit command\r\n"); if (_send("QUIT\r\n", 6) <= 0) { ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT; } } else ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT; continue; } if (!(status & FTP_CONNECTED)) continue; //-------------------------------------- //REQ_ACTION_LIST, REQ_ACTION_RECV, REQ_ACTION_SEND else if ((ftpCmdSocket->clientFlag == REQ_ACTION_LIST) || (ftpCmdSocket->clientFlag == REQ_ACTION_RECV) || (ftpCmdSocket->clientFlag == REQ_ACTION_SEND)) { ftpCmdSocket->clientLastFlag = ftpCmdSocket->clientFlag; ftpCmdSocket->clientFlag = NO_ACTION; _send("PASV\r\n", 6); } //REQ_ACTION_DOLIST else if (ftpCmdSocket->clientFlag == REQ_ACTION_DOLIST) { ftpCmdSocket->clientFlag = NO_ACTION; int res; if (ftpfile != NULL) { char tmps[100]; if (list_type == 1) sprintf(tmps,"NLST %s\r\n", ftpfile); else sprintf(tmps,"LIST %s\r\n", ftpfile); res = _send(&tmps[0], strlen(ftpfile)+7); free(ftpfile); ftpfile = NULL; } else { if (list_type == 1) res = _send("NLST\r\n", 6); else res = _send("LIST\r\n", 6); } if (res > 0) status |= FTP_LISTING; else { ftp_log("[FTP cmd] LIST command failed.\r\n"); } } //REQ_ACTION_DORECV else if (ftpCmdSocket->clientFlag == REQ_ACTION_DORECV) { ftpCmdSocket->clientFlag = NO_ACTION; char tmps[100]; sprintf(tmps,"RETR %s\r\n", ftpfile); int res = _send(&tmps[0], strlen(ftpfile)+7); if (res > 0) { status |= FTP_RECEIVING; file_status = 0; } else { ftp_log("[FTP cmd] RETR command failed.\r\n"); file_status = -4; } } //REQ_ACTION_DOSEND else if (ftpCmdSocket->clientFlag == REQ_ACTION_DOSEND) { ftpCmdSocket->clientFlag = NO_ACTION; char tmps[100]; if ((send_type & SEND_APPEND)) sprintf(tmps,"APPE %s\r\n", ftpfile); else sprintf(tmps,"STOR %s\r\n", ftpfile); int res = _send(&tmps[0], strlen(ftpfile)+7); if (res > 0) { file_status = 0; } else { ftp_log("[FTP cmd] STOR/APPE command failed.\r\n"); file_status = -4; } } //REQ_ACTION_CHDIR else if (ftpCmdSocket->clientFlag == REQ_ACTION_CHDIR) { ftpCmdSocket->clientFlag = NO_ACTION; if (ftpfile != NULL) { char tmps[100]; sprintf(tmps,"CWD %s\r\n", ftpfile); _send(&tmps[0], strlen(ftpfile)+6); free(ftpfile); ftpfile = NULL; } else { _send("PWD\r\n", 5); } } //REQ_ACTION_LOGGED else if (ftpCmdSocket->clientFlag == REQ_ACTION_LOGGED) { ftpCmdSocket->clientFlag=NO_ACTION; if (ftpCmdSocket->logon_cb != LUA_NOREF) { queue_msg_t msg; msg.L = gL; msg.source = onFTP; msg.para1 = 1; msg.para3 = NULL; msg.para2 = ftpCmdSocket->logon_cb; mico_rtos_push_to_queue( &os_queue, &msg, 0); } } //REQ_ACTION_LIST_RECEIVED else if (ftpCmdSocket->clientFlag == REQ_ACTION_LIST_RECEIVED) { ftpCmdSocket->clientFlag=NO_ACTION; if (ftpCmdSocket->list_cb != LUA_NOREF) { queue_msg_t msg; msg.L = gL; msg.source = onFTP; msg.para1 = recvDataLen; msg.para2 = ftpCmdSocket->list_cb; msg.para3 = (uint8_t*)malloc(recvDataLen+4); if (msg.para3 != NULL) memcpy((char*)msg.para3, recvDataBuf, recvDataLen); mico_rtos_push_to_queue( &os_queue, &msg, 0); } } //REQ_ACTION_RECEIVED else if (ftpCmdSocket->clientFlag == REQ_ACTION_RECEIVED) { ftpCmdSocket->clientFlag=NO_ACTION; if (ftpCmdSocket->received_cb != LUA_NOREF) { queue_msg_t msg; msg.L = gL; msg.source = onFTP; msg.para1 = file_status; msg.para3 = NULL; if (recv_type == RECV_TOSTRING) { msg.para3 = (uint8_t*)malloc(recvDataLen+4); if (msg.para3 != NULL) memcpy((char*)msg.para3, recvDataBuf, recvDataLen); } msg.para2 = ftpCmdSocket->received_cb; mico_rtos_push_to_queue( &os_queue, &msg, 0); } } //REQ_ACTION_SENT else if (ftpCmdSocket->clientFlag == REQ_ACTION_SENT) { ftpCmdSocket->clientFlag=NO_ACTION; if (ftpCmdSocket->sent_cb != LUA_NOREF) { queue_msg_t msg; msg.L = gL; msg.source = onFTP; msg.para1 = file_status; msg.para3 = NULL; msg.para2 = ftpCmdSocket->sent_cb; mico_rtos_push_to_queue( &os_queue, &msg, 0); } } // ========== stage 2, check data send ===================================== if ((ftpDataSocket != NULL) && ((status & FTP_SENDING))) { FD_ZERO(&wrset); FD_SET(ftpDataSocket->socket, &wrset); // check socket state select(ftpDataSocket->socket+1, NULL, &wrset, NULL, &t_val); if (FD_ISSET(ftpDataSocket->socket, &wrset)) { int err; if ((send_type & SEND_STRING)) err = _sendString(); else err = _sendFile(); if (err != 0) { closeDataSocket(); // close file; if (file_fd != FILE_NOT_OPENED) { SPIFFS_close(&fs,file_fd); file_fd = FILE_NOT_OPENED; ftp_log("\r\n[FTP dta] Data file closed\r\n"); } data_done = 1; status &= ~FTP_SENDING; ftpCmdSocket->clientFlag = REQ_ACTION_SENT; } continue; } } // ========== stage 3, check receive&disconnect ============================ FD_ZERO(&readset); // ** select sockets to monitor for receive or disconnect int maxfd = ftpCmdSocket->socket; FD_SET(ftpCmdSocket->socket, &readset); if ( (ftpDataSocket != NULL) && ((status & FTP_DATACONNECTED)) ) { if (ftpDataSocket->socket > maxfd) maxfd = ftpDataSocket->socket; FD_SET(ftpDataSocket->socket, &readset); } // ** check sockets state select(maxfd+1, &readset, NULL, NULL, &t_val); // ** Check COMMAND socket if (FD_ISSET(ftpCmdSocket->socket, &readset)) { // read received data to buffer int rcv_len; if ((MAX_RECV_LEN-recvLen) > 1) { rcv_len = recv(ftpCmdSocket->socket, (recvBuf+recvLen), MAX_RECV_LEN-recvLen-1, 0); } else { // buffer full, ignore received bytes char tmpb[16]; rcv_len = recv(ftpCmdSocket->socket, &tmpb[0], 16, 0); } if (rcv_len <= 0) { // failed ftp_log("\r\n[FTP cmd] Disconnect!\r\n"); ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT; continue; } recvLen += rcv_len; _checkCmdResponse(); // leave only the last line in buffer timeout = mico_get_time(); recv_tmo = 0; } // ** Check DATA socket if ( (ftpDataSocket != NULL) && ((status & FTP_DATACONNECTED)) ) { if (FD_ISSET(ftpDataSocket->socket, &readset)) { // read received data to buffer int rcv_len = recv(ftpDataSocket->socket, (recvDataBuf+recvDataLen), max_recv_datalen-recvDataLen-1, 0); if (rcv_len <= 0) { // failed if (!(status & (FTP_RECEIVING | FTP_LISTING))) { ftp_log("\r\n[FTP dta] Disconnect!\r\n"); closeDataSocket(); file_status = -9; data_done = 1; } continue; } else { if ((status & FTP_RECEIVING) && (recv_type == RECV_TOFILE)) { // === write received data to file === recvDataLen = rcv_len; _saveData(0); recvDataLen = 0; } else if ((status & FTP_LISTING) || ((status & FTP_RECEIVING) && (recv_type == RECV_TOSTRING))) { if ((recvDataLen + rcv_len) < (max_recv_datalen-16)) recvDataLen += rcv_len; else recvDataLen = max_recv_datalen-16; *(recvDataBuf + recvDataLen) = '\0'; } } timeout = mico_get_time(); recv_tmo = 0; } } // ===== nothing received ================================================== recv_tmo++; if (recv_tmo < 10) continue; recv_tmo = 0; // == Check if something was received from Command socket == if (recvLen > 0) { // == Analize response === response(); recvLen = 0; memset(recvBuf, 0, MAX_RECV_LEN); } // == Check if Data socket was receiving == if ((status & (FTP_RECEIVING | FTP_LISTING))) { // Finish all operattions on data socket if ((status & FTP_RECEIVING) && (recv_type == RECV_TOFILE)) { _saveData(1); recvDataLen = 0; } else { if ((status & FTP_RECEIVING) && (recv_type == RECV_TOSTRING)) { file_status = recvDataLen; } ftp_log("[FTP dta] Data received (%d)\r\n", recvDataLen); } if ((status & FTP_LISTING)) { status &= ~FTP_LISTING; ftpCmdSocket->clientFlag = REQ_ACTION_LIST_RECEIVED; } if ((status & FTP_RECEIVING)) { status &= ~FTP_RECEIVING; ftpCmdSocket->clientFlag = REQ_ACTION_RECEIVED; } // Close data socket closeDataSocket(); data_done = 1; } } // while terminate: _ftp_deinit(0); ftp_log("\r\n[FTP trd] FTP THREAD TERMINATED\r\n"); ftp_thread_is_started = false; mico_rtos_delete_thread( NULL ); }
void RemoteData::retreiveSIMBAD(QNetworkReply* reply) { qDebug() << "Retreiving from SIMBAD ..."; QByteArray response(reply->readAll()); qDebug() << response; }
bool EngineEffect::processEffectsRequest(const EffectsRequest& message, EffectsResponsePipe* pResponsePipe) { EngineEffectParameter* pParameter = NULL; EffectsResponse response(message); switch (message.type) { case EffectsRequest::SET_EFFECT_PARAMETERS: if (kEffectDebugOutput) { qDebug() << debugString() << "SET_EFFECT_PARAMETERS" << "enabled" << message.SetEffectParameters.enabled; } m_bEnabled = message.SetEffectParameters.enabled; response.success = true; pResponsePipe->writeMessages(&response, 1); return true; break; case EffectsRequest::SET_PARAMETER_PARAMETERS: if (kEffectDebugOutput) { qDebug() << debugString() << "SET_PARAMETER_PARAMETERS" << "parameter" << message.SetParameterParameters.iParameter << "minimum" << message.minimum << "maximum" << message.maximum << "default_value" << message.default_value << "value" << message.value; } pParameter = m_parameters.value( message.SetParameterParameters.iParameter, NULL); if (pParameter) { pParameter->setMinimum(message.minimum); pParameter->setMaximum(message.maximum); pParameter->setDefaultValue(message.default_value); pParameter->setValue(message.value); response.success = true; } else { response.success = false; response.status = EffectsResponse::NO_SUCH_PARAMETER; } pResponsePipe->writeMessages(&response, 1); return true; case EffectsRequest::SET_PARAMETER_BUTTON_PARAMETERS: if (kEffectDebugOutput) { qDebug() << debugString() << "SET_BUTTON_PARAMETER_PARAMETERS" << "parameter" << message.SetParameterParameters.iParameter << "minimum" << message.minimum << "maximum" << message.maximum << "default_value" << message.default_value << "value" << message.value; } pParameter = m_buttonParameters.value( message.SetParameterParameters.iParameter, NULL); if (pParameter) { pParameter->setMinimum(message.minimum); pParameter->setMaximum(message.maximum); pParameter->setDefaultValue(message.default_value); pParameter->setValue(message.value); response.success = true; } else { response.success = false; response.status = EffectsResponse::NO_SUCH_PARAMETER; } pResponsePipe->writeMessages(&response, 1); return true; default: break; } return false; }
bool SASLAuthFeature::xmppStanzaIn(IXmppStream *AXmppStream, Stanza &AStanza, int AOrder) { if (AXmppStream==FXmppStream && AOrder==XSHO_XMPP_FEATURE) { if (AStanza.kind() == "challenge") { QByteArray challengeData = QByteArray::fromBase64(AStanza.element().text().toLatin1()); LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth challenge received: %1").arg(QString::fromUtf8(challengeData))); QMap<QByteArray, QByteArray> responseMap; QMap<QByteArray, QByteArray> challengeMap = parseChallenge(challengeData); if (challengeMap.value("qop") == "auth") { QByteArray randBytes(32,' '); for (int i=0; i<randBytes.size(); i++) randBytes[i] = (char) (256.0 * qrand() / (RAND_MAX + 1.0)); responseMap["cnonce"] = randBytes.toHex(); if (challengeMap.contains("realm")) responseMap["realm"] = challengeMap.value("realm"); else responseMap["realm"] = FXmppStream->streamJid().pDomain().toUtf8(); responseMap["username"] = FXmppStream->streamJid().pNode().toUtf8(); responseMap["nonce"] = challengeMap.value("nonce"); responseMap["nc"] = "00000001"; responseMap["qop"] = "auth"; responseMap["digest-uri"] = QString("xmpp/%1").arg(FXmppStream->streamJid().pDomain()).toUtf8(); responseMap["charset"] = "utf-8"; responseMap["response"] = getResponseValue(responseMap,FXmppStream->password()); } QByteArray responseData = serializeResponse(responseMap); Stanza response("response",NS_FEATURE_SASL); response.element().appendChild(response.createTextNode(responseData.toBase64())); FXmppStream->sendStanza(response); LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth response sent: %1").arg(QString::fromUtf8(responseData))); } else { FXmppStream->removeXmppStanzaHandler(XSHO_XMPP_FEATURE,this); if (AStanza.kind() == "success") { LOG_STRM_INFO(FXmppStream->streamJid(),"Authorization successes"); deleteLater(); emit finished(true); } else if (AStanza.kind() == "failure") { XmppSaslError err(AStanza.element()); LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization failed: %1").arg(err.condition())); emit error(err); } else { XmppError err(IERR_SASL_AUTH_INVALID_RESPONSE); LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization error: Invalid stanza kind=%1").arg(AStanza.kind())); emit error(err); } } return true; } return false; }
void file_server::main(std::string file_name) { std::string path; if(!check_in_document_root(file_name,path)) { show404(); return; } int s=file_mode(path); if((s & S_IFDIR)) { std::string path2; int mode_2=0; bool have_index = check_in_document_root(file_name+"/" + index_file_ ,path2); if(have_index) { mode_2 = file_mode(path2); have_index = (mode_2 & S_IFREG) != 0; } if( !file_name.empty() && file_name[file_name.size()-1]!='/' // not ending with "/" as should && (have_index || list_directories_) ) { response().set_redirect_header(file_name + "/"); response().out()<<std::flush; return; } if(have_index) { path = path2; s=mode_2; } else { if(list_directories_) list_dir(file_name,path); else show404(); return; } } if(!(s & S_IFREG)) { show404(); return; } std::string ext; size_t pos = path.rfind('.'); if(pos != std::string::npos) ext=path.substr(pos); mime_type::const_iterator p=mime_.find(ext); if(p!=mime_.end()) response().content_type(p->second); else response().content_type("application/octet-stream"); if(!allow_deflate_) { response().io_mode(http::response::nogzip); } booster::nowide::ifstream file(path.c_str(),std::ios_base::binary); if(!file) { show404(); return; } response().out()<<file.rdbuf(); // write stream to stream }
void source(int argc, char *argv[]) { struct stat stb; static BUF buffer; BUF *bp; off_t i; off_t amt; int fd, haderr, indx, result; char *last, *name, buf[BUFSIZ]; for (indx = 0; indx < argc; ++indx) { name = argv[indx]; if ((fd = open(name, O_RDONLY, 0)) < 0) goto syserr; if (fstat(fd, &stb)) { syserr: run_err("%s: %s", name, strerror(errno)); goto next; } switch (stb.st_mode & S_IFMT) { case S_IFREG: break; case S_IFDIR: if (iamrecursive) { rsource(name, &stb); goto next; } /* FALLTHROUGH */ default: run_err("%s: not a regular file", name); goto next; } if ((last = strrchr(name, '/')) == NULL) last = name; else ++last; if (pflag) { /* * Make it compatible with possible future * versions expecting microseconds. */ (void)snprintf(buf, sizeof(buf), "T%lld %ld %lld %ld\n", (long long)stb.st_mtimespec.tv_sec, (long)stb.st_mtimespec.tv_nsec / 1000, (long long)stb.st_atimespec.tv_sec, (long)stb.st_atimespec.tv_nsec / 1000); (void)write(rem, buf, strlen(buf)); if (response() < 0) goto next; } #define RCPMODEMASK (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO) (void)snprintf(buf, sizeof(buf), "C%04o %lld %s\n", stb.st_mode & RCPMODEMASK, (long long)stb.st_size, last); (void)write(rem, buf, strlen(buf)); if (response() < 0) goto next; if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) { next: (void)close(fd); continue; } /* Keep writing after an error so that we stay sync'd up. */ haderr = 0; for (i = 0; i < stb.st_size; i += bp->cnt) { amt = bp->cnt; if (i + amt > stb.st_size) amt = stb.st_size - i; if (!haderr) { result = read(fd, bp->buf, (size_t)amt); if (result != amt) haderr = result >= 0 ? EIO : errno; } if (haderr) (void)write(rem, bp->buf, (size_t)amt); else { result = write(rem, bp->buf, (size_t)amt); if (result != amt) haderr = result >= 0 ? EIO : errno; } } if (close(fd) && !haderr) haderr = errno; if (!haderr) (void)write(rem, "", 1); else run_err("%s: %s", name, strerror(haderr)); (void)response(); } }
void talking(int s, string speech) // PC speech { /* Unicode speech format byte = char, short = char[2], int = char[4], wchar = char[2] = unicode character Message Sent By Client: 0xAD - Unicode Speech Request BYTE cmd(0xAD) short msgsize 1, 2 byte type(0 = say, 2 = emote, 8 = whisper, 9 = yell) 3 short color 4, 5 short font 6, 7 BYTE[4] lang(null terminated, "enu " for US english.) 8, 9, 10, 11 wchar[?] text(null terminated, ?=(msgsize - 12)/2) 13 Message Sent By Server: 0xAE - Unicode Speech Message BYTE cmd(0xAE) 0 short msgsize 1, 2 BYTE[4] ser(ser of speaker, all 0xFF if none) 3, 4, 5, 6 BYTE[2] model(id of speaker, all 0xFF if none)7, 8 BYTE type 9 short color 10, 11 short font 12, 13 BYTE[4] language(same as before) 14, 15, 16, 17 BYTE[30] speaker's name(normal chars, not wchars) 18 - 48 WCHAR[?] text(null terminated, ?=(msgsize - 48)/2 Importnat note regarding 0xAD: since 2.0.7 clients send between lang and text 0...10 bytes. (we can ignore them safely) Those bytes get cut out in network.cpp correctly, so the buffer THIS functions sees is actualy what is written above. The actual data the client sends is differently though. Just noted this to prevent from debugging if somebody finds out client data doesn't fit to this description (LB) */ char nonuni[512]; unsigned char talk2[19]; char unicodetext[512]; char lang[4]; char name[50] = {0,}; // it **IS** important to 0 out the remaining gaps P_CHAR pc_currchar = MAKE_CHARREF_LR(currchar[s]); strcpy(nonuni, speech.c_str()); // len+font+color+type = same postion for non unicode and unicode speech packets // but 8 ... x DIFFER a lot for unicode and non unicode packets !!! // memset(name, 0, 30); strncpy(name, pc_currchar->name, 50); char speech_type = buffer[s][3]; UI16 speech_color = ShortFromCharPtr(&buffer[s][4]); char speech_fontbyte1 = buffer[s][6]; char speech_fontbyte2 = buffer[s][7]; int ucl = ( strlen ( nonuni ) * 2 ) + 2 ; int tl = ucl + 48 ; if (pc_currchar->unicode) { lang[0]=buffer[s][8]; lang[1]=buffer[s][9]; lang[2]=buffer[s][10]; lang[3]=buffer[s][11]; memcpy(unicodetext, &buffer[s][12], ucl); } else { lang[0]='E'; lang[1]='N'; lang[2]='U'; lang[3]=0; char2wchar(nonuni); // we are sending unicode response no matter if the speech request was non unicode or not // so convert to uni-text in case of non unicode memcpy(unicodetext, temp, ucl); } /* clConsole.send("speech: %s\n",nonuni); clConsole.send("unicode speech:\n"); for ( a=0; a < tl-48; a++) clConsole.send("%02i ",unicodetext[a]); clConsole.send("\n");*/ //// Very important: do not use buffer[s][] anymore in this function !!!! //// unicode text that gets send is in unicodetext, nonunicode text for normal string processing in non uni code if (InputSpeech(nonuni, pc_currchar, s)) // handle things like renaming or describing an item return; if (pc_currchar->squelched) // not allowed to talk { sysmessage(s, "You have been squelched."); return; } // AntiChrist pc_currchar->unhide(); if (nonuni[0] == SrvParms->commandPrefix ) { Commands->Command(s, speech); return; } if ( speech_type == '\x09' && pc_currchar->canBroadcast() ) { broadcast(s); return; } talk2[0] = 0xAE; ShortToCharPtr(tl, &talk2[1]); LongToCharPtr(pc_currchar->serial, &talk2[3]); ShortToCharPtr(pc_currchar->id(), &talk2[7]); talk2[9] = speech_type; ShortToCharPtr(speech_color, &talk2[10]); talk2[12] = speech_fontbyte1; talk2[13] = speech_fontbyte2; talk2[14] = lang[0]; talk2[15] = lang[1]; talk2[16] = lang[2]; talk2[17] = lang[3]; Xsend(s, talk2, 18); Xsend(s, name, 30); Xsend(s, unicodetext, ucl); if (speech_type == 0 || speech_type == 2) { pc_currchar->saycolor = speech_color; } if (SrvParms->speech_log) // Logging bugfixed by LB { char temp2[512]; sprintf(temp2, "%s.speech_log", pc_currchar->name); sprintf((char*)temp, "%s [%x] [%i] said:\n%s\n", pc_currchar->name, pc_currchar->serial, pc_currchar->account, nonuni); savelog((char*)temp, (char*)temp2); } char SpeechUpr[512]; strcpy(SpeechUpr, nonuni); strupr(SpeechUpr); if (!strcmp(SpeechUpr, "I RESIGN FROM MY GUILD")) Guilds->Resign(s); if (response(s,pc_currchar,SpeechUpr)) return; // Vendor responded already if (strstr(SpeechUpr, "GUARDS")) callguards(currchar[s]); if (Boats->Speech(s, SpeechUpr)) return; house_speech(s, SpeechUpr); // houses crackerjack 8/12/99 int i, j; for (i = 0; i < now; i++) { // AntiChrist - don't check line of sight for talking!!! if (inrange1(i, s) && perm[i] && i!=s)//&&line_of_sight(s, pc_currchar->pos.x, pc_currchar->pos.y, pc_currchar->pos.z, chars[currchar[i]].x, chars[currchar[i]].y, chars[currchar[i]].z, WALLS_CHIMNEYS + DOORS + FLOORS_FLAT_ROOFING)) { Xsend(i, talk2, 18); Xsend(i, name, 30); if (pc_currchar->dead // a ghost is talking && !chars[currchar[i]].dead // Ghost can talk normally to other ghosts && !chars[currchar[i]].isGMorCounselor()// GM/Counselors can see ghosts talking always Seers? && chars[currchar[i]].spiritspeaktimer == 0) { unsigned char ghostspeech[512]; memcpy(&ghostspeech, &unicodetext, ucl); for (j = 1; j < ucl-2 ; j += 2) // -2: dont override /0 /0 terminator ! { if (ghostspeech[j] != 32) // keep the blanks ghostspeech[j] = (ghostspeech[j]%2) ? 'O' : 'o'; } Xsend(i, ghostspeech, ucl); // send 'ghostified' speech "OOoooOo Ooo" } else Xsend(i, unicodetext, ucl); } } if (pc_currchar->dead) return; // this makes it so npcs do not respond to dead people cChar* pc=NULL; cChar* pNpc=NULL; cRegion::RegionIterator4Chars ri(pc_currchar->pos); for (ri.Begin(); (pc=ri.GetData()) != ri.End(); ri++) { if (!pc->isSameAs(pc_currchar) && pc->isNpc() && pc->dist(pc_currchar) <= 2) { pNpc=pc; break; } } if (pNpc && pNpc->speech) { Script *pScp=i_scripts[speech_script]; if (!pScp->Open()) return; char sect[512]; sprintf(sect, "SPEECH %i", pNpc->speech); if (!pScp->find(sect)) { pScp->Close(); return; } int match = 0; strcpy(sect, "NO DEFAULT TEXT DEFINED"); int loopexit = 0; do { pScp->NextLineSplitted(); if (script1[0] != '}') { if (!(strcmp("DEFAULT", (char*)script1))) { strcpy(sect, (char*)script2); } if (!(strcmp("ON", (char*)script1))) { char scpUpr[500]; strcpy(scpUpr,script2); strupr(scpUpr); if (strstr(SpeechUpr,scpUpr)) match=1; } if (!(strcmp("SAY", (char*)script1))) { if (match == 1) { npctalk(s, pNpc, (char*)script2, 0); match = 2; } } if (!(strcmp("TRG", (char*)script1))) // Added by Magius(CHE) § { if (match == 1) { pNpc->trigger = str2num(script2); scpMark m=pScp->Suspend(); triggernpc(s, DEREF_P_CHAR(pNpc), 1); pScp->Resume(m); strcpy((char*)script1, "DUMMY"); match = 2; } } } } while (script1[0] != '}' && (++loopexit < MAXLOOPS)); if (match == 0) { npctalk(s, pNpc, sect, 0); } pScp->Close(); } }
int main(int argc, char *argv[]) { struct servent *sp; int ch, fflag, tflag; char *targ; const char *shell; setprogname(argv[0]); (void)setlocale(LC_ALL, ""); fflag = tflag = 0; while ((ch = getopt(argc, argv, OPTIONS)) != -1) switch(ch) { /* User-visible flags. */ case '4': family = AF_INET; break; case '6': family = AF_INET6; break; case 'K': break; case 'p': pflag = 1; break; case 'r': iamrecursive = 1; break; /* Server options. */ case 'd': targetshouldbedirectory = 1; break; case 'f': /* "from" */ iamremote = 1; fflag = 1; break; case 't': /* "to" */ iamremote = 1; tflag = 1; break; case '?': default: usage(); } argc -= optind; argv += optind; sp = getservbyname(shell = "shell", "tcp"); if (sp == NULL) errx(1, "%s/tcp: unknown service", shell); port = sp->s_port; if ((pwd = getpwuid(userid = getuid())) == NULL) errx(1, "unknown user %d", (int)userid); if ((pwname = strdup(pwd->pw_name)) == NULL) err(1, NULL); rem = STDIN_FILENO; /* XXX */ if (fflag) { /* Follow "protocol", send data. */ (void)response(); source(argc, argv); exit(errs); } if (tflag) { /* Receive data. */ sink(argc, argv); exit(errs); } if (argc < 2) usage(); if (argc > 2) targetshouldbedirectory = 1; rem = -1; /* Command to be executed on remote system using "rsh". */ (void)snprintf(cmd, sizeof(cmd), "rcp%s%s%s", iamrecursive ? " -r" : "", pflag ? " -p" : "", targetshouldbedirectory ? " -d" : ""); (void)signal(SIGPIPE, lostconn); if ((targ = colon(argv[argc - 1])) != NULL)/* Dest is remote host. */ toremote(targ, argc, argv); else { tolocal(argc, argv); /* Dest is local host. */ if (targetshouldbedirectory) verifydir(argv[argc - 1]); } exit(errs); /* NOTREACHED */ }
/** * This is just a wrapper for the R-to-C interface. * The actual function is run_EM_one_iteration() (see definition.hpp) */ extern "C" void EM_one_iteration( // Parameters: INPUT and OUTPUT double *A_data, const int *A_dim, double *B_data, const int *B_dim, double *b_data, const int *b_dim, double *alpha_data, const int *alpha_dim, double *beta_data, const int *beta_dim, double *var_x, double *var_y, double *var_z, // vectors of length: nApps double *var_u, // scalar // Posterior mean of factors: OUTPUT double *u, // matrix of size nUsers x nGlobalFactors double *z_data, const int *z_dim, // Posterior variance for logistic regression: OUTPUT double *xMean_var, const int *xMean_var_length, // 0 or feature_nrow double *yMean_var, const int *yMean_var_length, // 0 or response_nrow // Feature table: INPUT const int *feature_user, const int *feature_app, const int *feature_index, const double *feature_x, const double *feature_w, const int *feature_nrow, const int *feature_has_w, // Response table: INPUT const int *response_user, const int *response_app, const int *response_item, const double *response_y, const double *response_w, const int *response_nrow, const int *response_has_w, // Ridge regression parameters: INPUT const double *ridge_lambda, const int *ridge_lambda_length, // ridge_lambda for A, B, beta // Size information: INPUT const int *nApps, const int *nUsers, const int *nGlobalFactors, // scalars const int *nFeatures, const int *nItems, const int *nLocalFactors, // vectors of length: nApps // Others const int *option, const int *verbose, const int *debug // scalars ){ if((*xMean_var_length) != 0 && (*xMean_var_length) != (*feature_nrow)) STOP2("length(xMean_var) = %d, nrow(feature) = %d: They should be the same", *xMean_var_length, *feature_nrow); if((*yMean_var_length) != 0 && (*yMean_var_length) != (*response_nrow)) STOP2("length(yMean_var) = %d, nrow(response) = %d: They should be the same", *yMean_var_length, *response_nrow); ListOfMatrices A(A_data, A_dim), B(B_data, B_dim), b(b_data, b_dim), alpha(alpha_data, alpha_dim), beta(beta_data, beta_dim), z(z_data, z_dim); Matrix_ColumnMajor u_matrix; u_matrix.wrap(u, *nUsers, *nGlobalFactors); ObsTable feature(feature_user, feature_app, feature_index, feature_x, feature_w, *feature_nrow, *feature_has_w, *nUsers), response(response_user, response_app, response_item, response_y, response_w, *response_nrow, *response_has_w, *nUsers); if(*verbose >= 100){ // Print the input data for debugging printf("---------------------------------------------------------------\n" "INPUT DATA to EM_one_iteration (C function)\n" "(option:%d verbose:%d debug:%d\n" "---------------------------------------------------------------\n", *option, *verbose, *debug); printf("nApps=%d, nUsers=%d, nGlobalFeatures=%d\n", *nApps, *nUsers, *nGlobalFactors); printf("nFeatures:\n"); print_intVector(" ", nFeatures, *nApps); printf("nItems:\n"); print_intVector(" ", nItems, *nApps); printf("nLocalFactors:\n"); print_intVector(" ", nLocalFactors, *nApps); printf("Feature table:\n"); feature.print(" "); printf("Response table:\n"); response.print(" "); printf("param$A:\n"); A.print(); printf("param$B:\n"); B.print(); printf("param$b:\n"); b.print(); printf("param$alpha:\n"); alpha.print(); printf("param$beta:\n"); beta.print(); printf("param$var_x:\n"); print_vector(" ", var_x, *nApps); printf("param$var_y:\n"); print_vector(" ", var_y, *nApps); printf("param$var_z:\n"); print_vector(" ", var_z, *nApps); printf("param$var_u:\n"); print_vector(" ", var_u, 1); printf("factor$u:\n"); u_matrix.print(" "); printf("factor$z:\n"); z.print(); printf("ridge.lambda:\n"); print_vector(" ", ridge_lambda, *ridge_lambda_length); } if(*ridge_lambda_length != 3) STOP1("length(redige.lambda) = %d (should be 3)", *ridge_lambda_length); run_EM_one_iteration( A, B, b, alpha, beta, var_x, var_y, var_z, *var_u, u_matrix, z, xMean_var, *xMean_var_length, yMean_var, *yMean_var_length, feature, response, *nApps, *nUsers, *nGlobalFactors, nFeatures, nItems, nLocalFactors, ridge_lambda[0], ridge_lambda[1], ridge_lambda[2], *option, *verbose, *debug ); }
void toremote(char *targ, int argc, char **argv) { char *bp, *host, *src, *suser, *thost, *tuser, *arg; arglist alist; int i; u_int j; memset(&alist, '\0', sizeof(alist)); alist.list = NULL; *targ++ = 0; if (*targ == 0) targ = "."; arg = xstrdup(argv[argc - 1]); if ((thost = strrchr(arg, '@'))) { /* user@host */ *thost++ = 0; tuser = arg; if (*tuser == '\0') tuser = NULL; } else { thost = arg; tuser = NULL; } if (tuser != NULL && !okname(tuser)) { xfree(arg); return; } for (i = 0; i < argc - 1; i++) { src = colon(argv[i]); if (src && throughlocal) { /* extended remote to remote */ *src++ = 0; if (*src == 0) src = "."; host = strrchr(argv[i], '@'); if (host) { *host++ = 0; host = cleanhostname(host); suser = argv[i]; if (*suser == '\0') suser = pwd->pw_name; else if (!okname(suser)) continue; } else { host = cleanhostname(argv[i]); suser = NULL; } xasprintf(&bp, "%s -f -- %s", cmd, src); if (do_cmd(host, suser, bp, &remin, &remout) < 0) exit(1); (void) xfree(bp); host = cleanhostname(thost); xasprintf(&bp, "%s -t -- %s", cmd, targ); if (do_cmd2(host, tuser, bp, remin, remout) < 0) exit(1); (void) xfree(bp); (void) close(remin); (void) close(remout); remin = remout = -1; } else if (src) { /* standard remote to remote */ freeargs(&alist); addargs(&alist, "%s", ssh_program); addargs(&alist, "-x"); addargs(&alist, "-oClearAllForwardings=yes"); addargs(&alist, "-n"); for (j = 0; j < remote_remote_args.num; j++) { addargs(&alist, "%s", remote_remote_args.list[j]); } *src++ = 0; if (*src == 0) src = "."; host = strrchr(argv[i], '@'); if (host) { *host++ = 0; host = cleanhostname(host); suser = argv[i]; if (*suser == '\0') suser = pwd->pw_name; else if (!okname(suser)) continue; addargs(&alist, "-l"); addargs(&alist, "%s", suser); } else { host = cleanhostname(argv[i]); } addargs(&alist, "--"); addargs(&alist, "%s", host); addargs(&alist, "%s", cmd); addargs(&alist, "%s", src); addargs(&alist, "%s%s%s:%s", tuser ? tuser : "", tuser ? "@" : "", thost, targ); if (do_local_cmd(&alist) != 0) errs = 1; } else { /* local to remote */ if (remin == -1) { xasprintf(&bp, "%s -t -- %s", cmd, targ); host = cleanhostname(thost); if (do_cmd(host, tuser, bp, &remin, &remout) < 0) exit(1); if (response() < 0) exit(1); (void) xfree(bp); } source(1, argv + i); } } xfree(arg); }
static void workerContextDidReceiveAuthenticationCancellation(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<CrossThreadResourceResponseData> responseData) { ASSERT_UNUSED(context, context->isWorkerContext()); OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData)); workerClientWrapper->didReceiveAuthenticationCancellation(*response); }
void sink(int argc, char **argv) { static BUF buffer; struct stat stb; enum { YES, NO, DISPLAYED } wrerr; BUF *bp; off_t i; size_t j, count; int amt, exists, first, ofd; mode_t mode, omode, mask; off_t size, statbytes; int setimes, targisdir, wrerrno = 0; char ch, *cp, *np, *targ, *why, *vect[1], buf[2048]; struct timeval tv[2]; #define atime tv[0] #define mtime tv[1] #define SCREWUP(str) { why = str; goto screwup; } setimes = targisdir = 0; mask = umask(0); if (!pflag) (void) umask(mask); if (argc != 1) { run_err("ambiguous target"); exit(1); } targ = *argv; if (targetshouldbedirectory) verifydir(targ); (void) atomicio(vwrite, remout, "", 1); if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode)) targisdir = 1; for (first = 1;; first = 0) { cp = buf; if (atomicio(read, remin, cp, 1) != 1) return; if (*cp++ == '\n') SCREWUP("unexpected <newline>"); do { if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch)) SCREWUP("lost connection"); *cp++ = ch; } while (cp < &buf[sizeof(buf) - 1] && ch != '\n'); *cp = 0; if (verbose_mode) fprintf(stderr, "Sink: %s", buf); if (buf[0] == '\01' || buf[0] == '\02') { if (iamremote == 0) (void) atomicio(vwrite, STDERR_FILENO, buf + 1, strlen(buf + 1)); if (buf[0] == '\02') exit(1); ++errs; continue; } if (buf[0] == 'E') { (void) atomicio(vwrite, remout, "", 1); return; } if (ch == '\n') *--cp = 0; cp = buf; if (*cp == 'T') { setimes++; cp++; mtime.tv_sec = strtol(cp, &cp, 10); if (!cp || *cp++ != ' ') SCREWUP("mtime.sec not delimited"); mtime.tv_usec = strtol(cp, &cp, 10); if (!cp || *cp++ != ' ') SCREWUP("mtime.usec not delimited"); atime.tv_sec = strtol(cp, &cp, 10); if (!cp || *cp++ != ' ') SCREWUP("atime.sec not delimited"); atime.tv_usec = strtol(cp, &cp, 10); if (!cp || *cp++ != '\0') SCREWUP("atime.usec not delimited"); (void) atomicio(vwrite, remout, "", 1); continue; } if (*cp != 'C' && *cp != 'D') { /* * Check for the case "rcp remote:foo\* local:bar". * In this case, the line "No match." can be returned * by the shell before the rcp command on the remote is * executed so the ^Aerror_message convention isn't * followed. */ if (first) { run_err("%s", cp); exit(1); } SCREWUP("expected control record"); } mode = 0; for (++cp; cp < buf + 5; cp++) { if (*cp < '0' || *cp > '7') SCREWUP("bad mode"); mode = (mode << 3) | (*cp - '0'); } if (*cp++ != ' ') SCREWUP("mode not delimited"); for (size = 0; isdigit(*cp);) size = size * 10 + (*cp++ - '0'); if (*cp++ != ' ') SCREWUP("size not delimited"); if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) { run_err("error: unexpected filename: %s", cp); exit(1); } if (targisdir) { static char *namebuf; static size_t cursize; size_t need; need = strlen(targ) + strlen(cp) + 250; if (need > cursize) { if (namebuf) xfree(namebuf); namebuf = xmalloc(need); cursize = need; } (void) snprintf(namebuf, need, "%s%s%s", targ, strcmp(targ, "/") ? "/" : "", cp); np = namebuf; } else np = targ; curfile = cp; exists = stat(np, &stb) == 0; if (buf[0] == 'D') { int mod_flag = pflag; if (!iamrecursive) SCREWUP("received directory without -r"); if (exists) { if (!S_ISDIR(stb.st_mode)) { errno = ENOTDIR; goto bad; } if (pflag) (void) chmod(np, mode); } else { /* Handle copying from a read-only directory */ mod_flag = 1; if (mkdir(np, mode | S_IRWXU) < 0) goto bad; } vect[0] = xstrdup(np); sink(1, vect); if (setimes) { setimes = 0; if (utimes(vect[0], tv) < 0) run_err("%s: set times: %s", vect[0], strerror(errno)); } if (mod_flag) (void) chmod(vect[0], mode); if (vect[0]) xfree(vect[0]); continue; } omode = mode; mode |= S_IWRITE; if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) { bad: run_err("%s: %s", np, strerror(errno)); continue; } (void) atomicio(vwrite, remout, "", 1); if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) { (void) close(ofd); continue; } cp = bp->buf; wrerr = NO; statbytes = 0; if (showprogress) start_progress_meter(curfile, size, &statbytes); set_nonblock(remin); for (count = i = 0; i < size; i += bp->cnt) { amt = bp->cnt; if (i + amt > size) amt = size - i; count += amt; do { j = atomicio6(read, remin, cp, amt, scpio, &statbytes); if (j == 0) { run_err("%s", j != EPIPE ? strerror(errno) : "dropped connection"); exit(1); } amt -= j; cp += j; } while (amt > 0); if (count == bp->cnt) { /* Keep reading so we stay sync'd up. */ if (wrerr == NO) { if (atomicio(vwrite, ofd, bp->buf, count) != count) { wrerr = YES; wrerrno = errno; } } count = 0; cp = bp->buf; } } unset_nonblock(remin); if (showprogress) stop_progress_meter(); if (count != 0 && wrerr == NO && atomicio(vwrite, ofd, bp->buf, count) != count) { wrerr = YES; wrerrno = errno; } if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) && ftruncate(ofd, size) != 0) { run_err("%s: truncate: %s", np, strerror(errno)); wrerr = DISPLAYED; } if (pflag) { if (exists || omode != mode) #ifdef HAVE_FCHMOD if (fchmod(ofd, omode)) { #else /* HAVE_FCHMOD */ if (chmod(np, omode)) { #endif /* HAVE_FCHMOD */ run_err("%s: set mode: %s", np, strerror(errno)); wrerr = DISPLAYED; } } else { if (!exists && omode != mode) #ifdef HAVE_FCHMOD if (fchmod(ofd, omode & ~mask)) { #else /* HAVE_FCHMOD */ if (chmod(np, omode & ~mask)) { #endif /* HAVE_FCHMOD */ run_err("%s: set mode: %s", np, strerror(errno)); wrerr = DISPLAYED; } } if (close(ofd) == -1) { wrerr = YES; wrerrno = errno; } (void) response(); if (setimes && wrerr == NO) { setimes = 0; if (utimes(np, tv) < 0) { run_err("%s: set times: %s", np, strerror(errno)); wrerr = DISPLAYED; } } switch (wrerr) { case YES: run_err("%s: %s", np, strerror(wrerrno)); break; case NO: (void) atomicio(vwrite, remout, "", 1); break; case DISPLAYED: break; } } screwup: run_err("protocol error: %s", why); exit(1); } int response(void) { char ch, *cp, resp, rbuf[2048]; if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp)) lostconn(0); cp = rbuf; switch (resp) { case 0: /* ok */ return (0); default: *cp++ = resp; /* FALLTHROUGH */ case 1: /* error, followed by error msg */ case 2: /* fatal error, "" */ do { if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch)) lostconn(0); *cp++ = ch; } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n'); if (!iamremote) (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf); ++errs; if (resp == 1) return (-1); exit(1); } /* NOTREACHED */ } void usage(void) { (void) fprintf(stderr, "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n" " [-l limit] [-o ssh_option] [-P port] [-S program]\n" " [[user@]host1:]file1 ... [[user@]host2:]file2\n"); exit(1); }
void DrasculaEngine::converse(int index) { debug(4, "converse(%d)", index); char fileName[20]; sprintf(fileName, "op_%d.cal", index); Common::SeekableReadStream *stream = _archives.open(fileName); if (!stream) error("missing data file %s", fileName); int game1 = kDialogOptionUnselected, game2 = kDialogOptionUnselected, game3 = kDialogOptionUnselected; char phrase1[128], phrase2[128], phrase3[128], phrase4[128]; char sound1[13], sound2[13], sound3[13], sound4[13]; int phrase1_bottom, phrase2_bottom, phrase3_bottom, phrase4_bottom; int answer1, answer2, answer3; breakOut = 0; selectVerb(kVerbNone); TextResourceParser p(stream, DisposeAfterUse::YES); p.parseString(phrase1); p.parseString(phrase2); p.parseString(phrase3); p.parseString(phrase4); p.parseString(sound1); p.parseString(sound2); p.parseString(sound3); p.parseString(sound4); p.parseInt(answer1); p.parseInt(answer2); p.parseInt(answer3); // no need to delete the stream, since TextResourceParser takes ownership // delete stream; if (currentChapter == 2 && !strcmp(fileName, "op_5.cal") && flags[38] == 1 && flags[33] == 1) { strcpy(phrase3, _text[405]); strcpy(sound3, "405.als"); answer3 = 31; } if (currentChapter == 6 && !strcmp(fileName, "op_12.cal") && flags[7] == 1) { strcpy(phrase3, _text[273]); strcpy(sound3, "273.als"); answer3 = 14; } if (currentChapter == 6 && !strcmp(fileName, "op_12.cal") && flags[10] == 1) { strcpy(phrase3, _text[274]); strcpy(sound3, "274.als"); answer3 = 15; } cleanupString(phrase1); cleanupString(phrase2); cleanupString(phrase3); cleanupString(phrase4); loadPic("car.alg", backSurface); // TODO code here should limit y position for mouse in dialog menu, // but we can't implement this as there is lack in backend functionality // from 1(top) to 31 color_abc(kColorLightGreen); while (breakOut == 0 && !shouldQuit()) { updateRoom(); if (musicStatus() == 0 && roomMusic != 0) { if (currentChapter == 3 || currentChapter == 5) { playMusic(roomMusic); } else { // chapters 1, 2, 4, 6 if (flags[11] == 0) playMusic(roomMusic); } } updateEvents(); flushKeyBuffer(); phrase1_bottom = 8 * print_abc_opc(phrase1, 2, game1); phrase2_bottom = phrase1_bottom + 8 * print_abc_opc(phrase2, phrase1_bottom + 2, game2); phrase3_bottom = phrase2_bottom + 8 * print_abc_opc(phrase3, phrase2_bottom + 2, game3); phrase4_bottom = phrase3_bottom + 8 * print_abc_opc(phrase4, phrase3_bottom + 2, kDialogOptionUnselected); if (mouseY > 0 && mouseY < phrase1_bottom) { if (game1 == kDialogOptionClicked && _color != kColorWhite) color_abc(kColorWhite); else if (game1 != kDialogOptionClicked && _color != kColorLightGreen) color_abc(kColorLightGreen); print_abc_opc(phrase1, 2, kDialogOptionSelected); if (leftMouseButton == 1) { delay(100); game1 = kDialogOptionClicked; talk(phrase1, sound1); response(answer1); } } else if (mouseY > phrase1_bottom && mouseY < phrase2_bottom) { if (game2 == kDialogOptionClicked && _color != kColorWhite) color_abc(kColorWhite); else if (game2 != kDialogOptionClicked && _color != kColorLightGreen) color_abc(kColorLightGreen); print_abc_opc(phrase2, phrase1_bottom + 2, kDialogOptionSelected); if (leftMouseButton == 1) { delay(100); game2 = kDialogOptionClicked; talk(phrase2, sound2); response(answer2); } } else if (mouseY > phrase2_bottom && mouseY < phrase3_bottom) { if (game3 == kDialogOptionClicked && _color != kColorWhite) color_abc(kColorWhite); else if (game3 != kDialogOptionClicked && _color != kColorLightGreen) color_abc(kColorLightGreen); print_abc_opc(phrase3, phrase2_bottom + 2, kDialogOptionSelected); if (leftMouseButton == 1) { delay(100); game3 = kDialogOptionClicked; talk(phrase3, sound3); response(answer3); } } else if (mouseY > phrase3_bottom && mouseY < phrase4_bottom) { print_abc_opc(phrase4, phrase3_bottom + 2, kDialogOptionSelected); if (leftMouseButton == 1) { delay(100); talk(phrase4, sound4); breakOut = 1; } } else if (_color != kColorLightGreen) color_abc(kColorLightGreen); _system->delayMillis(10); updateScreen(); } // while (breakOut == 0) if (currentChapter == 2) loadPic(menuBackground, backSurface); else loadPic(99, backSurface); }
void pckt_callback(u_char *user, const struct pcap_pkthdr *pkthdr, const u_char *packet_data) { airspf_ctx *ctx = (airspf_ctx *)user; airspf_trace *trace; char ssid_name[256]; uint32_t packetlen; packetlen = pkthdr->len; // code to handle skipping past "prism monitoring header" blocks if(*((unsigned int*)packet_data) == htonl(0x44000000)){ uint32_t len = *((uint32_t*)(packet_data+4)); packet_data = packet_data + len; packetlen -= len; } // same for radiotap headers, which have a first 16 bits of 0x0000 if(*((uint16_t*)packet_data) == htons(0x0000)) { uint16_t len = *((uint16_t*)(packet_data+2)); packet_data = packet_data + len; packetlen -= len; } switch(packet_data[0]){ // data packet case 0x08: trace = match_trace(pkthdr, packet_data); if(trace->is_cracked) play_spoof(trace, pkthdr, packet_data); else collect(trace, pkthdr, packet_data); response(trace, pkthdr, packet_data); break; case 0x80: get_ssid(packet_data, ssid_name, sizeof(ssid_name)); printlog(ctx, 4, " beacon frame (%s)\n", ssid_name); break; case 0x40: get_ssid(packet_data, ssid_name, sizeof(ssid_name)); printlog(ctx, 4, " probe request (%s)\n", ssid_name); break; case 0x50: get_ssid(packet_data, ssid_name, sizeof(ssid_name)); printlog(ctx, 4, " probe response (%s)\n", ssid_name); break; case 0xd4: printlog(ctx, 4, " acknowledgement\n"); break; case 0x48: printlog(ctx, 4, " null function\n"); break; case 0xb0: printlog(ctx, 4, " authentication\n"); break; case 0xc0: printlog(ctx, 4, " deauthentication\n"); break; case 0x30: printlog(ctx, 4, " reassociation response\n"); break; case 0xc4: printlog(ctx, 4, " clear to send\n"); break; default: printlog(ctx, 5, " *** unknown type %x\n", packet_data[0]); } }
void context::locale(std::locale const &new_locale) { d->locale=new_locale; if(response().some_output_was_written()) response().out().imbue(d->locale); }
/*! Servers servicemanager first looks for a client to relay the message to. If none found then use the servers command chain to handle the service request. */ void TasServerServiceManager::handleServiceRequest(TasCommandModel& commandModel, TasSocket* requester, qint32 responseId) { TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest: " + commandModel.service() + ": " + commandModel.id()); TasClient* targetClient = 0; if (!commandModel.id().isEmpty() && commandModel.id() != "1"){ bool ok; quint64 clientPid = commandModel.id().toULongLong(&ok); targetClient = mClientManager->findByProcessId(clientPid); //no registered client check for platform specific handles for the process id if(!targetClient && extensionHandled(commandModel, requester, responseId)){ return; } if(!targetClient){ TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest: no target client send error..."); TasResponse response(responseId); response.setIsError(true); response.setErrorMessage("The application with Id " + commandModel.id() + " is no longer available."); requester->sendMessage(response); return; } } if(!targetClient && (commandModel.service() == APPLICATION_STATE || commandModel.service() == SCREEN_SHOT || commandModel.service() == FIND_OBJECT_SERVICE)){ targetClient = mClientManager->findClient(commandModel); } else if (commandModel.service() == RESOURCE_LOGGING_SERVICE){ targetClient = mClientManager->logMemClient(); } else{ } if(targetClient){ TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest client is: " + targetClient->processId() + "," + targetClient->applicationName()); int timeout = 10000; if(!commandModel.parameter("plugin_timeout").isEmpty()){ TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest set timeout " + commandModel.parameter("plugin_timeout")); timeout = commandModel.parameter("plugin_timeout").toInt(); } ResponseWaiter* waiter = new ResponseWaiter(responseId, requester, timeout); if(commandModel.service() == CLOSE_APPLICATION){ waiter->setResponseFilter(new CloseFilter(commandModel)); } connect(waiter, SIGNAL(responded(qint32)), this, SLOT(removeWaiter(qint32))); mResponseQueue.insert(responseId, waiter); if(commandModel.service() == APPLICATION_STATE || commandModel.service() == FIND_OBJECT_SERVICE){ commandModel.addDomAttribute("needFragment", "true"); //send request for qt uistate to client targetClient->socket()->sendRequest(responseId, commandModel.sourceString(false)); //in the meantime process native getNativeUiState(responseId, commandModel); } else{ //can respond as soon as response from qt side waiter->okToRespond(); targetClient->socket()->sendRequest(responseId, commandModel.sourceString()); } } else{ handleClientLess(commandModel, requester, responseId); } }
PassRefPtr<ArchiveResource> DocumentLoader::mainResource() const { const ResourceResponse& r = response(); return ArchiveResource::create(mainResourceData(), r.url(), r.mimeType(), r.textEncodingName(), frame()->tree()->name()); }