static SLVAL request_method(sl_vm_t* vm) { return request(vm)->method; }
int main(int argc, char *argv[]) { int interactive; int raw = 0; int warning_displayed = 0; int c; int ret = 0; for (;;) { c = getopt(argc, argv, "hvrR"); if (c < 0) break; switch (c) { case 'h': usage(); return 0; case 'r': if (raw) { usage(); return -1; } raw = SHOW_RAW; break; case 'R': if (raw) { usage(); return -1; } raw = (SHOW_RAW | SHOW_RAW_ONLY); break; case 'v': printf("%s\n", cli_version); return 0; default: usage(); return -1; } } show_raw = raw; interactive = argc == optind; if (interactive) { printf("%s\n\n%s\n\n", cli_version, cli_license); } for (;;) { clif_conn = clif_open(); if (clif_conn) { if (warning_displayed) printf("Connection established.\n"); break; } if (!interactive) { perror("Failed to connect to lldpad - clif_open"); return -1; } if (!warning_displayed) { printf("Could not connect to lldpad - re-trying\n"); warning_displayed = 1; } sleep(1); continue; } signal(SIGINT, cli_terminate); signal(SIGTERM, cli_terminate); signal(SIGALRM, cli_alarm); if (interactive) { if (clif_attach(clif_conn, NULL) == 0) cli_attached = 1; else printf("Warning: Failed to attach to lldpad.\n"); cli_interactive(raw); } else ret = request(clif_conn, argc - optind, &argv[optind], raw); cli_close_connection(); return ret; }
void process_command(int descr, dbref player, char *command) { char *arg1; char *arg2; char *full_command, *commandline=command, *commandstuff; char *p; /* utility */ char pbuf[BUFFER_LEN]; char xbuf[BUFFER_LEN]; char ybuf[BUFFER_LEN]; const char *path; struct frame *tmpfr; if (command == 0) abort(); /* robustify player */ if (player < 0 || player >= db_top || (Typeof(player) != TYPE_PLAYER && Typeof(player) != TYPE_THING)) { log_status("process_command: bad player %d\n", player); return; } if ((tp_log_commands || (tp_log_guests && Guest(OWNER(player)))) && (!(FLAGS(player)&(INTERACTIVE | READMODE)))) { log_command("%s%s%s%s(%d) in %s(%d):%s %s\n", Mage(OWNER(player)) ? "WIZ: " : "", (Typeof(player) != TYPE_PLAYER) ? NAME(player) : "", (Typeof(player) != TYPE_PLAYER) ? " by " : "", NAME(OWNER(player)), (int) player, NAME(DBFETCH(player)->location), (int) DBFETCH(player)->location, (FLAGS(player) & INTERACTIVE) ? " [interactive]" : " ", command); } if (FLAGS(player) & INTERACTIVE) { interactive(descr, player, command); return; } /* eat leading whitespace */ while (*command && isspace(*command)) command++; commandstuff = command; /* check for single-character commands */ if (*command == SAY_TOKEN || *command == '\'') { sprintf(pbuf, "say %s", command + 1); command = &pbuf[0]; } else if (*command == POSE_TOKEN || *command == ';') { sprintf(pbuf, "pose %s", command + 1); command = &pbuf[0]; } else if ((*command == '|' || (*commandstuff++ == '\\' && *commandstuff == '\\') ) && can_move(descr, player, "spoof", 0)) { if(*command = '\\') sprintf(pbuf, "spoof %s", command + 2); else sprintf(pbuf, "spoof %s", command + 1); command = &pbuf[0]; } /* if player is a wizard, and uses overide token to start line...*/ /* ... then do NOT run actions, but run the command they specify. */ if (!strcmp(command, WHO_COMMAND)) { char xxbuf[BUFFER_LEN]; strcpy(xxbuf, "@"); strcat(xxbuf, WHO_COMMAND); strcat(xxbuf, " "); strcat(xxbuf, command + sizeof(WHO_COMMAND) - 1); if (can_move(descr, player, xxbuf, 5)) { do_move(descr, player, xxbuf, 5); } else { pdump_who_users(descr, command + sizeof(WHO_COMMAND) - 1); } return; } if (!( *command == OVERIDE_TOKEN && TMage(player) )) { if( can_move(descr, player, command, 0) ) { do_move(descr, player, command, 0); /* command is exact match for exit */ *match_args = 0; *match_cmdname = 0; return; } } if (*command == OVERIDE_TOKEN && TMage(player)) command++; full_command = strcpy(xbuf, command); for (; *full_command && !isspace(*full_command); full_command++); if (*full_command) full_command++; /* find arg1 -- move over command word */ command = strcpy(ybuf, command); for (arg1 = command; *arg1 && !isspace(*arg1); arg1++); /* truncate command */ if (*arg1) *arg1++ = '\0'; /* remember command for programs */ strcpy(match_cmdname, command); /* move over spaces */ while (*arg1 && isspace(*arg1)) arg1++; /* find end of arg1, start of arg2 */ for (arg2 = arg1; *arg2 && *arg2 != ARG_DELIMITER; arg2++); /* truncate arg1 */ for (p = arg2 - 1; p >= arg1 && isspace(*p); p--) *p = '\0'; /* go past delimiter if present */ if (*arg2) *arg2++ = '\0'; while (*arg2 && isspace(*arg2)) arg2++; strcpy(match_cmdname, command); strcpy(match_args, full_command); switch (command[0]) { case '@': switch (command[1]) { case 'a': case 'A': /* @action, @attach */ switch (command[2]) { case 'c': case 'C': Matched("@action"); do_action(descr, player, arg1, arg2); break; case 'r': case 'R': if (string_compare(command, "@armageddon")) goto bad; do_armageddon(player, full_command); break; case 't': case 'T': Matched("@attach"); do_attach(descr, player, arg1, arg2); break; case 'n': case 'N': Matched("@ansidescribe"); do_ansidescribe(descr, player, arg1, arg2); break; default: goto bad; } break; case 'b': case 'B': Matched("@boot"); do_boot(player, arg1); break; case 'c': case 'C': /* chown, contents, create */ switch (command[2]) { case 'h': case 'H': switch (command[3]) { case 'l': case 'L': Matched("@chlock"); do_chlock(descr, player, arg1, arg2); break; case 'o': case 'O': Matched("@chown"); do_chown(descr, player, arg1, arg2); break; default: goto bad; } break; case 'o': case 'O': switch (command[4]) { case 'l': case 'L': Matched("@conlock"); do_conlock(descr, player, arg1, arg2); break; case 't': case 'T': Matched("@contents"); do_contents(descr, player, arg1, arg2); break; default: goto bad; } break; case 'r': case 'R': if (string_compare(command, "@credits")) { Matched("@create"); do_create(player, arg1, arg2); } else { do_credits(player); } break; default: goto bad; } break; case 'd': case 'D': /* describe, dequeue, dig, or dump */ switch (command[2]) { case 'b': case 'B': Matched("@dbginfo"); do_serverdebug(descr, player, arg1, arg2); break; case 'e': case 'E': #ifdef DELTADUMPS if(command[3] == 'l' || command[3] == 'L') { Matched("@delta"); do_delta(player); } else #endif { if( (command[3] == 's' || command[3] == 'S') && (command[4] == 't' || command[4] == 'T') ) { Matched("@destroy"); do_recycle(descr, player, arg1); } else { Matched("@describe"); do_describe(descr, player, arg1, arg2); } } break; case 'i': case 'I': Matched("@dig"); do_dig(descr, player, arg1, arg2); break; #ifdef DELTADUMPS case 'l': case 'L': Matched("@dlt"); do_delta(player); break; #endif case 'o': case 'O': Matched("@doing"); if (!tp_who_doing) goto bad; do_doing(descr, player, arg1, arg2); break; case 'r': case 'R': Matched("@drop"); do_drop_message(descr, player, arg1, arg2); break; case 'u': case 'U': Matched("@dump"); do_dump(player, full_command); break; default: goto bad; } break; case 'e': case 'E': switch (command[2]) { case 'd': case 'D': Matched("@edit"); do_edit(descr, player, arg1); break; case 'n': case 'N': Matched("@entrances"); do_entrances(descr, player, arg1, arg2); break; case 'x': case 'X': Matched("@examine"); sane_dump_object(player, arg1); break; default: goto bad; } break; case 'f': case 'F': /* fail, find, force, or frob */ switch (command[2]) { case 'a': case 'A': Matched("@fail"); do_fail(descr, player, arg1, arg2); break; case 'i': case 'I': if(command[3] == 'x' || command[3] == 'X') { Matched("@fixwizbits"); do_fixw(player, full_command); } else { Matched("@find"); do_find(player, arg1, arg2); } break; case 'l': case 'L': Matched("@flock"); do_flock(descr, player, arg1, arg2); break; case 'o': case 'O': Matched("@force"); do_force(descr, player, arg1, arg2); break; case 'r': case 'R': if (string_compare(command, "@frob")) goto bad; do_frob(descr, player, arg1, arg2); break; default: goto bad; } break; case 'h': case 'H': switch (command[2]) { case 'T': case 't': Matched("@htmldescribe"); do_htmldescribe(descr, player, arg1, arg2); break; default: Matched("@hopper"); do_hopper(player, arg1); break; } break; case 'i': case 'I': switch(command[2]) { case 'h': case 'H': Matched("@ihtmldescribe"); do_ihtmldescribe(descr, player, arg1, arg2); break; case 'a': case 'A': Matched("@iansidescribe"); do_iansidescribe(descr, player, arg1, arg2); break; default: Matched("@idescribe"); do_idescribe(descr, player, arg1, arg2); break; } break; case 'k': case 'K': Matched("@kill"); do_dequeue(descr, player, arg1); break; case 'l': case 'L': /* lock or link */ switch (command[2]) { case 'i': case 'I': switch (command[3]) { case 'n': case 'N': Matched("@link"); do_link(descr, player, arg1, arg2); break; case 's': case 'S': Matched("@list"); match_and_list(descr, player, arg1, arg2, 1); break; default: goto bad; } break; case 'o': case 'O': Matched("@lock"); do_lock(descr, player, arg1, arg2); break; default: goto bad; } break; case 'm': case 'M': switch (command[2]) { case 'e': case 'E': Matched("@memory"); do_memory(player); break; case 'c': case 'C': switch (command[4]) { case '2': Matched("@mcp2muf"); match_and_list(descr, player, arg1, arg2, 0); break; default: Matched("@mcp"); do_prog(descr, player, arg1, 1); break; } default: goto bad; } break; case 'n': case 'N': /* @name or @newpassword */ switch (command[2]) { case 'a': case 'A': Matched("@name"); do_name(descr, player, arg1, arg2); break; case 'e': case 'E': if (string_compare(command, "@newpassword")) goto bad; do_newpassword(player, arg1, arg2); break; default: goto bad; } break; case 'o': case 'O': switch (command[2]) { case 'd': case 'D': Matched("@odrop"); do_odrop(descr, player, arg1, arg2); break; case 'e': case 'E': Matched("@oecho"); do_oecho(descr, player, arg1, arg2); break; case 'f': case 'F': Matched("@ofail"); do_ofail(descr, player, arg1, arg2); break; case 'p': case 'P': Matched("@open"); do_open(descr, player, arg1, arg2); break; case 's': case 'S': Matched("@osuccess"); do_osuccess(descr, player, arg1, arg2); break; case 'w': case 'W': Matched("@owned"); do_owned(player, arg1, arg2); break; default: goto bad; } break; case 'p': case 'P': switch (command[2]) { case 'a': case 'A': Matched("@password"); do_password(player, arg1, arg2); break; case 'c': case 'C': Matched("@pcreate"); do_pcreate(player, arg1, arg2); break; case 'e': case 'E': Matched("@pecho"); do_pecho(descr, player, arg1, arg2); break; case 'r': case 'R': if (string_prefix("@program", command)) { do_prog(descr, player, arg1, 0); break; } else if (string_prefix("@proginfo", command)) { do_proginfo(player, arg1); break; } else { Matched("@propset"); do_propset(descr, player, arg1, arg2); break; } case 's': case 'S': Matched("@ps"); list_events(player); break; case 'u': case 'U': Matched("@purge"); do_purge(descr, player, arg1, arg2); break; default: goto bad; } break; case 'r': case 'R': switch (command[3]) { case 'c': case 'C': Matched("@recycle"); do_recycle(descr, player, arg1); break; case 's': case 'S': if (!string_compare(command, "@restart")) { do_restart(player, full_command); } else if (!string_compare(command, "@restrict")) { do_restrict(player, arg1); } else { goto bad; } break; default: goto bad; } break; case 's': case 'S': /* set, shutdown, success */ switch (command[2]) { case 'a': case 'A': if (!string_compare(command, "@sanity")) { sanity(player); } else if (!string_compare(command, "@sanchange")) { sanechange(player, full_command); } else if (!string_compare(command, "@sanfix")) { sanfix(player); } else { goto bad; } break; case 'e': case 'E': Matched("@set"); do_set(descr, player, arg1, arg2); break; case 'h': case 'H': if (!string_compare(command, "@shout")) { do_wall(player, full_command); break; } if (string_compare(command, "@shutdown")) goto bad; do_shutdown(player, arg1); break; case 't': case 'T': Matched("@stats"); do_stats(player, arg1); break; case 'u': case 'U': Matched("@success"); do_success(descr, player, arg1, arg2); break; case 'w': case 'W': Matched("@sweep"); do_sweep(descr, player, arg1); break; default: goto bad; } break; case 't': case 'T': switch (command[2]) { case 'e': case 'E': Matched("@teleport"); do_teleport(descr, player, arg1, arg2); break; case 'o': case 'O': if (string_compare(command, "@toad")) goto bad; do_frob(descr, player, arg1, arg2); break; case 'r': case 'R': Matched("@trace"); do_trace(descr, player, arg1, atoi(arg2)); break; case 'u': case 'U': Matched("@tune"); do_tune(player, arg1, arg2); break; default: goto bad; } break; case 'u': case 'U': switch (command[2]) { case 'N': case 'n': if (string_prefix(command, "@unlink")) { do_unlink(descr, player, arg1); } else if (string_prefix(command, "@unlock")) { do_unlock(descr, player, arg1); } else if (string_prefix(command, "@uncompile")) { do_uncompile(player); } else { goto bad; } break; #ifndef NO_USAGE_COMMAND case 'S': case 's': Matched("@usage"); do_usage(player); break; #endif default: goto bad; break; } break; case 'v': case 'V': Matched("@version"); anotify_nolisten2(player, CRIMSON "ProtoMUCK " PROTOBASE PURPLE " (" RED VERSION WHITE " -- " AQUA NEONVER PURPLE ")" ); break; case 'w': case 'W': if (string_compare(command, "@wall")) goto bad; do_wall(player, full_command); break; default: goto bad; } break; case '&': do_mush_set(descr, player, arg1, arg2, command); break; case 'd': case 'D': switch (command[1]) { case 'b': case 'B': Matched("dboot"); do_dboot(player, arg1); break; case 'i': case 'I': Matched("dinfo"); do_dinfo(player, arg1); break; case 'r': case 'R': Matched("drop"); do_drop(descr, player, arg1, arg2); break; case 'w': case 'W': Matched("dwall"); do_dwall(player, arg1, arg2); break; default: goto bad; } break; case 'e': case 'E': switch (command[1]) { case 'm': case 'M': Matched("emote"); do_pose(descr, player, full_command); break; case 'x': case 'X': case '\0': Matched("examine"); do_examine(descr, player, arg1, arg2); break; default: goto bad; } break; case 'g': case 'G': /* get, give, go, or gripe */ switch (command[1]) { case 'e': case 'E': Matched("get"); do_get(descr, player, arg1, arg2); break; case 'i': case 'I': Matched("give"); do_give(descr, player, arg1, atoi(arg2)); break; case 'o': case 'O': Matched("goto"); do_move(descr, player, arg1, 0); break; case 'r': case 'R': if(command[2]=='i' || command[2]=='I') { if (string_compare(command, "gripe")) goto bad; do_gripe(player, full_command); break; } default: goto bad; } break; case 'h': case 'H': switch (command[1]) { case 'a': case 'A': Matched("hand"); do_drop(descr, player, arg1, arg2); break; case 'e': case 'E': Matched("help"); do_help(player, arg1, arg2); break; default: goto bad; } break; case 'i': case 'I': if (string_compare(command, "info")) { Matched("inventory"); do_inventory(player); } else { do_info(player, arg1, arg2); } break; case 'l': case 'L': if (string_prefix("look", command)) { do_look_at(descr, player, arg1, arg2); break; } else { Matched("leave"); do_leave(descr, player); break; } case 'm': case 'M': if (string_prefix(command, "move")) { do_move(descr, player, arg1, 0); break; } else if (!string_compare(command, "motd")) { do_motd(player, full_command); break; } else if (!string_compare(command, "mpi")) { do_mpihelp(player, arg1, arg2); break; } else { if (string_compare(command, "man")) goto bad; do_man(player, arg1, arg2); } break; case 'n': case 'N': /* news */ Matched("news"); do_news(player, arg1, arg2); break; case 'p': case 'P': switch (command[1]) { case 'a': case 'A': case '\0': Matched("page"); do_page(descr, player, arg1, arg2); break; case 'o': case 'O': Matched("pose"); do_pose(descr, player, full_command); break; case 'u': case 'U': Matched("put"); do_drop(descr, player, arg1, arg2); break; default: goto bad; } break; case 'r': case 'R': switch (command[1]) { case 'e': case 'E': if(command[2] == 'q' || command[2] == 'Q'){ Matched("request"); request(player, NULL, commandline); } else { Matched("read"); /* undocumented alias for look */ do_look_at(descr, player, arg1, arg2); } break; default: goto bad; } break; case 's': case 'S': /* say, "score" */ switch (command[1]) { case 'a': case 'A': Matched("say"); do_say(descr, player, full_command); break; case 'c': case 'C': case '\0': if( command[1] && (command[2] == 'a' || command[2] == 'A' )) { Matched("scan"); do_sweep(descr, player, arg1); } else { Matched("score"); do_score(player, 1); } break; default: goto bad; } break; case 't': case 'T': switch (command[1]) { case 'a': case 'A': Matched("take"); do_get(descr, player, arg1, arg2); break; case 'h': case 'H': Matched("throw"); do_drop(descr, player, arg1, arg2); break; default: goto bad; } break; case 'w': case 'W': switch (command[1]){ case 'c': case 'C': Matched("wc"); do_wizchat(player, full_command); break; case 'i': case 'I': Matched("wizchat"); do_wizchat(player, arg1); break; case 'h': case 'H': case '\0': Matched("whisper"); do_whisper(descr, player, arg1, arg2); break; default: goto bad; } break; default: bad: if ( Typeof(tp_huh_command) == TYPE_PROGRAM && !(player == -1)) { tmpfr = interp(descr, player, DBFETCH(player)->location, tp_huh_command, (dbref)-4, FOREGROUND, STD_REGUID); if (!tmpfr) goto bad2; (void) interp_loop(player, tp_huh_command, tmpfr, 0); } else { bad2: anotify_fmt(player, CINFO "%s",tp_huh_mesg); if (tp_log_failed_commands && !controls(player, DBFETCH(player)->location)) { log_status("HUH from %s(%d) in %s(%d)[%s]: %s %s\n", NAME(player), player, NAME(DBFETCH(player)->location), DBFETCH(player)->location, NAME(OWNER(DBFETCH(player)->location)), command, full_command); } } break; } }
void ImageLoader::updateFromElement() { // If we're not making renderers for the page, then don't load images. We don't want to slow // down the raw HTML parsing case by loading images we don't intend to display. Document& document = element().document(); if (!document.hasLivingRenderTree()) return; AtomicString attr = element().imageSourceURL(); if (attr == m_failedLoadURL) return; // Do not load any image if the 'src' attribute is missing or if it is // an empty string. CachedResourceHandle<CachedImage> newImage = 0; if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) { CachedResourceRequest request(ResourceRequest(document.completeURL(sourceURI(attr)))); request.setInitiator(&element()); String crossOriginMode = element().fastGetAttribute(HTMLNames::crossoriginAttr); if (!crossOriginMode.isNull()) { StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials; updateRequestForAccessControl(request.mutableResourceRequest(), document.securityOrigin(), allowCredentials); } if (m_loadManually) { bool autoLoadOtherImages = document.cachedResourceLoader()->autoLoadImages(); document.cachedResourceLoader()->setAutoLoadImages(false); newImage = new CachedImage(request.resourceRequest(), m_element.document().page()->sessionID()); newImage->setLoading(true); newImage->setOwningCachedResourceLoader(document.cachedResourceLoader()); document.cachedResourceLoader()->m_documentResources.set(newImage->url(), newImage.get()); document.cachedResourceLoader()->setAutoLoadImages(autoLoadOtherImages); } else newImage = document.cachedResourceLoader()->requestImage(request); // If we do not have an image here, it means that a cross-site // violation occurred, or that the image was blocked via Content // Security Policy, or the page is being dismissed. Trigger an // error event if the page is not being dismissed. if (!newImage && !pageIsBeingDismissed(document)) { m_failedLoadURL = attr; m_hasPendingErrorEvent = true; errorEventSender().dispatchEventSoon(*this); } else clearFailedLoadURL(); } else if (!attr.isNull()) { // Fire an error event if the url is empty. m_failedLoadURL = attr; m_hasPendingErrorEvent = true; errorEventSender().dispatchEventSoon(*this); } CachedImage* oldImage = m_image.get(); if (newImage != oldImage) { if (m_hasPendingBeforeLoadEvent) { beforeLoadEventSender().cancelEvent(*this); m_hasPendingBeforeLoadEvent = false; } if (m_hasPendingLoadEvent) { loadEventSender().cancelEvent(*this); m_hasPendingLoadEvent = false; } // Cancel error events that belong to the previous load, which is now cancelled by changing the src attribute. // If newImage is null and m_hasPendingErrorEvent is true, we know the error event has been just posted by // this load and we should not cancel the event. // FIXME: If both previous load and this one got blocked with an error, we can receive one error event instead of two. if (m_hasPendingErrorEvent && newImage) { errorEventSender().cancelEvent(*this); m_hasPendingErrorEvent = false; } m_image = newImage; m_hasPendingBeforeLoadEvent = !document.isImageDocument() && newImage; m_hasPendingLoadEvent = newImage; m_imageComplete = !newImage; if (newImage) { if (!document.isImageDocument()) { if (!document.hasListenerType(Document::BEFORELOAD_LISTENER)) dispatchPendingBeforeLoadEvent(); else beforeLoadEventSender().dispatchEventSoon(*this); } else updateRenderer(); // If newImage is cached, addClient() will result in the load event // being queued to fire. Ensure this happens after beforeload is // dispatched. newImage->addClient(this); } if (oldImage) oldImage->removeClient(this); } if (RenderImageResource* imageResource = renderImageResource()) imageResource->resetAnimation(); // Only consider updating the protection ref-count of the Element immediately before returning // from this function as doing so might result in the destruction of this ImageLoader. updatedHasPendingEvent(); }
void ImageLoader::doUpdateFromElement(UpdateFromElementBehavior updateBehavior) { // FIXME: According to // http://www.whatwg.org/specs/web-apps/current-work/multipage/embedded-content.html#the-img-element:the-img-element-55 // When "update image" is called due to environment changes and the load fails, onerror should not be called. // That is currently not the case. // // We don't need to call clearLoader here: Either we were called from the // task, or our caller updateFromElement cleared the task's loader (and set // m_pendingTask to null). m_pendingTask.clear(); // Make sure to only decrement the count when we exit this function OwnPtr<IncrementLoadEventDelayCount> loadDelayCounter; loadDelayCounter.swap(m_loadDelayCounter); Document& document = m_element->document(); if (!document.isActive()) return; AtomicString imageSourceURL = m_element->imageSourceURL(); KURL url = imageSourceToKURL(imageSourceURL); ResourcePtr<ImageResource> newImage = 0; if (!url.isNull()) { // Unlike raw <img>, we block mixed content inside of <picture> or <img srcset>. ResourceLoaderOptions resourceLoaderOptions = ResourceFetcher::defaultResourceOptions(); ResourceRequest resourceRequest(url); if (!element()->getAttribute(HTMLNames::srcsetAttr).isNull()) resourceRequest.setRequestContext(WebURLRequest::RequestContextImageSet); FetchRequest request(ResourceRequest(url), element()->localName(), resourceLoaderOptions); newImage = document.fetcher()->fetchImage(request); if (!newImage && !pageIsBeingDismissed(&document)) crossSiteOrCSPViolationOccured(imageSourceURL); else clearFailedLoadURL(); } else if (!imageSourceURL.isNull()) { // Fire an error event if the url string is not empty, but the KURL is. m_hasPendingErrorEvent = true; errorEventSender().dispatchEventSoon(this); } ImageResource* oldImage = m_image.get(); if (newImage != oldImage) { sourceImageChanged(); if (m_hasPendingLoadEvent) { loadEventSender().cancelEvent(this); m_hasPendingLoadEvent = false; } // Cancel error events that belong to the previous load, which is now cancelled by changing the src attribute. // If newImage is null and m_hasPendingErrorEvent is true, we know the error event has been just posted by // this load and we should not cancel the event. // FIXME: If both previous load and this one got blocked with an error, we can receive one error event instead of two. if (m_hasPendingErrorEvent && newImage) { errorEventSender().cancelEvent(this); m_hasPendingErrorEvent = false; } m_image = newImage; m_hasPendingLoadEvent = newImage; m_imageComplete = !newImage; updateRenderer(); // If newImage exists and is cached, addClient() will result in the load event // being queued to fire. Ensure this happens after beforeload is dispatched. if (newImage) newImage->addClient(this); if (oldImage) oldImage->removeClient(this); } else if (updateBehavior == UpdateSizeChanged && m_element->renderer() && m_element->renderer()->isImage()) { toRenderImage(m_element->renderer())->intrinsicSizeChanged(); } if (RenderImageResource* imageResource = renderImageResource()) imageResource->resetAnimation(); // Only consider updating the protection ref-count of the Element immediately before returning // from this function as doing so might result in the destruction of this ImageLoader. updatedHasPendingEvent(); }
void CentralServerConnection::onReceive(const Archive::ByteStream & message) { Archive::ReadIterator ri = message.begin(); GameNetworkMessage msg(ri); ri = message.begin(); if(msg.isType("ConGenericMessage")) { // dispatch to CentralCommandParser ConGenericMessage con(ri); Unicode::String wideResult; m_centralCommandParser->parse(NetworkId(static_cast<NetworkId::NetworkIdType>(con.getMsgId())), Unicode::narrowToWide(con.getMsg()), wideResult); ConGenericMessage response(Unicode::wideToNarrow(wideResult), con.getMsgId()); send(response, true); } else if(msg.isType("CharacterTransferStatusMessage")) { CharacterTransferStatusMessage c(ri); CreatureObject * character = safe_cast<CreatureObject *>(NetworkIdManager::getObjectById(c.getToCharacterId())); if(character) { if(character->getClient()) { character->receiveCharacterTransferStatusMessage(c.getStatusMessage()); } } } else if(msg.isType("TransferRequestNameValidation")) { const GenericValueTypeMessage<TransferCharacterData> requestNameValidation(ri); LOG("CustomerService", ("CharacterTransfer: Received TransferRequestNameValidation from CentralServer : %s", requestNameValidation.getValue().toString().c_str())); std::string name = requestNameValidation.getValue().getDestinationCharacterName(); if(name.empty()) { name = requestNameValidation.getValue().getSourceCharacterName(); } // call the same name validation code that gets called for normal character creation std::string templateName = requestNameValidation.getValue().getObjectTemplateName(); if (templateName.empty()) { uint32 const templateCrc = requestNameValidation.getValue().getObjectTemplateCrc(); if (templateCrc != 0) { templateName = ObjectTemplateList::lookUp(templateCrc).getString(); } } VerifyAndLockNameRequest const verifyRequest(requestNameValidation.getValue().getDestinationStationId(), NetworkId::cms_invalid, templateName, Unicode::narrowToWide(name), 0xFFFFFFFF); StringId const verifyResult = GameServer::getInstance().handleVerifyAndLockNameRequest(verifyRequest, false, false); TransferCharacterData replyData(requestNameValidation.getValue()); replyData.setIsValidName(verifyResult == NameErrors::nameApproved); GenericValueTypeMessage<std::pair<std::string, TransferCharacterData> > reply("TransferReplyNameValidation", std::make_pair(std::string("@") + verifyResult.getCanonicalRepresentation(), replyData)); send(reply, true); } else if(msg.isType("TransferReplyCharacterList")) { const TransferReplyCharacterList reply(ri); const AvatarList & oldAl = reply.getAvatarList(); // remove any characters from the list that would qualify for free CTS; characters that // qualify for free CTS should/must use the in-game free CTS to transfer the character; AvatarList newAl; std::string const & clusterName = GameServer::getInstance().getClusterName(); for (AvatarList::const_iterator iter = oldAl.begin(); iter != oldAl.end(); ++iter) { if (!FreeCtsDataTable::getFreeCtsInfoForCharacter(static_cast<time_t>(NameManager::getInstance().getPlayerCreateTime(iter->m_networkId)), clusterName, false)) newAl.push_back(*iter); else LOG("CustomerService", ("CharacterTransfer: removing (%s, %s, %s) from paid CTS character list for station id %u because the character qualifies for free CTS", clusterName.c_str(), Unicode::wideToNarrow(iter->m_name).c_str(), iter->m_networkId.getValueString().c_str(), reply.getStationId())); } // send updated character list back to CentralServer const TransferReplyCharacterList updatedReply(reply.getTrack(), reply.getStationId(), newAl); send(updatedReply, true); } else if(msg.isType("CtsCompletedForcharacter")) { const GenericValueTypeMessage<std::pair<std::string, NetworkId> > msg(ri); MessageToQueue::getInstance().sendMessageToJava(msg.getValue().second, "ctsCompletedForCharacter", std::vector<int8>(), 0, false); } else if( msg.isType( "GameServerCSRequest" ) ) { GameServerCSRequestMessage request( ri ); GameServer::getInstance().handleCSRequest( request ); } else if( msg.isType( "CSFindAuthObject" ) ) { // see if we have the object. GenericValueTypeMessage< std::pair<NetworkId, unsigned int> > msg( ri ); ServerObject * object = safe_cast<ServerObject *>( NetworkIdManager::getObjectById( msg.getValue().first ) ); // return an appropriate response. if( object && object->isAuthoritative() ) { GenericValueTypeMessage< std::pair< unsigned int, bool > > rmsg( "CSFindAuthObjectReply", std::make_pair( msg.getValue().second, true ) ); GameServer::getInstance().sendToCentralServer( rmsg ); } else { GenericValueTypeMessage< std::pair< unsigned int, bool > > rmsg( "CSFindAuthObjectReply", std::make_pair( msg.getValue().second, false ) ); GameServer::getInstance().sendToCentralServer( rmsg ); } } else { ServerConnection::onReceive(message); } }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void SeparationsMatrixFacility::makeRequests(){ for (vector<string>::iterator iter = in_commod_.begin(); iter != in_commod_.end(); iter ++){ // The separations facility should ask for at least as much SNF as it is // already committed to using this month. double requestAmt; // In a constrained market, it happily accepts amounts no matter how small double minAmt = 0; // check how full its inventory is double inv = this->checkInventory(); // and how much is already in its stocks double sto = this->checkStocks(); // subtract inv and sto from inventory max size to get total empty space // the request cannot exceed the space available double space = inventory_size_ - inv - sto; // Currently, no pricing information included for Separations Facility double commod_price = 0; // spotCapacity represents unaccounted for capacity double spotCapacity = capacity_ - outstMF_; if (space == 0){ // don't request anything } else if (space < capacity_){ int total = checkStocks(); Communicator* recipient = dynamic_cast<Communicator*>(MarketModel::marketForCommod(*iter)); // if empty space is less than monthly acceptance capacity requestAmt = space; // request a generic resource GenericResource* request_res = new GenericResource((*iter), "kg", requestAmt); // build the transaction and message Transaction trans; trans.commod = (*iter); trans.minfrac = minAmt/requestAmt; trans.is_offer = false; trans.price = commod_price; trans.resource = request_res; msg_ptr request(new Message(this, recipient, trans)); request->setNextDest(facInst()); request->sendOn(); } // otherwise, the upper bound is the monthly acceptance capacity // minus the amount in stocks. else if (space >= capacity_){ Communicator* recipient = dynamic_cast<Communicator*>(MarketModel::marketForCommod(*iter)); // if empty space is more than monthly acceptance capacity requestAmt = capacity_ - sto; // request a generic resource GenericResource* request_res = new GenericResource((*iter), "kg", requestAmt); // build the transaction and message Transaction trans; trans.commod = (*iter); trans.minfrac = minAmt/requestAmt; trans.is_offer = false; trans.price = commod_price; trans.resource = request_res; msg_ptr request(new Message(this, recipient, trans)); request->setNextDest(facInst()); request->sendOn(); } } // <- for leop }
void BatchWriteExec::executeBatch( const BatchedCommandRequest& clientRequest, BatchedCommandResponse* clientResponse ) { BatchWriteOp batchOp; batchOp.initClientRequest( &clientRequest ); int numTargetErrors = 0; int numStaleBatches = 0; int numResolveFailures = 0; for ( int rounds = 0; !batchOp.isFinished(); rounds++ ) { // // Refresh the targeter if we need to (no-op if nothing stale) // Status refreshStatus = _targeter->refreshIfNeeded(); if ( !refreshStatus.isOK() ) { // It's okay if we can't refresh, we'll just record errors for the ops if // needed. warning() << "could not refresh targeter" << causedBy( refreshStatus.reason() ) << endl; } // // Get child batches to send // vector<TargetedWriteBatch*> childBatches; // // Targeting errors can be caused by remote metadata changing (the collection could have // been dropped and recreated, for example with a new shard key). If a remote metadata // change occurs *before* a client sends us a batch, we need to make sure that we don't // error out just because we're staler than the client - otherwise mongos will be have // unpredictable behavior. // // (If a metadata change happens *during* or *after* a client sends us a batch, however, // we make no guarantees about delivery.) // // For this reason, we don't record targeting errors until we've refreshed our targeting // metadata at least once *after* receiving the client batch - at that point, we know: // // 1) our new metadata is the same as the metadata when the client sent a batch, and so // targeting errors are real. // OR // 2) our new metadata is a newer version than when the client sent a batch, and so // the metadata must have changed after the client batch was sent. We don't need to // deliver in this case, since for all the client knows we may have gotten the batch // exactly when the metadata changed. // // If we've had a targeting error or stale error, we've refreshed the metadata once and // can record target errors. bool recordTargetErrors = numTargetErrors > 0 || numStaleBatches > 0; Status targetStatus = batchOp.targetBatch( *_targeter, recordTargetErrors, &childBatches ); if ( !targetStatus.isOK() ) { _targeter->noteCouldNotTarget(); ++numTargetErrors; continue; } // // Send all child batches // size_t numSent = 0; while ( numSent != childBatches.size() ) { // Collect batches out on the network, mapped by endpoint HostBatchMap pendingBatches; // // Send side // // Get as many batches as we can at once for ( vector<TargetedWriteBatch*>::iterator it = childBatches.begin(); it != childBatches.end(); ++it ) { // // Collect the info needed to dispatch our targeted batch // TargetedWriteBatch* nextBatch = *it; // If the batch is NULL, we sent it previously, so skip if ( nextBatch == NULL ) continue; // Figure out what host we need to dispatch our targeted batch ConnectionString shardHost; Status resolveStatus = _resolver->chooseWriteHost( nextBatch->getEndpoint() .shardName, &shardHost ); if ( !resolveStatus.isOK() ) { ++numResolveFailures; // Record a resolve failure // TODO: It may be necessary to refresh the cache if stale, or maybe just // cancel and retarget the batch BatchedErrorDetail error; buildErrorFrom( resolveStatus, &error ); batchOp.noteBatchError( *nextBatch, error ); // We're done with this batch *it = NULL; continue; } // If we already have a batch for this host, wait until the next time HostBatchMap::iterator pendingIt = pendingBatches.find( shardHost ); if ( pendingIt != pendingBatches.end() ) continue; // // We now have all the info needed to dispatch the batch // BatchedCommandRequest request( clientRequest.getBatchType() ); batchOp.buildBatchRequest( *nextBatch, &request ); // Internally we use full namespaces for request/response, but we send the // command to a database with the collection name in the request. NamespaceString nss( request.getNS() ); request.setNS( nss.coll() ); _dispatcher->addCommand( shardHost, nss.db(), request ); // Indicate we're done by setting the batch to NULL // We'll only get duplicate hostEndpoints if we have broadcast and non-broadcast // endpoints for the same host, so this should be pretty efficient without // moving stuff around. *it = NULL; // Recv-side is responsible for cleaning up the nextBatch when used pendingBatches.insert( make_pair( shardHost, nextBatch ) ); } // Send them all out _dispatcher->sendAll(); numSent += pendingBatches.size(); // // Recv side // while ( _dispatcher->numPending() > 0 ) { // Get the response ConnectionString shardHost; BatchedCommandResponse response; Status dispatchStatus = _dispatcher->recvAny( &shardHost, &response ); // Get the TargetedWriteBatch to find where to put the response dassert( pendingBatches.find( shardHost ) != pendingBatches.end() ); TargetedWriteBatch* batchRaw = pendingBatches.find( shardHost )->second; scoped_ptr<TargetedWriteBatch> batch( batchRaw ); if ( dispatchStatus.isOK() ) { TrackedErrors trackedErrors; trackedErrors.startTracking( ErrorCodes::StaleShardVersion ); // Dispatch was ok, note response batchOp.noteBatchResponse( *batch, response, &trackedErrors ); // Note if anything was stale const vector<ShardError*>& staleErrors = trackedErrors.getErrors( ErrorCodes::StaleShardVersion ); if ( staleErrors.size() > 0 ) { noteStaleResponses( staleErrors, _targeter ); ++numStaleBatches; } } else { // Error occurred dispatching, note it BatchedErrorDetail error; buildErrorFrom( dispatchStatus, &error ); batchOp.noteBatchError( *batch, error ); } } } } batchOp.buildClientResponse( clientResponse ); }
Load::Load(QObject *parent) : QObject(parent), d_ptr(new LoadPrivate(this)) { Q_D(Load); ins = this; setObjectName("Load"); auto avProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString i = task.code.mid(2, sharp - 2); QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1); QString url("http://www.%1/video/av%2/"); url = url.arg(Utils::customUrl(Utils::Bilibili)).arg(i); if (!p.isEmpty()){ url += QString("index_%1.html").arg(p); } forward(QNetworkRequest(url), Page); break; } case Page: { d->model->clear(); QString api, id, video(reply->readAll()); int part = video.indexOf("<select"); if (part != -1 && sharp == -1){ QRegularExpression r("(?<=>).*?(?=</option>)"); QStringRef list(&video, part, video.indexOf("</select>", part) - part); QRegularExpressionMatchIterator i = r.globalMatch(list); api = "http://www.%1/video/%2/index_%3.html"; api = api.arg(Utils::customUrl(Utils::Bilibili)); while (i.hasNext()){ int index = d->model->rowCount() + 1; QStandardItem *item = new QStandardItem; item->setData(QUrl(api.arg(task.code).arg(index)), UrlRole); item->setData((task.code + "#%1").arg(index), StrRole); item->setData(Page, NxtRole); item->setData(Utils::decodeXml(i.next().captured()), Qt::EditRole); d->model->appendRow(item); } } if (d->model->rowCount() > 0){ emit stateChanged(task.state = Part); } else{ QRegularExpression r = QRegularExpression("cid[=\":]*\\d+", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatchIterator i = r.globalMatch(video); while (i.hasNext()){ QString m = i.next().captured(); m = QRegularExpression("\\d+").match(m).captured(); if (id.isEmpty()){ id = m; } else if (id != m){ id.clear(); break; } } if (!id.isEmpty()){ api = "http://comment.%1/%2.xml"; api = api.arg(Utils::customUrl(Utils::Bilibili)); forward(QNetworkRequest(api.arg(id)), File); } else{ emit stateChanged(203); qDebug() << "Fail to load danmaku, try biliApi"; dequeue(); } } break; } case File: { dumpDanmaku(reply->readAll(), Utils::Bilibili, false); emit stateChanged(task.state = None); dequeue(); break; } } }; auto avRegular = [](QString &code){ code.remove(QRegularExpression("/index(?=_\\d+\\.html)")); QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return getRegular(r)(code); }; d->pool.append({ avRegular, 0, avProcess }); auto bbProcess = [this, avProcess](QNetworkReply *reply) { Q_D(Load); Task &task = d->queue.head(); switch (task.state) { case None: { QString i = task.code.mid(2); QString u = "http://www.%1/bangumi/i/%2/"; u = u.arg(Utils::customUrl(Utils::Bilibili)).arg(i); forward(QNetworkRequest(u), Page); break; } case Page: { d->model->clear(); QString page(reply->readAll()); QStringList list = page.split("<li data-index"); if (list.size() < 2) { emit stateChanged(task.state = None); dequeue(); break; } list.removeFirst(); QListIterator<QString> iter(list); iter.toBack(); while (iter.hasPrevious()) { QRegularExpression r; const QString &i = iter.previous(); r.setPattern("(?<=href=\")[^\"]+"); QString c = r.match(i).captured(); fixCode(c); r.setPattern("(?<=<span>).+(?=</span>)"); QString t = Utils::decodeXml(r.match(i).captured()); QStandardItem *item = new QStandardItem; item->setData(c, StrRole); item->setData(None, NxtRole); item->setData(t, Qt::EditRole); d->model->appendRow(item); } emit stateChanged(task.state = Part); } } }; auto bbRegular = [](QString &code) { code.replace(QRegularExpression("bangumi/i/(?=\\d+)"), "bb"); QRegularExpression r("b(b(\\d+)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return getRegular(r)(code); }; d->pool.append({ bbRegular, 0, bbProcess }); auto acProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString i = task.code.mid(2, sharp - 2); QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1); QString url("http://www.%1/v/ac%2"); url = url.arg(Utils::customUrl(Utils::AcFun)).arg(i); if (!p.isEmpty()){ url += QString("_%1").arg(p); } forward(QNetworkRequest(url), Page); break;; } case Page: { d->model->clear(); QRegularExpressionMatchIterator match = QRegularExpression("data-vid.*?</a>").globalMatch(reply->readAll()); while (match.hasNext()){ QStandardItem *item = new QStandardItem; QString part = match.next().captured(); QRegularExpression r; r.setPattern("(?<=>)[^>]+?(?=</a>)"); item->setData(Utils::decodeXml(r.match(part).captured()), Qt::EditRole); r.setPattern("(?<=data-vid=\").+?(?=\")"); QString next("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1"); next = next.arg(Utils::customUrl(Utils::AcFun)).arg(r.match(part).captured()); item->setData(next, UrlRole); item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole); item->setData(File, NxtRole); d->model->appendRow(item); } if (sharp == -1 && d->model->rowCount() >= 2){ emit stateChanged(task.state = Part); } else{ int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1; if (i >= 0 && i < d->model->rowCount()){ forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File); } else{ emit stateChanged(203); dequeue(); } } break; } case File: { QByteArray data = reply->readAll(); if (data != "[[],[],[]]"){ QNetworkRequest &request = task.request; QUrl url = request.url(); int page = QUrlQuery(url).queryItemValue("pageNo").toInt(); url.setQuery(QString()); request.setUrl(url); dumpDanmaku(data, Utils::AcFun, false); QUrlQuery query; query.addQueryItem("pageSize", "1000"); query.addQueryItem("pageNo", QString::number(page + 1)); url.setQuery(query); request.setUrl(url); forward(request, File); } else{ emit stateChanged(task.state = None); dequeue(); } break; } } }; auto acRegular = getRegular(QRegularExpression("a(c(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption)); d->pool.append({ acRegular, 0, acProcess }); auto abProcess = [this, acProcess](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString url("http://www.%1/bangumi/video/page?bangumiId=%2&pageSize=30&pageNo=%3&order=2"); url = url.arg(Utils::customUrl(Utils::AcFun)).arg(task.code.mid(2, sharp - 2)); url = url.arg(sharp == -1 ? 1 : (task.code.mid(sharp + 1).toInt() - 1) / 30 + 1); forward(QNetworkRequest(url), Page); break; } case Page: { if (sharp != -1){ QJsonObject data = QJsonDocument::fromJson(reply->readAll()).object()["data"].toObject(); int i = task.code.mid(sharp + 1).toInt(); if (i > 0){ i = (i - 1) % 30; } else{ i = data["totalCount"].toInt(); if (i > 30){ task.code = task.code.left(sharp) + QString("#%1").arg(i); task.state = None; task.processer->process(nullptr); break; } } QJsonArray list = data["list"].toArray(); if (i < 0 || i >= list.size()){ emit stateChanged(203); dequeue(); break; } QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1"); head = head.arg(Utils::customUrl(Utils::AcFun)); head = head.arg(list[i].toObject()["danmakuId"].toString()); forward(QNetworkRequest(head), File); break; } else{ d->model->clear(); } } case Part: { QJsonObject info = QJsonDocument::fromJson(reply->readAll()).object(); if (!info["success"].toBool() && d->model->rowCount() == 0){ emit stateChanged(info["status"].toInt()); dequeue(); } QJsonObject data = info["data"].toObject(); for (const QJsonValue &value : data["list"].toArray()){ QStandardItem *item = new QStandardItem; QJsonObject data = value.toObject(); item->setData(data["title"].toString(), Qt::EditRole); QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1"); head = head.arg(Utils::customUrl(Utils::AcFun)).arg(data["danmakuId"].toString()); item->setData(head, UrlRole); item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole); item->setData(File, NxtRole); d->model->appendRow(item); } if (task.state != Part){ emit stateChanged(task.state = Part); } if (data["pageNo"].toInt() < data["totalPage"].toInt()){ QUrl url = reply->request().url(); auto arg = QUrlQuery(url).queryItems(); for (auto &p : arg){ if (p.first == "pageNo"){ p.second = QString::number(p.second.toInt() + 1); break; } } QUrlQuery query; query.setQueryItems(arg); url.setQuery(query); d->remain.insert(d->manager.get(QNetworkRequest(url))); } break; } case File: { acProcess(reply); break; } } }; auto abRegular = getRegular(QRegularExpression("a(b(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption)); d->pool.append({ abRegular, 0, abProcess }); auto ccProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString i = task.code.mid(2, sharp - 2); QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1); QString url("http://www.%1/play/h%2/"); url = url.arg(Utils::customUrl(Utils::TuCao)).arg(i); if (!p.isEmpty()){ url += QString("#%1").arg(p); } forward(QNetworkRequest(url), Page); break; } case Page: { QString page = reply->readAll(); d->model->clear(); QRegularExpressionMatch m; QRegularExpression r("(?<=<li>)[^<]*(?=</li>)"); m = r.match(page, page.indexOf("<ul id=\"player_code\"")); QStringList list = m.captured().split("**"); m = r.match(page, m.capturedEnd()); QString code = m.captured(); for (const QString &iter : list){ QStandardItem *item = new QStandardItem; item->setData(iter.mid(iter.indexOf('|') + 1), Qt::EditRole); QString api("http://www.%1/index.php?m=mukio&c=index&a=init&playerID=%2"); api = api.arg(Utils::customUrl(Utils::TuCao)).arg((code + "-%1").arg(d->model->rowCount())); item->setData(api, UrlRole); item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole); item->setData(File, NxtRole); d->model->appendRow(item); } if (sharp == -1 && d->model->rowCount() >= 2){ emit stateChanged(task.state = Part); } else{ int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1; if (i >= 0 && i < d->model->rowCount()){ forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File); } else{ emit stateChanged(203); dequeue(); } } break; } case File: { dumpDanmaku(reply->readAll(), Utils::TuCao, false); emit stateChanged(task.state = None); dequeue(); break; } } }; auto ccRegular = [](QString &code){ code.replace(QRegularExpression("[Hh](?=\\d)"), "cc"); QRegularExpression r("c(c(\\d+([#_])?(\\d+)?)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return getRegular(r)(code); }; d->pool.append({ ccRegular, 0, ccProcess }); d->pool.append(Proc()); Proc *directProc = &d->pool.last(); directProc->process = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); switch (task.state){ case None: { QUrl url = QUrl::fromUserInput(task.code); task.request.setUrl(url); task.state = File; forward(); break; } case File: { Record load; QUrl url = reply->url(); QByteArray data(reply->readAll()); load.source = url.url(); load.access = url.isLocalFile() ? url.toLocalFile() : load.source; load.string = QFileInfo(task.code).fileName(); load.delay = task.delay; QString head = Utils::decodeTxt(data.left(512)); if (head.startsWith("[Script Info]")){ load.danmaku = Parse::parseComment(data, Utils::ASS); } else if (!head.startsWith("<?xml")){ load.danmaku = Parse::parseComment(data, Utils::AcFun); } else if (head.indexOf("<packet>") != -1){ load.danmaku = Parse::parseComment(data, Utils::Niconico); } else if (head.indexOf("<i>") != -1){ load.danmaku = Parse::parseComment(data, Utils::Bilibili); QString i = QRegularExpression("(?<=<chatid>)\\d+(?=</chatid>)").match(head).captured(); if (!i.isEmpty()){ load.source = "http://comment.%1/%2.xml"; load.source = load.source.arg(Utils::customUrl(Utils::Bilibili)).arg(i); } } else if (head.indexOf("<c>") != -1){ load.danmaku = Parse::parseComment(data, Utils::AcfunLocalizer); } if (load.delay != 0){ for (Comment &c : load.danmaku){ c.time += load.delay; } } Danmaku::instance()->appendToPool(&load); emit stateChanged(task.state = None); dequeue(); break; } } }; directProc->priority = -100; directProc->regular = [this, directProc](QString &code){ if (code.startsWith("full?") || code.startsWith("hist?")){ code.clear(); return false; } QUrl u = QUrl::fromUserInput(code); if (!u.host().isEmpty() && !u.path().isEmpty()){ return true; } if (QFileInfo(code).exists()){ return true; } code.clear(); return false; }; auto fullBiProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); switch (task.state) { case None: { emit progressChanged(0); QString api("http://comment.%1/rolldate,%2"); api = api.arg(Utils::customUrl(Utils::Bilibili)); task.code = QUrlQuery(task.code.mid(5)).queryItemValue("source"); forward(QNetworkRequest(api.arg(QFileInfo(task.code).baseName())), Page); break; } case Page: { QByteArray data = reply->readAll(); QJsonArray date = QJsonDocument::fromJson(data).array(); if (date.isEmpty()) { emit stateChanged(203); dequeue(); break; } QJsonObject head = date.first().toObject(); QString url("http://comment.%1/dmroll,%2,%3"); url = url.arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(head["timestamp"].toVariant().toInt()); url = url.arg(QFileInfo(task.code).baseName()); QNetworkRequest request(url); request.setAttribute(QNetworkRequest::User, data); forward(request, Code); break; } case Code: { QByteArray data = task.request.attribute(QNetworkRequest::User).toByteArray(); QJsonArray date = QJsonDocument::fromJson(data).array(); QMap<int, int> count; for (auto iter : date) { QJsonObject item = iter.toObject(); count[item["timestamp"].toVariant().toInt()] += item["new"].toVariant().toInt(); } data = reply->readAll(); if (count.size() >= 2) { int max = QRegularExpression("(?<=\\<max_count\\>).+(?=\\</max_count\\>)").match(data).captured().toInt(); int now = 0; auto getHistory = [d, &count, &task](int date) { QString url("http://comment.%1/dmroll,%2,%3"); url = url.arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(date); url = url.arg(QFileInfo(task.code).baseName()); return d->manager.get(QNetworkRequest(url)); }; for (auto iter = count.begin() + 1;; ++iter) { now += iter.value(); if (iter + 1 == count.end()) { d->remain += getHistory(iter.key()); break; } else if (now + (iter + 1).value() > max) { d->remain += getHistory(iter.key()); now = 0; } } auto pool = QSharedPointer<QVector<Parse::ResultDelegate>>::create(); pool->append(Parse::parseComment(data, Utils::Bilibili)); double total = d->remain.size() + 2; for (QNetworkReply *iter : d->remain) { connect(iter, &QNetworkReply::finished, [=, &task]() { QByteArray data = iter->readAll(); pool->append(Parse::parseComment(data, Utils::Bilibili)); switch (iter->error()) { case QNetworkReply::NoError: emit progressChanged((total - d->remain.size()) / total); case QNetworkReply::OperationCanceledError: if (d->remain.isEmpty() && !pool->empty()) { Record load; load.full = true; for (auto &iter : *pool) { load.danmaku.append(iter); } load.source = task.code; Danmaku::instance()->appendToPool(&load); emit stateChanged(task.state = None); dequeue(); } default: break; } }); } emit progressChanged(2 / total); emit stateChanged(task.state = File); break; } else { emit progressChanged(1); dumpDanmaku(data, Utils::Bilibili, true); emit stateChanged(task.state = None); dequeue(); break; } } } }; auto fullBiRegular = QRegularExpression("^full\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml$"); fullBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption); d->pool.append({ getRegular(fullBiRegular), 100, fullBiProcess }); auto histBiProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); switch (task.state){ case None: { QUrlQuery query(task.code.mid(5)); task.code = query.queryItemValue("source"); QString cid = QFileInfo(task.code).baseName(); QString dat = query.queryItemValue("date"); QString url; QNetworkRequest request; if (dat != "0" && dat.toUInt() != QDateTime(QDate::currentDate()).toTime_t()){ url = QString("http://comment.%1/dmroll,%2,%3"); url = url.arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(dat).arg(cid); int limit = QDateTime(QDateTime::fromTime_t(dat.toInt()).date().addDays(1)).toTime_t(); request.setAttribute(QNetworkRequest::User, limit); } else{ url = QString("http://comment.%1/%2.xml").arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(cid); } request.setUrl(url); forward(request, File); break; } case File: { Record load; load.danmaku = Parse::parseComment(reply->readAll(), Utils::Bilibili); load.source = task.code; for (Record &iter : Danmaku::instance()->getPool()){ if (iter.source == load.source){ iter.full = false; iter.danmaku.clear(); iter.limit = 1; break; } } load.limit = task.request.attribute(QNetworkRequest::User).toInt(); Danmaku::instance()->appendToPool(&load); emit stateChanged(task.state = None); dequeue(); break; } } }; auto histBiRegular = QRegularExpression("^hist\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml&date=\\d+$"); histBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption); d->pool.append({ getRegular(histBiRegular), 100, histBiProcess }); connect(this, &Load::stateChanged, [this](int code){ switch (code){ case None: case Page: case Part: case Code: case File: break; default: { Q_D(Load); if (!d->tryNext()){ emit errorOccured(code); } break; } } }); }
static SLVAL request_remote_addr(sl_vm_t* vm) { return request(vm)->remote_addr; }
static SLVAL request_index(sl_vm_t* vm, SLVAL self, SLVAL name) { (void)self; return sl_dict_get(vm, request(vm)->params, name); }
static SLVAL request_query_string(sl_vm_t* vm) { return request(vm)->query_string; }
static SLVAL request_path_info(sl_vm_t* vm) { return request(vm)->path_info; }
static SLVAL request_uri(sl_vm_t* vm) { return request(vm)->uri; }
void MainResourceLoader::continueAfterContentPolicy(PolicyAction contentPolicy, const ResourceResponse& r) { KURL url = request().url(); const String& mimeType = r.mimeType(); switch (contentPolicy) { case PolicyUse: { // Prevent remote web archives from loading because they can claim to be from any domain and thus avoid cross-domain security checks (4120255). bool isRemoteWebArchive = equalIgnoringCase("application/x-webarchive", mimeType) && !m_substituteData.isValid() && !url.isLocalFile(); if (!frameLoader()->canShowMIMEType(mimeType) || isRemoteWebArchive) { frameLoader()->cannotShowMIMEType(r); // Check reachedTerminalState since the load may have already been cancelled inside of _handleUnimplementablePolicyWithErrorCode::. if (!reachedTerminalState()) stopLoadingForPolicyChange(); return; } break; } case PolicyDownload: // m_handle can be null, e.g. when loading a substitute resource from application cache. if (!m_handle) { receivedError(cannotShowURLError()); return; } frameLoader()->client()->download(m_handle.get(), request(), m_handle.get()->request(), r); // It might have gone missing if (frameLoader()) receivedError(interruptionForPolicyChangeError()); return; case PolicyIgnore: stopLoadingForPolicyChange(); return; default: ASSERT_NOT_REACHED(); } RefPtr<MainResourceLoader> protect(this); if (r.isHTTP()) { int status = r.httpStatusCode(); if (status < 200 || status >= 300) { bool hostedByObject = frameLoader()->isHostedByObjectElement(); frameLoader()->handleFallbackContent(); // object elements are no longer rendered after we fallback, so don't // keep trying to process data from their load if (hostedByObject) cancel(); } } // we may have cancelled this load as part of switching to fallback content if (!reachedTerminalState()) ResourceLoader::didReceiveResponse(r); if (frameLoader() && !frameLoader()->isStopping()) if (m_substituteData.isValid()) { if (m_substituteData.content()->size()) didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true); if (frameLoader() && !frameLoader()->isStopping()) didFinishLoading(); } else if (shouldLoadAsEmptyDocument(url) || frameLoader()->representationExistsForURLScheme(url.protocol())) didFinishLoading(); }
PassRefPtr<IDBRequest> IDBRequest::create(ScriptExecutionContext* context, PassRefPtr<IDBAny> source, IDBTransactionBackendInterface::TaskType taskType, IDBTransaction* transaction) { RefPtr<IDBRequest> request(adoptRef(new IDBRequest(context, source, taskType, transaction))); request->suspendIfNeeded(); return request.release(); }
void XMLHttpRequest::createRequest(ExceptionCode& ec) { #if ENABLE(BLOB) // Only GET request is supported for blob URL. if (m_url.protocolIs("blob") && m_method != "GET") { ec = XMLHttpRequestException::NETWORK_ERR; return; } #endif // The presence of upload event listeners forces us to use preflighting because POSTing to an URL that does not // permit cross origin requests should look exactly like POSTing to an URL that does not respond at all. // Also, only async requests support upload progress events. bool uploadEvents = false; if (m_async) { m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadstartEvent)); if (m_requestEntityBody && m_upload) { uploadEvents = m_upload->hasEventListeners(); m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadstartEvent)); } } m_sameOriginRequest = securityOrigin()->canRequest(m_url); // We also remember whether upload events should be allowed for this request in case the upload listeners are // added after the request is started. m_uploadEventsAllowed = m_sameOriginRequest || uploadEvents || !isSimpleCrossOriginAccessRequest(m_method, m_requestHeaders); ResourceRequest request(m_url); request.setHTTPMethod(m_method); #if PLATFORM(CHROMIUM) || PLATFORM(BLACKBERRY) request.setTargetType(ResourceRequest::TargetIsXHR); #endif InspectorInstrumentation::willLoadXHR(scriptExecutionContext(), this, m_method, m_url, m_async, m_requestEntityBody ? m_requestEntityBody->deepCopy() : 0, m_requestHeaders, m_includeCredentials); if (m_requestEntityBody) { ASSERT(m_method != "GET"); ASSERT(m_method != "HEAD"); request.setHTTPBody(m_requestEntityBody.release()); } if (m_requestHeaders.size() > 0) request.addHTTPHeaderFields(m_requestHeaders); ThreadableLoaderOptions options; options.sendLoadCallbacks = SendCallbacks; options.sniffContent = DoNotSniffContent; options.preflightPolicy = uploadEvents ? ForcePreflight : ConsiderPreflight; options.allowCredentials = (m_sameOriginRequest || m_includeCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials; options.crossOriginRequestPolicy = UseAccessControl; options.securityOrigin = securityOrigin(); m_exceptionCode = 0; m_error = false; if (m_async) { if (m_upload) request.setReportUploadProgress(true); // ThreadableLoader::create can return null here, for example if we're no longer attached to a page. // This is true while running onunload handlers. // FIXME: Maybe we need to be able to send XMLHttpRequests from onunload, <http://bugs.webkit.org/show_bug.cgi?id=10904>. // FIXME: Maybe create() can return null for other reasons too? m_loader = ThreadableLoader::create(scriptExecutionContext(), this, request, options); if (m_loader) { // Neither this object nor the JavaScript wrapper should be deleted while // a request is in progress because we need to keep the listeners alive, // and they are referenced by the JavaScript wrapper. setPendingActivity(this); } } else { InspectorInstrumentation::willLoadXHRSynchronously(scriptExecutionContext()); ThreadableLoader::loadResourceSynchronously(scriptExecutionContext(), request, *this, options); InspectorInstrumentation::didLoadXHRSynchronously(scriptExecutionContext()); } if (!m_exceptionCode && m_error) m_exceptionCode = XMLHttpRequestException::NETWORK_ERR; ec = m_exceptionCode; }
void UpdateWorker::check() const { QNetworkRequest request(Url::VERSION); http->get(request); }
StatusWith<AggregationRequest> AggregationRequest::parseFromBSON( NamespaceString nss, const BSONObj& cmdObj, boost::optional<ExplainOptions::Verbosity> explainVerbosity) { // Parse required parameters. auto pipelineElem = cmdObj[kPipelineName]; auto pipeline = AggregationRequest::parsePipelineFromBSON(pipelineElem); if (!pipeline.isOK()) { return pipeline.getStatus(); } AggregationRequest request(std::move(nss), std::move(pipeline.getValue())); const std::initializer_list<StringData> optionsParsedElseWhere = {kPipelineName, kCommandName}; bool hasCursorElem = false; bool hasExplainElem = false; bool hasFromMongosElem = false; bool hasNeedsMergeElem = false; // Parse optional parameters. for (auto&& elem : cmdObj) { auto fieldName = elem.fieldNameStringData(); if (QueryRequest::kUnwrappedReadPrefField == fieldName) { // We expect this field to be validated elsewhere. request.setUnwrappedReadPref(elem.embeddedObject()); } else if (std::find(optionsParsedElseWhere.begin(), optionsParsedElseWhere.end(), fieldName) != optionsParsedElseWhere.end()) { // Ignore options that are parsed elsewhere. } else if (kCursorName == fieldName) { long long batchSize; auto status = CursorRequest::parseCommandCursorOptions(cmdObj, kDefaultBatchSize, &batchSize); if (!status.isOK()) { return status; } hasCursorElem = true; request.setBatchSize(batchSize); } else if (kCollationName == fieldName) { if (elem.type() != BSONType::Object) { return {ErrorCodes::TypeMismatch, str::stream() << kCollationName << " must be an object, not a " << typeName(elem.type())}; } request.setCollation(elem.embeddedObject().getOwned()); } else if (QueryRequest::cmdOptionMaxTimeMS == fieldName) { auto maxTimeMs = QueryRequest::parseMaxTimeMS(elem); if (!maxTimeMs.isOK()) { return maxTimeMs.getStatus(); } request.setMaxTimeMS(maxTimeMs.getValue()); } else if (repl::ReadConcernArgs::kReadConcernFieldName == fieldName) { if (elem.type() != BSONType::Object) { return {ErrorCodes::TypeMismatch, str::stream() << repl::ReadConcernArgs::kReadConcernFieldName << " must be an object, not a " << typeName(elem.type())}; } request.setReadConcern(elem.embeddedObject().getOwned()); } else if (kHintName == fieldName) { if (BSONType::Object == elem.type()) { request.setHint(elem.embeddedObject()); } else if (BSONType::String == elem.type()) { request.setHint(BSON("$hint" << elem.valueStringData())); } else { return Status(ErrorCodes::FailedToParse, str::stream() << kHintName << " must be specified as a string representing an index" << " name, or an object representing an index's key pattern"); } } else if (kCommentName == fieldName) { if (elem.type() != BSONType::String) { return {ErrorCodes::TypeMismatch, str::stream() << kCommentName << " must be a string, not a " << typeName(elem.type())}; } request.setComment(elem.str()); } else if (kExplainName == fieldName) { if (elem.type() != BSONType::Bool) { return {ErrorCodes::TypeMismatch, str::stream() << kExplainName << " must be a boolean, not a " << typeName(elem.type())}; } hasExplainElem = true; if (elem.Bool()) { request.setExplain(ExplainOptions::Verbosity::kQueryPlanner); } } else if (kFromMongosName == fieldName) { if (elem.type() != BSONType::Bool) { return {ErrorCodes::TypeMismatch, str::stream() << kFromMongosName << " must be a boolean, not a " << typeName(elem.type())}; } hasFromMongosElem = true; request.setFromMongos(elem.Bool()); } else if (kNeedsMergeName == fieldName) { if (elem.type() != BSONType::Bool) { return {ErrorCodes::TypeMismatch, str::stream() << kNeedsMergeName << " must be a boolean, not a " << typeName(elem.type())}; } hasNeedsMergeElem = true; request.setNeedsMerge(elem.Bool()); } else if (kAllowDiskUseName == fieldName) { if (storageGlobalParams.readOnly) { return {ErrorCodes::IllegalOperation, str::stream() << "The '" << kAllowDiskUseName << "' option is not permitted in read-only mode."}; } else if (elem.type() != BSONType::Bool) { return {ErrorCodes::TypeMismatch, str::stream() << kAllowDiskUseName << " must be a boolean, not a " << typeName(elem.type())}; } request.setAllowDiskUse(elem.Bool()); } else if (bypassDocumentValidationCommandOption() == fieldName) { request.setBypassDocumentValidation(elem.trueValue()); } else if (!isGenericArgument(fieldName)) { return {ErrorCodes::FailedToParse, str::stream() << "unrecognized field '" << elem.fieldName() << "'"}; } } if (explainVerbosity) { if (hasExplainElem) { return { ErrorCodes::FailedToParse, str::stream() << "The '" << kExplainName << "' option is illegal when a explain verbosity is also provided"}; } request.setExplain(explainVerbosity); } // 'hasExplainElem' implies an aggregate command-level explain option, which does not require // a cursor argument. if (!hasCursorElem && !hasExplainElem) { return {ErrorCodes::FailedToParse, str::stream() << "The '" << kCursorName << "' option is required, except for aggregate with the explain argument"}; } if (request.getExplain() && cmdObj[WriteConcernOptions::kWriteConcernField]) { return {ErrorCodes::FailedToParse, str::stream() << "Aggregation explain does not support the'" << WriteConcernOptions::kWriteConcernField << "' option"}; } if (hasNeedsMergeElem && !hasFromMongosElem) { return {ErrorCodes::FailedToParse, str::stream() << "Cannot specify '" << kNeedsMergeName << "' without '" << kFromMongosName << "'"}; } return request; }
void VideoCapture::capture() { request(); }
QByteArray QgsSvgCache::getImageData( const QString &path ) const { // is it a path to local file? QFile svgFile( path ); if ( svgFile.exists() ) { if ( svgFile.open( QIODevice::ReadOnly ) ) { return svgFile.readAll(); } else { return mMissingSvg; } } // maybe it's a url... if ( !path.contains( "://" ) ) // otherwise short, relative SVG paths might be considered URLs { return mMissingSvg; } QUrl svgUrl( path ); if ( !svgUrl.isValid() ) { return mMissingSvg; } // check whether it's a url pointing to a local file if ( svgUrl.scheme().compare( "file", Qt::CaseInsensitive ) == 0 ) { svgFile.setFileName( svgUrl.toLocalFile() ); if ( svgFile.exists() ) { if ( svgFile.open( QIODevice::ReadOnly ) ) { return svgFile.readAll(); } } // not found... return mMissingSvg; } // the url points to a remote resource, download it! QNetworkReply *reply = nullptr; // The following code blocks until the file is downloaded... // TODO: use signals to get reply finished notification, in this moment // it's executed while rendering. while ( 1 ) { QgsDebugMsg( QString( "get svg: %1" ).arg( svgUrl.toString() ) ); QNetworkRequest request( svgUrl ); request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache ); request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true ); reply = QgsNetworkAccessManager::instance()->get( request ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( downloadProgress( qint64, qint64 ) ) ); //emit statusChanged( tr( "Downloading svg." ) ); // wait until the image download finished // TODO: connect to the reply->finished() signal while ( !reply->isFinished() ) { QCoreApplication::processEvents( QEventLoop::ExcludeUserInputEvents, 500 ); } if ( reply->error() != QNetworkReply::NoError ) { QgsMessageLog::logMessage( tr( "SVG request failed [error: %1 - url: %2]" ).arg( reply->errorString(), reply->url().toString() ), tr( "SVG" ) ); reply->deleteLater(); return QByteArray(); } QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute ); if ( redirect.isNull() ) { // neither network error nor redirection // TODO: cache the image break; } // do a new request to the redirect url svgUrl = redirect.toUrl(); reply->deleteLater(); } QVariant status = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ); if ( !status.isNull() && status.toInt() >= 400 ) { QVariant phrase = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ); QgsMessageLog::logMessage( tr( "SVG request error [status: %1 - reason phrase: %2]" ).arg( status.toInt() ).arg( phrase.toString() ), tr( "SVG" ) ); reply->deleteLater(); return mMissingSvg; } QString contentType = reply->header( QNetworkRequest::ContentTypeHeader ).toString(); QgsDebugMsg( "contentType: " + contentType ); if ( !contentType.startsWith( "image/svg+xml", Qt::CaseInsensitive ) ) { reply->deleteLater(); return mMissingSvg; } // read the image data QByteArray ba = reply->readAll(); reply->deleteLater(); return ba; }
const KURL& DocumentLoader::requestURL() const { return request().url(); }
void QWsServer::dataReceived() { QTcpSocket * tcpSocket = qobject_cast<QTcpSocket*>( sender() ); if (tcpSocket == 0) return; bool allHeadersFetched = false; const QLatin1String emptyLine("\r\n"); while ( tcpSocket->canReadLine() ) { QString line = tcpSocket->readLine(); if (line == emptyLine) { allHeadersFetched = true; break; } headerBuffer[ tcpSocket ].append(line); } if (!allHeadersFetched) return; QString request( headerBuffer[ tcpSocket ].join("") ); QRegExp regExp; regExp.setMinimal( true ); // Extract mandatory datas // Version regExp.setPattern( QWsServer::regExpVersionStr ); regExp.indexIn(request); QString versionStr = regExp.cap(1); EWebsocketVersion version; if ( ! versionStr.isEmpty() ) { version = (EWebsocketVersion)versionStr.toInt(); } else if ( tcpSocket->bytesAvailable() >= 8 ) { version = WS_V0; request.append( tcpSocket->read(8) ); } else { version = WS_VUnknow; } // Resource name regExp.setPattern( QWsServer::regExpResourceNameStr ); regExp.indexIn(request); QString resourceName = regExp.cap(1); // Host (address & port) regExp.setPattern( QWsServer::regExpHostStr ); regExp.indexIn(request); QString host = regExp.cap(1); QStringList hostTmp = host.split(':'); QString hostAddress = hostTmp[0]; QString hostPort; if ( hostTmp.size() > 1 ) hostPort = hostTmp.last(); // fix for IPv6 // Key QString key, key1, key2, key3; if ( version >= WS_V4 ) { regExp.setPattern( QWsServer::regExpKeyStr ); regExp.indexIn(request); key = regExp.cap(1); } else { regExp.setPattern( QWsServer::regExpKey1Str ); regExp.indexIn(request); key1 = regExp.cap(1); regExp.setPattern( QWsServer::regExpKey2Str ); regExp.indexIn(request); key2 = regExp.cap(1); regExp.setPattern( QWsServer::regExpKey3Str ); regExp.indexIn(request); key3 = regExp.cap(1); } //////////////////////////////////////////////////////////////////// // If the mandatory fields are not specified, we abord the connection to the Websocket server if ( version == WS_VUnknow || resourceName.isEmpty() || hostAddress.isEmpty() || ( key.isEmpty() && ( key1.isEmpty() || key2.isEmpty() || key3.isEmpty() ) ) ) { // Send bad request response QString response = QWsServer::composeBadRequestResponse( QList<EWebsocketVersion>() << WS_V6 << WS_V7 << WS_V8 << WS_V13 ); tcpSocket->write( response.toUtf8() ); tcpSocket->flush(); return; } //////////////////////////////////////////////////////////////////// // Extract optional datas // Origin regExp.setPattern( QWsServer::regExpOriginStr ); if ( regExp.indexIn(request) == -1 ) { regExp.setPattern( QWsServer::regExpOrigin2Str ); regExp.indexIn(request); } QString origin = regExp.cap(1); // Protocol regExp.setPattern( QWsServer::regExpProtocolStr ); regExp.indexIn(request); QString protocol = regExp.cap(1); // Extensions regExp.setPattern( QWsServer::regExpExtensionsStr ); regExp.indexIn(request); QString extensions = regExp.cap(1); //////////////////////////////////////////////////////////////////// // Compose opening handshake response QString response; if ( version >= WS_V6 ) { QString accept = computeAcceptV4( key ); response = QWsServer::composeOpeningHandshakeResponseV6( accept, protocol ); } else if ( version >= WS_V4 ) { QString accept = computeAcceptV4( key ); QString nonce = generateNonce(); response = QWsServer::composeOpeningHandshakeResponseV4( accept, nonce, protocol ); } else { QString accept = computeAcceptV0( key1, key2, key3 ); response = QWsServer::composeOpeningHandshakeResponseV0( accept, origin, hostAddress, hostPort, resourceName , protocol ); } // Handshake OK, disconnect readyRead disconnect( tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()) ); // Send opening handshake response if ( version == WS_V0 ) tcpSocket->write( response.toLatin1() ); else tcpSocket->write( response.toUtf8() ); tcpSocket->flush(); QWsSocket * wsSocket = new QWsSocket( this, tcpSocket, version ); wsSocket->setResourceName( resourceName ); wsSocket->setHost( host ); wsSocket->setHostAddress( hostAddress ); wsSocket->setHostPort( hostPort.toInt() ); wsSocket->setOrigin( origin ); wsSocket->setProtocol( protocol ); wsSocket->setExtensions( extensions ); wsSocket->serverSideSocket = true; // ORIGINAL CODE //int socketDescriptor = tcpSocket->socketDescriptor(); //incomingConnection( socketDescriptor ); // CHANGED CODE FOR LINUX COMPATIBILITY addPendingConnection( wsSocket ); emit newConnection(); }
void B9UpdateManager::OnRecievedReply(QNetworkReply* reply) { timeoutTimer.stop(); if(ignoreReplies) { currentReply->deleteLater(); currentReply = NULL; return; } if(reply->bytesAvailable() == 0)//nothing downloaded. { qDebug() << "B9Update Manager, zero bytes downloaded."; if(!silentUpdateChecking) { QMessageBox msgBox; msgBox.setText("Online Update Attempt Failed."); if(downloadState == "DownloadingFileVersions") { waitingbar->hide(); msgBox.setInformativeText("You may use a B9Creator update pack if available. \nBrowse to a local update pack now?"); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int ret = msgBox.exec(); if(ret == QMessageBox::Ok) { ResetEverything(); PromptDoUpdates(true,true); return; }//if no - continue to reset below. } else { msgBox.setInformativeText("please check your internet connection."); msgBox.exec(); } } ResetEverything(); return; } if(downloadState == "DownloadingFileVersions") { //remoteEntries - localEntries = updateEntries CopyInRemoteEntries(); CopyInLocalEntries(); CalculateUpdateEntries(); //so now we have a big list of local things that need updated... if(updateEntries.size() > 0) { waitingbar->hide(); QMessageBox msgBox; msgBox.setIcon(QMessageBox::Question); if(updateEntries.size() == 1) { msgBox.setText("There is " + QString::number(updateEntries.size()) + " file update available."); msgBox.setInformativeText("Do you want to update it? <a href=\"http://b9creator.com/softwaredelta\">View change log</a>"); } else { msgBox.setText("There are " + QString::number(updateEntries.size()) + " file updates available."); msgBox.setInformativeText("Do you want to update them? <a href=\"http://b9creator.com/softwaredelta\">View change log</a>"); } msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int doUpdates = msgBox.exec(); currentUpdateIndx = 0;//at this point we know we can iterate through //needed updates if(doUpdates == QMessageBox::Yes) { waitingbar->show(); downloadState = "DownloadingFiles";//next state //send a new request currentReply->deleteLater(); currentReply = NULL; //request the file in the right directory on the server QNetworkRequest request(QUrl(RemoteManifestPath + updateEntries[currentUpdateIndx].OSDir + updateEntries[currentUpdateIndx].fileName)); StartNewDownload(request); } else//no { ResetEverything(); } } else { ResetEverything(); emit NotifyUpdateFinished();//emit update finished signal if(!silentUpdateChecking) { QMessageBox msgBox; msgBox.setText("All files are up to date"); msgBox.setIcon(QMessageBox::Information); msgBox.exec(); } } } else if(downloadState == "DownloadingFiles") { //lets put the file in the temp directory if(!OnDownloadDone()) { //bail ResetEverything(); return; } if(currentUpdateIndx < updateEntries.size() - 1) { currentUpdateIndx++; currentReply->deleteLater(); currentReply = NULL; QNetworkRequest request(QUrl(RemoteManifestPath + updateEntries[currentUpdateIndx].OSDir + updateEntries[currentUpdateIndx].fileName)); StartNewDownload(request); } else { if(!CopyFromTemp()) { //bail qDebug() << "UpdateManager: Unable To Copy Files From Temp Directory"; QMessageBox msgBox; msgBox.setText("Unable to update,\nUnable To Copy Files From Temp Directory."); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); ResetEverything(); return; } if(!UpdateLocalFileVersionList()) { qDebug() << "UpdateManager: Unable To overwrite local FileVersions.txt"; QMessageBox msgBox; msgBox.setText("Unable to update,\nUnable To overwrite local FileVersions.txt."); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); ResetEverything(); return; } waitingbar->hide(); QMessageBox msgBox; msgBox.setIcon(QMessageBox::Information); msgBox.setText("All files up to date"); msgBox.setInformativeText("Please Re-Launch B9Creator."); msgBox.exec(); ResetEverything(); //Safely Exit the Program..... QCoreApplication::exit(); } } }
int QgsGml::getFeatures( const QString& uri, QGis::WkbType* wkbType, QgsRectangle* extent, const QString& userName, const QString& password , const QString& authcfg ) { //start with empty extent mExtent.setMinimal(); QNetworkRequest request( uri ); if ( !authcfg.isEmpty() ) { if ( !QgsAuthManager::instance()->updateNetworkRequest( request, authcfg ) ) { QgsMessageLog::logMessage( tr( "GML Getfeature network request update failed for authcfg %1" ).arg( authcfg ), tr( "Network" ), QgsMessageLog::CRITICAL ); return 1; } } else if ( !userName.isNull() || !password.isNull() ) { request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( userName, password ).toAscii().toBase64() ); } QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request ); connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) ); //find out if there is a QGIS main window. If yes, display a progress dialog QProgressDialog* progressDialog = nullptr; QWidget* mainWindow = nullptr; QWidgetList topLevelWidgets = qApp->topLevelWidgets(); for ( QWidgetList::const_iterator it = topLevelWidgets.constBegin(); it != topLevelWidgets.constEnd(); ++it ) { if (( *it )->objectName() == "QgisApp" ) { mainWindow = *it; break; } } if ( mainWindow ) { progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow ); progressDialog->setWindowModality( Qt::ApplicationModal ); connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) ); connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) ); connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) ); progressDialog->show(); } int atEnd = 0; while ( !atEnd ) { if ( mFinished ) { atEnd = 1; } QByteArray readData = reply->readAll(); if ( !readData.isEmpty() ) { QString errorMsg; if ( !mParser.processData( readData, atEnd, errorMsg ) ) QgsMessageLog::logMessage( errorMsg, QObject::tr( "WFS" ) ); } QCoreApplication::processEvents(); } fillMapsFromParser(); QNetworkReply::NetworkError replyError = reply->error(); QString replyErrorString = reply->errorString(); delete reply; delete progressDialog; if ( replyError ) { QgsMessageLog::logMessage( tr( "GML Getfeature network request failed with error: %1" ).arg( replyErrorString ), tr( "Network" ), QgsMessageLog::CRITICAL ); return 1; } *wkbType = mParser.wkbType(); if ( *wkbType != QGis::WKBNoGeometry ) { if ( mExtent.isEmpty() ) { //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features calculateExtentFromFeatures(); } } if ( extent ) *extent = mExtent; return 0; }
bool Downloader::go(const QUrl& url) { return request("GET", url, QString()); }
void InspectorResourceContentLoader::start() { m_started = true; Vector<Document*> documents; for (Frame* frame = m_inspectedFrame; frame; frame = frame->tree().traverseNext(m_inspectedFrame)) { if (!frame->isLocalFrame()) continue; LocalFrame* localFrame = toLocalFrame(frame); documents.append(localFrame->document()); documents.appendVector(InspectorPageAgent::importsForFrame(localFrame)); } for (Document* document : documents) { HashSet<String> urlsToFetch; ResourceRequest resourceRequest; HistoryItem* item = document->frame() ? document->frame()->loader().currentItem() : nullptr; if (item) { resourceRequest = FrameLoader::resourceRequestFromHistoryItem(item, ReturnCacheDataDontLoad); } else { resourceRequest = document->url(); resourceRequest.setCachePolicy(ReturnCacheDataDontLoad); } resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal); if (!resourceRequest.url().string().isEmpty()) { urlsToFetch.add(resourceRequest.url().string()); FetchRequest request(resourceRequest, FetchInitiatorTypeNames::internal); ResourcePtr<Resource> resource = RawResource::fetch(request, document->fetcher()); if (resource) { // Prevent garbage collection by holding a reference to this resource. m_resources.append(resource.get()); ResourceClient* resourceClient = new ResourceClient(this); m_pendingResourceClients.add(resourceClient); resourceClient->waitForResource(resource.get()); } } WillBeHeapVector<RawPtrWillBeMember<CSSStyleSheet> > styleSheets; InspectorCSSAgent::collectAllDocumentStyleSheets(document, styleSheets); for (CSSStyleSheet* styleSheet : styleSheets) { if (styleSheet->isInline() || !styleSheet->contents()->loadCompleted()) continue; String url = styleSheet->baseURL().string(); if (url.isEmpty() || urlsToFetch.contains(url)) continue; urlsToFetch.add(url); FetchRequest request(ResourceRequest(url), FetchInitiatorTypeNames::internal); request.mutableResourceRequest().setRequestContext(WebURLRequest::RequestContextInternal); ResourcePtr<Resource> resource = CSSStyleSheetResource::fetch(request, document->fetcher()); if (!resource) continue; // Prevent garbage collection by holding a reference to this resource. m_resources.append(resource.get()); ResourceClient* resourceClient = new ResourceClient(this); m_pendingResourceClients.add(resourceClient); resourceClient->waitForResource(resource.get()); } } m_allRequestsStarted = true; checkDone(); }
void QWsServer::dataReceived() { QTcpSocket * clientSocket = qobject_cast<QTcpSocket*>(sender()); if (clientSocket == 0) return; QString request( clientSocket->readAll() ); QRegExp regExp; regExp.setMinimal( true ); // Extract mandatory datas // Version regExp.setPattern( QWsServer::regExpVersionStr ); regExp.indexIn(request); QString versionStr = regExp.cap(1); int version = 0; if ( ! versionStr.isEmpty() ) version = versionStr.toInt(); // Resource name regExp.setPattern( QWsServer::regExpResourceNameStr ); regExp.indexIn(request); QString resourceName = regExp.cap(1); // Host (address & port) regExp.setPattern( QWsServer::regExpHostStr ); regExp.indexIn(request); QStringList sl = regExp.cap(1).split(':'); QString hostAddress = sl[0]; QString hostPort; if ( sl.size() > 1 ) hostPort = sl[1]; // Key QString key, key1, key2, key3; if ( version >= 6 ) { regExp.setPattern( QWsServer::regExpKeyStr ); regExp.indexIn(request); key = regExp.cap(1); } else { regExp.setPattern( QWsServer::regExpKey1Str ); regExp.indexIn(request); key1 = regExp.cap(1); regExp.setPattern( QWsServer::regExpKey2Str ); regExp.indexIn(request); key2 = regExp.cap(1); regExp.setPattern( QWsServer::regExpKey3Str ); regExp.indexIn(request); key3 = regExp.cap(1); } // Extract optional datas // Origin QString origin; if ( version < 6 || version > 8 ) { regExp.setPattern( QWsServer::regExpOriginStr ); regExp.indexIn(request); origin = regExp.cap(1); } else { regExp.setPattern( QWsServer::regExpOriginV6Str ); regExp.indexIn(request); origin = regExp.cap(1); } // Protocol regExp.setPattern( QWsServer::regExpProtocolStr ); regExp.indexIn(request); QString protocol = regExp.cap(1); // Extensions regExp.setPattern( QWsServer::regExpExtensionsStr ); regExp.indexIn(request); QString extensions = regExp.cap(1); //////////////////////////////////////////////////////////////////// if ( version < 6 ) { qDebug() << "======== Handshake Received \n" << request << "======== \n"; } // If the mandatory params are not setted, we abord the connection to the Websocket server if ( hostAddress.isEmpty() || resourceName.isEmpty() || ( key.isEmpty() && ( key1.isEmpty() || key2.isEmpty() || key3.isEmpty() ) ) ) return; //////////////////////////////////////////////////////////////////// // Compose handshake answer QString answer; QString accept; if ( version >= 6 ) { accept = computeAcceptV2( key ); answer.append("HTTP/1.1 101 Switching Protocols\r\n"); answer.append("Upgrade: websocket\r\n"); answer.append("Connection: Upgrade\r\n"); answer.append("Sec-WebSocket-Accept: " + accept + "\r\n" + "\r\n"); } else if ( version < 6 ) { accept = computeAcceptV1( key1, key2, key3 ); answer.append("HTTP/1.1 101 WebSocket Protocol Handshake\r\n"); answer.append("Upgrade: Websocket\r\n"); answer.append("Connection: Upgrade\r\n"); answer.append("Sec-WebSocket-Origin: " + origin + "\r\n"); answer.append("Sec-WebSocket-Location: ws://" + hostAddress + ( hostPort.isEmpty() ? "" : (":"+hostPort) ) + resourceName + "\r\n"); if ( !protocol.isEmpty() ) answer.append("Sec-WebSocket-Protocol: " + protocol + "\r\n"); answer.append( accept ); } if ( version < 6 ) { qDebug() << "======== Handshake sent \n" << answer << "======== \n"; } // Handshake OK, new connection disconnect(clientSocket, SIGNAL(readyRead()), this, SLOT(dataReceived())); // Send handshake answer clientSocket->write( answer.toUtf8() ); clientSocket->flush(); // TEMPORARY CODE FOR LINUX COMPATIBILITY QWsSocket * wsSocket = new QWsSocket( clientSocket, this ); addPendingConnection( wsSocket ); emit newConnection(); /* // ORIGINAL CODE int socketDescriptor = clientSocket->socketDescriptor(); incomingConnection( socketDescriptor ); */ }
ResourceError MainResourceLoader::interruptionForPolicyChangeError() const { return frameLoader()->interruptionForPolicyChangeError(request()); }
static SLVAL request_cookies(sl_vm_t* vm) { return request(vm)->cookies; }