void nsHttpConnectionMgr::OnMsgPrintDiagnostics(int32_t, ARefBase *) { MOZ_ASSERT(OnSocketThread(), "not on socket thread"); nsCOMPtr<nsIConsoleService> consoleService = do_GetService(NS_CONSOLESERVICE_CONTRACTID); if (!consoleService) return; mLogData.AppendPrintf("HTTP Connection Diagnostics\n---------------------\n"); mLogData.AppendPrintf("IsSpdyEnabled() = %d\n", gHttpHandler->IsSpdyEnabled()); mLogData.AppendPrintf("MaxSocketCount() = %d\n", gHttpHandler->MaxSocketCount()); mLogData.AppendPrintf("mNumActiveConns = %d\n", mNumActiveConns); mLogData.AppendPrintf("mNumIdleConns = %d\n", mNumIdleConns); for (auto iter = mCT.Iter(); !iter.Done(); iter.Next()) { RefPtr<nsConnectionEntry> ent = iter.Data(); mLogData.AppendPrintf(" ent host = %s hashkey = %s\n", ent->mConnInfo->Origin(), ent->mConnInfo->HashKey().get()); mLogData.AppendPrintf(" AtActiveConnectionLimit = %d\n", AtActiveConnectionLimit(ent, NS_HTTP_ALLOW_KEEPALIVE)); mLogData.AppendPrintf(" RestrictConnections = %d\n", RestrictConnections(ent)); mLogData.AppendPrintf(" Pending Q Length = %zu\n", ent->PendingQLength()); mLogData.AppendPrintf(" Active Conns Length = %zu\n", ent->mActiveConns.Length()); mLogData.AppendPrintf(" Idle Conns Length = %zu\n", ent->mIdleConns.Length()); mLogData.AppendPrintf(" Half Opens Length = %zu\n", ent->mHalfOpens.Length()); mLogData.AppendPrintf(" Coalescing Keys Length = %zu\n", ent->mCoalescingKeys.Length()); mLogData.AppendPrintf(" Spdy using = %d\n", ent->mUsingSpdy); uint32_t i; for (i = 0; i < ent->mActiveConns.Length(); ++i) { mLogData.AppendPrintf(" :: Active Connection #%u\n", i); ent->mActiveConns[i]->PrintDiagnostics(mLogData); } for (i = 0; i < ent->mIdleConns.Length(); ++i) { mLogData.AppendPrintf(" :: Idle Connection #%u\n", i); ent->mIdleConns[i]->PrintDiagnostics(mLogData); } for (i = 0; i < ent->mHalfOpens.Length(); ++i) { mLogData.AppendPrintf(" :: Half Open #%u\n", i); ent->mHalfOpens[i]->PrintDiagnostics(mLogData); } i = 0; for (auto it = ent->mPendingTransactionTable.Iter(); !it.Done(); it.Next()) { mLogData.AppendPrintf(" :: Pending Transactions with Window ID = %" PRIu64 "\n", it.Key()); for (uint32_t j = 0; j < it.UserData()->Length(); ++j) { mLogData.AppendPrintf(" ::: Pending Transaction #%u\n", i); it.UserData()->ElementAt(j)->PrintDiagnostics(mLogData); ++i; } } for (i = 0; i < ent->mCoalescingKeys.Length(); ++i) { mLogData.AppendPrintf(" :: Coalescing Key #%u %s\n", i, ent->mCoalescingKeys[i].get()); } } consoleService->LogStringMessage(NS_ConvertUTF8toUTF16(mLogData).Data()); mLogData.Truncate(); }
nsresult GetSlotWithMechanism(uint32_t aMechanism, nsIInterfaceRequestor *m_ctx, PK11SlotInfo** aSlot) { nsNSSShutDownPreventionLock locker; PK11SlotList * slotList = nullptr; PRUnichar** tokenNameList = nullptr; nsITokenDialogs * dialogs; PRUnichar *unicodeTokenChosen; PK11SlotListElement *slotElement, *tmpSlot; uint32_t numSlots = 0, i = 0; bool canceled; nsresult rv = NS_OK; *aSlot = nullptr; // Get the slot slotList = PK11_GetAllTokens(MapGenMechToAlgoMech(aMechanism), true, true, m_ctx); if (!slotList || !slotList->head) { rv = NS_ERROR_FAILURE; goto loser; } if (!slotList->head->next) { /* only one slot available, just return it */ *aSlot = slotList->head->slot; } else { // Gerenate a list of slots and ask the user to choose // tmpSlot = slotList->head; while (tmpSlot) { numSlots++; tmpSlot = tmpSlot->next; } // Allocate the slot name buffer // tokenNameList = static_cast<PRUnichar**>(nsMemory::Alloc(sizeof(PRUnichar *) * numSlots)); if (!tokenNameList) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } i = 0; slotElement = PK11_GetFirstSafe(slotList); while (slotElement) { tokenNameList[i] = UTF8ToNewUnicode(nsDependentCString(PK11_GetTokenName(slotElement->slot))); slotElement = PK11_GetNextSafe(slotList, slotElement, false); if (tokenNameList[i]) i++; else { // OOM. adjust numSlots so we don't free unallocated memory. numSlots = i; PK11_FreeSlotListElement(slotList, slotElement); rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } } /* Throw up the token list dialog and get back the token */ rv = getNSSDialogs((void**)&dialogs, NS_GET_IID(nsITokenDialogs), NS_TOKENDIALOGS_CONTRACTID); if (NS_FAILED(rv)) goto loser; { nsPSMUITracker tracker; if (!tokenNameList || !*tokenNameList) { rv = NS_ERROR_OUT_OF_MEMORY; } else if (tracker.isUIForbidden()) { rv = NS_ERROR_NOT_AVAILABLE; } else { rv = dialogs->ChooseToken(m_ctx, (const PRUnichar**)tokenNameList, numSlots, &unicodeTokenChosen, &canceled); } } NS_RELEASE(dialogs); if (NS_FAILED(rv)) goto loser; if (canceled) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; } // Get the slot // slotElement = PK11_GetFirstSafe(slotList); nsAutoString tokenStr(unicodeTokenChosen); while (slotElement) { if (tokenStr.Equals(NS_ConvertUTF8toUTF16(PK11_GetTokenName(slotElement->slot)))) { *aSlot = slotElement->slot; PK11_FreeSlotListElement(slotList, slotElement); break; } slotElement = PK11_GetNextSafe(slotList, slotElement, false); } if(!(*aSlot)) { rv = NS_ERROR_FAILURE; goto loser; } } // Get a reference to the slot // PK11_ReferenceSlot(*aSlot); loser: if (slotList) { PK11_FreeSlotList(slotList); } if (tokenNameList) { NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(numSlots, tokenNameList); } return rv; }
NS_IMETHODIMP KDEWallet::FindLogins(PRUint32 *count, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo ***logins) { PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLogins() Called") ); *count = 0; nsresult res = checkWallet(); NS_ENSURE_SUCCESS(res, res); QString key = generateQueryWalletKey( aHostname, aActionURL, aHttpRealm, NS_ConvertUTF8toUTF16( "*" ) ); QMap< QString, QMap< QString, QString > > entryMap; if( wallet->readMapList( key, entryMap ) != 0 ) return NS_OK; PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLogins() Found %d maps", entryMap.count() ) ); if( entryMap.count() == 0 ) return NS_OK; nsILoginInfo **array = (nsILoginInfo**) nsMemory::Alloc(entryMap.count() * sizeof(nsILoginInfo*)); NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY); memset(array, 0, entryMap.count() * sizeof(nsILoginInfo*)); QMapIterator< QString, QMap< QString, QString > > iterator(entryMap); int i = 0; while (iterator.hasNext()) { iterator.next(); QMap< QString, QString > entry = iterator.value(); nsCOMPtr<nsILoginInfo> loginInfo = do_CreateInstance(NS_LOGININFO_CONTRACTID); NS_ADDREF((nsILoginInfo*) loginInfo); if (!loginInfo) return NS_ERROR_FAILURE; nsAutoString temp; if( entry.contains( kHostnameAttr ) ) loginInfo->SetHostname( QtString2NSString( entry.value( kHostnameAttr ) ) ); if( entry.contains( kUsernameAttr ) ) loginInfo->SetUsername(QtString2NSString( entry.value( kUsernameAttr ) ) ); if( entry.contains( kUsernameFieldAttr ) ) loginInfo->SetUsernameField(QtString2NSString( entry.value( kUsernameFieldAttr ) ) ); if( entry.contains( kPasswordAttr ) ) loginInfo->SetPassword(QtString2NSString( entry.value( kPasswordAttr ) ) ); if( entry.contains( kPasswordFieldAttr ) ) loginInfo->SetPasswordField(QtString2NSString( entry.value( kPasswordFieldAttr ) ) ); if( entry.contains( kFormSubmitURLAttr ) ) loginInfo->SetFormSubmitURL(QtString2NSString( entry.value( kFormSubmitURLAttr ) ) ); if( entry.contains( kHttpRealmAttr ) ) loginInfo->SetHttpRealm(QtString2NSString( entry.value( kHttpRealmAttr ) ) ); if( entry.contains( kGuidAttr ) ) { nsCOMPtr<nsILoginMetaInfo> loginmeta( do_QueryInterface(loginInfo, &res) ); NS_ENSURE_SUCCESS(res, res); nsAutoString aGUID ; res = loginmeta->SetGuid(QtString2NSString( entry.value( kGuidAttr ) )); NS_ENSURE_SUCCESS(res, res); } PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLogins() Found key: %s guid: %s", iterator.key().toUtf8().data(), entry.value( kGuidAttr ).toUtf8().data() ) ); array[i] = loginInfo; i++; } *logins = array; *count = i; return NS_OK; }
/** entry point */ int main(int argc, char *argv[]) { const char *uuid = NULL; int c; int listHostModes = 0; int quit = 0; const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "startvm", required_argument, NULL, 's' }, { "fixedres", required_argument, NULL, 'f' }, { "listhostmodes", no_argument, NULL, 'l' }, { "scale", no_argument, NULL, 'c' } }; printf("VirtualBox DirectFB GUI built %s %s\n" "(C) 2004-" VBOX_C_YEAR " " VBOX_VENDOR "\n" "(C) 2004-2005 secunet Security Networks AG\n", __DATE__, __TIME__); for (;;) { c = getopt_long(argc, argv, "s:", options, NULL); if (c == -1) break; switch (c) { case 'h': { showusage(); exit(0); break; } case 's': { // UUID as string, parse it RTUUID buuid; if (!RT_SUCCESS(RTUuidFromStr((PRTUUID)&buuid, optarg))) { printf("Error, invalid UUID format given!\n"); showusage(); exit(-1); } uuid = optarg; break; } case 'f': { if (sscanf(optarg, "%ux%ux%u", &fixedVideoMode.width, &fixedVideoMode.height, &fixedVideoMode.bpp) != 3) { printf("Error, invalid resolution argument!\n"); showusage(); exit(-1); } useFixedVideoMode = 1; break; } case 'l': { listHostModes = 1; break; } case 'c': { scaleGuest = 1; break; } default: break; } } // check if we got a UUID if (!uuid) { printf("Error, no UUID given!\n"); showusage(); exit(-1); } /** * XPCOM setup */ nsresult rc; /* * Note that we scope all nsCOMPtr variables in order to have all XPCOM * objects automatically released before we call NS_ShutdownXPCOM at the * end. This is an XPCOM requirement. */ { nsCOMPtr<nsIServiceManager> serviceManager; rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), nsnull, nsnull); if (NS_FAILED(rc)) { printf("Error: XPCOM could not be initialized! rc=0x%x\n", rc); exit(-1); } // register our component nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(serviceManager); if (!registrar) { printf("Error: could not query nsIComponentRegistrar interface!\n"); exit(-1); } registrar->AutoRegister(nsnull); /* * Make sure the main event queue is created. This event queue is * responsible for dispatching incoming XPCOM IPC messages. The main * thread should run this event queue's loop during lengthy non-XPCOM * operations to ensure messages from the VirtualBox server and other * XPCOM IPC clients are processed. This use case doesn't perform such * operations so it doesn't run the event loop. */ nsCOMPtr<nsIEventQueue> eventQ; rc = NS_GetMainEventQ(getter_AddRefs (eventQ)); if (NS_FAILED(rc)) { printf("Error: could not get main event queue! rc=%08X\n", rc); return -1; } /* * Now XPCOM is ready and we can start to do real work. * IVirtualBox is the root interface of VirtualBox and will be * retrieved from the XPCOM component manager. We use the * XPCOM provided smart pointer nsCOMPtr for all objects because * that's very convenient and removes the need deal with reference * counting and freeing. */ nsCOMPtr<nsIComponentManager> manager; rc = NS_GetComponentManager (getter_AddRefs (manager)); if (NS_FAILED(rc)) { printf("Error: could not get component manager! rc=%08X\n", rc); exit(-1); } nsCOMPtr<IVirtualBox> virtualBox; rc = manager->CreateInstanceByContractID(NS_VIRTUALBOX_CONTRACTID, nsnull, NS_GET_IID(IVirtualBox), getter_AddRefs(virtualBox)); if (NS_FAILED(rc)) { printf("Error, could not instantiate object! rc=0x%x\n", rc); exit(-1); } nsCOMPtr<ISession> session; rc = manager->CreateInstance(CLSID_Session, nsnull, NS_GET_IID(ISession), getter_AddRefs(session)); if (NS_FAILED(rc)) { printf("Error: could not instantiate Session object! rc = %08X\n", rc); exit(-1); } // open session for this VM rc = virtualBox->OpenSession(session, NS_ConvertUTF8toUTF16(uuid).get()); if (NS_FAILED(rc)) { printf("Error: given machine not found!\n"); exit(-1); } nsCOMPtr<IMachine> machine; session->GetMachine(getter_AddRefs(machine)); if (!machine) { printf("Error: given machine not found!\n"); exit(-1); } nsCOMPtr<IConsole> console; session->GetConsole(getter_AddRefs(console)); if (!console) { printf("Error: cannot get console!\n"); exit(-1); } nsCOMPtr<IDisplay> display; console->GetDisplay(getter_AddRefs(display)); if (!display) { printf("Error: could not get display object!\n"); exit(-1); } nsCOMPtr<IKeyboard> keyboard; nsCOMPtr<IMouse> mouse; VBoxDirectFB *frameBuffer = NULL; /** * Init DirectFB */ IDirectFB *dfb = NULL; IDirectFBSurface *surface = NULL; IDirectFBInputDevice *dfbKeyboard = NULL; IDirectFBInputDevice *dfbMouse = NULL; IDirectFBEventBuffer *dfbEventBuffer = NULL; DFBSurfaceDescription dsc; int screen_width, screen_height; DFBCHECK(DirectFBInit(&argc, &argv)); DFBCHECK(DirectFBCreate(&dfb)); DFBCHECK(dfb->SetCooperativeLevel(dfb, DFSCL_FULLSCREEN)); // populate our structure of supported video modes DFBCHECK(dfb->EnumVideoModes(dfb, enumVideoModesHandler, NULL)); if (listHostModes) { printf("*****************************************************\n"); printf("Number of available host video modes: %u\n", numVideoModes); for (uint32_t i = 0; i < numVideoModes; i++) { printf("Mode %u: xres = %u, yres = %u, bpp = %u\n", i, videoModes[i].width, videoModes[i].height, videoModes[i].bpp); } printf("Note: display modes with bpp < have been filtered out\n"); printf("*****************************************************\n"); goto Leave; } if (useFixedVideoMode) { int32_t bestVideoMode = getBestVideoMode(fixedVideoMode.width, fixedVideoMode.height, fixedVideoMode.bpp); // validate the fixed mode if ((bestVideoMode == -1) || ((fixedVideoMode.width != videoModes[bestVideoMode].width) || (fixedVideoMode.height != videoModes[bestVideoMode].height) || (fixedVideoMode.bpp != videoModes[bestVideoMode].bpp))) { printf("Error: the specified fixed video mode is not available!\n"); exit(-1); } } else { initialVideoMode = getBestVideoMode(640, 480, 16); if (initialVideoMode == -1) { printf("Error: initial video mode 640x480x16 is not available!\n"); exit(-1); } } dsc.flags = DSDESC_CAPS; dsc.caps = DSCAPS_PRIMARY; DFBCHECK(dfb->CreateSurface(dfb, &dsc, &surface)); DFBCHECK(surface->Clear(surface, 0, 0, 0, 0)); DFBCHECK(surface->GetSize(surface, &screen_width, &screen_height)); DFBCHECK(dfb->GetInputDevice(dfb, DIDID_KEYBOARD, &dfbKeyboard)); DFBCHECK(dfbKeyboard->CreateEventBuffer(dfbKeyboard, &dfbEventBuffer)); DFBCHECK(dfb->GetInputDevice(dfb, DIDID_MOUSE, &dfbMouse)); DFBCHECK(dfbMouse->AttachEventBuffer(dfbMouse, dfbEventBuffer)); if (useFixedVideoMode) { printf("Information: setting video mode to %ux%ux%u\n", fixedVideoMode.width, fixedVideoMode.height, fixedVideoMode.bpp); DFBCHECK(dfb->SetVideoMode(dfb, fixedVideoMode.width, fixedVideoMode.height, fixedVideoMode.bpp)); } else { printf("Information: starting with default video mode %ux%ux%u\n", videoModes[initialVideoMode].width, videoModes[initialVideoMode].height, videoModes[initialVideoMode].bpp); DFBCHECK(dfb->SetVideoMode(dfb, videoModes[initialVideoMode].width, videoModes[initialVideoMode].height, videoModes[initialVideoMode].bpp)); } // register our framebuffer frameBuffer = new VBoxDirectFB(dfb, surface); display->SetFramebuffer(0, frameBuffer); /** * Start the VM execution thread */ console->PowerUp(NULL); console->GetKeyboard(getter_AddRefs(keyboard)); console->GetMouse(getter_AddRefs(mouse)); /** * Main event loop */ #define MAX_KEYEVENTS 10 PRInt32 keyEvents[MAX_KEYEVENTS]; int numKeyEvents; while (!quit) { DFBInputEvent event; numKeyEvents = 0; DFBCHECK(dfbEventBuffer->WaitForEvent(dfbEventBuffer)); while (dfbEventBuffer->GetEvent(dfbEventBuffer, DFB_EVENT(&event)) == DFB_OK) { int mouseXDelta = 0; int mouseYDelta = 0; int mouseZDelta = 0; switch (event.type) { #define QUEUEEXT() keyEvents[numKeyEvents++] = 0xe0 #define QUEUEKEY(scan) keyEvents[numKeyEvents++] = scan | (event.type == DIET_KEYRELEASE ? 0x80 : 0x00) #define QUEUEKEYRAW(scan) keyEvents[numKeyEvents++] = scan case DIET_KEYPRESS: case DIET_KEYRELEASE: { // @@@AH development hack to get out of it! if ((event.key_id == DIKI_ESCAPE) && (event.modifiers & (DIMM_CONTROL | DIMM_ALT))) quit = 1; if (numKeyEvents < MAX_KEYEVENTS) { //printf("%s: key_code: 0x%x\n", event.type == DIET_KEYPRESS ? "DIET_KEYPRESS" : "DIET_KEYRELEASE", event.key_code); switch ((uint32_t)event.key_id) { case DIKI_CONTROL_R: QUEUEEXT(); QUEUEKEY(0x1d); break; case DIKI_INSERT: QUEUEEXT(); QUEUEKEY(0x52); break; case DIKI_DELETE: QUEUEEXT(); QUEUEKEY(0x53); break; case DIKI_HOME: QUEUEEXT(); QUEUEKEY(0x47); break; case DIKI_END: QUEUEEXT(); QUEUEKEY(0x4f); break; case DIKI_PAGE_UP: QUEUEEXT(); QUEUEKEY(0x49); break; case DIKI_PAGE_DOWN: QUEUEEXT(); QUEUEKEY(0x51); break; case DIKI_LEFT: QUEUEEXT(); QUEUEKEY(0x4b); break; case DIKI_RIGHT: QUEUEEXT(); QUEUEKEY(0x4d); break; case DIKI_UP: QUEUEEXT(); QUEUEKEY(0x48); break; case DIKI_DOWN: QUEUEEXT(); QUEUEKEY(0x50); break; case DIKI_KP_DIV: QUEUEEXT(); QUEUEKEY(0x35); break; case DIKI_KP_ENTER: QUEUEEXT(); QUEUEKEY(0x1c); break; case DIKI_PRINT: // the break code is inverted! if (event.type == DIET_KEYPRESS) { QUEUEEXT(); QUEUEKEY(0x2a); QUEUEEXT(); QUEUEKEY(0x37); } else { QUEUEEXT(); QUEUEKEY(0x37); QUEUEEXT(); QUEUEKEY(0x2a); } break; case DIKI_PAUSE: // This is a super weird key. No break code and a 6 byte // combination. if (event.type == DIET_KEYPRESS) { QUEUEKEY(0xe1); QUEUEKEY(0x1d); QUEUEKEY(0x45); QUEUEKEY(0xe1); QUEUEKEY(0x9d); QUEUEKEY(0xc5); } break; case DIKI_META_L: // the left Windows logo is a bit different if (event.type == DIET_KEYPRESS) { QUEUEEXT(); QUEUEKEYRAW(0x1f); } else { QUEUEEXT(); QUEUEKEYRAW(0xf0); QUEUEKEYRAW(0x1f); } break; case DIKI_META_R: // the right Windows logo is a bit different if (event.type == DIET_KEYPRESS) { QUEUEEXT(); QUEUEKEYRAW(0x27); } else { QUEUEEXT(); QUEUEKEYRAW(0xf0); QUEUEKEYRAW(0x27); } break; case DIKI_SUPER_R: // the popup menu is a bit different if (event.type == DIET_KEYPRESS) { QUEUEEXT(); QUEUEKEYRAW(0x2f); } else { QUEUEEXT(); QUEUEKEYRAW(0xf0); QUEUEKEYRAW(0x2f); } break; default: // check if we got a hardware scancode if (event.key_code != -1) { // take the scancode from DirectFB as is QUEUEKEY(event.key_code); } else { // XXX need extra handling! } } } break; } #undef QUEUEEXT #undef QUEUEKEY #undef QUEUEKEYRAW case DIET_AXISMOTION: { switch (event.axis) { case DIAI_X: mouseXDelta += event.axisrel; break; case DIAI_Y: mouseYDelta += event.axisrel; break; case DIAI_Z: mouseZDelta += event.axisrel; break; default: break; } // fall through } case DIET_BUTTONPRESS: // fall through; case DIET_BUTTONRELEASE: { int buttonState = 0; if (event.buttons & DIBM_LEFT) buttonState |= MouseButtonState::LeftButton; if (event.buttons & DIBM_RIGHT) buttonState |= MouseButtonState::RightButton; if (event.buttons & DIBM_MIDDLE) buttonState |= MouseButtonState::MiddleButton; mouse->PutMouseEvent(mouseXDelta, mouseYDelta, mouseZDelta, buttonState); break; } default: break; } } // did we get any keyboard events? if (numKeyEvents > 0) { uint32_t codesStored; if (numKeyEvents > 1) { keyboard->PutScancodes(numKeyEvents, keyEvents, &codesStored); } else { keyboard->PutScancode(keyEvents[0]); } } } { nsCOMPtr<IProgress> progress; console->PowerDown(getter_AddRefs(progress)); progress->WaitForCompletion(-1); } } Leave: /* * Perform the standard XPCOM shutdown procedure. */ NS_ShutdownXPCOM(nsnull); return 0; }
// The end of a body is marked by a CRLF followed by the boundary. So the // CRLF is part of the boundary and not the body, but any prior CRLFs are // part of the body. This will position the iterator at the beginning of the // boundary (after the CRLF). bool ParseBody(const nsACString& aBoundaryString, nsACString::const_iterator& aStart, nsACString::const_iterator& aEnd) { const char* beginning = aStart.get(); // Find the boundary marking the end of the body. nsACString::const_iterator end(aEnd); if (!FindInReadable(aBoundaryString, aStart, end)) { return false; } // We found a boundary, strip the just prior CRLF, and consider // everything else the body section. if (aStart.get() - beginning < 2) { // Only the first entry can have a boundary right at the beginning. Even // an empty body will have a CRLF before the boundary. So this is // a failure. return false; } // Check that there is a CRLF right before the boundary. aStart.advance(-2); // Skip optional hyphens. if (*aStart == '-' && *(aStart.get()+1) == '-') { if (aStart.get() - beginning < 2) { return false; } aStart.advance(-2); } if (*aStart != nsCRT::CR || *(aStart.get()+1) != nsCRT::LF) { return false; } nsAutoCString body(beginning, aStart.get() - beginning); // Restore iterator to after the \r\n as we promised. // We do not need to handle the extra hyphens case since our boundary // parser in PushOverBoundary() aStart.advance(2); if (!mFormData) { mFormData = new nsFormData(); } NS_ConvertUTF8toUTF16 name(mName); if (mFilename.IsVoid()) { mFormData->Append(name, NS_ConvertUTF8toUTF16(body)); } else { // Unfortunately we've to copy the data first since all our strings are // going to free it. We also need fallible alloc, so we can't just use // ToNewCString(). char* copy = static_cast<char*>(moz_xmalloc(body.Length())); if (!copy) { NS_WARNING("Failed to copy File entry body."); return false; } nsCString::const_iterator bodyIter, bodyEnd; body.BeginReading(bodyIter); body.EndReading(bodyEnd); char *p = copy; while (bodyIter != bodyEnd) { *p++ = *bodyIter++; } p = nullptr; nsRefPtr<Blob> file = File::CreateMemoryFile(mParentObject, reinterpret_cast<void *>(copy), body.Length(), NS_ConvertUTF8toUTF16(mFilename), NS_ConvertUTF8toUTF16(mContentType), /* aLastModifiedDate */ 0); Optional<nsAString> dummy; mFormData->Append(name, *file, dummy); } return true; }
nsresult nsMovemailService::GetNewMail(nsIMsgWindow *aMsgWindow, nsIUrlListener *aUrlListener, nsIMsgFolder *aMsgFolder, nsIMovemailIncomingServer *movemailServer, nsIURI ** aURL) { LOG(("nsMovemailService::GetNewMail")); nsresult rv = NS_OK; nsCOMPtr<nsIMsgIncomingServer> in_server = do_QueryInterface(movemailServer); if (!in_server) return NS_MSG_INVALID_OR_MISSING_SERVER; mMsgWindow = aMsgWindow; // Attempt to locate the mail spool file nsCAutoString spoolPath; rv = LocateSpoolFile(spoolPath); if (NS_FAILED(rv) || spoolPath.IsEmpty()) { Error(MOVEMAIL_SPOOL_FILE_NOT_FOUND, nsnull, 0); return NS_ERROR_FAILURE; } // Create an input stream for the spool file nsCOMPtr<nsILocalFile> spoolFile; rv = NS_NewNativeLocalFile(spoolPath, true, getter_AddRefs(spoolFile)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIInputStream> spoolInputStream; rv = NS_NewLocalFileInputStream(getter_AddRefs(spoolInputStream), spoolFile); if (NS_FAILED(rv)) { const PRUnichar *params[] = { NS_ConvertUTF8toUTF16(spoolPath).get() }; Error(MOVEMAIL_CANT_OPEN_SPOOL_FILE, params, 1); return rv; } // Get a line input interface for the spool file nsCOMPtr<nsILineInputStream> lineInputStream = do_QueryInterface(spoolInputStream, &rv); if (!lineInputStream) return rv; nsCOMPtr<nsIMsgFolder> serverFolder; nsCOMPtr<nsIMsgFolder> inbox; nsCOMPtr<nsIMsgFolder> rootMsgFolder; rv = in_server->GetRootFolder(getter_AddRefs(serverFolder)); NS_ENSURE_SUCCESS(rv, rv); rootMsgFolder = do_QueryInterface(serverFolder, &rv); if (!rootMsgFolder) return rv; rv = rootMsgFolder->GetFolderWithFlags(nsMsgFolderFlags::Inbox, getter_AddRefs(inbox)); NS_ENSURE_TRUE(inbox, NS_ERROR_FAILURE); nsCOMPtr <nsIOutputStream> outputStream; nsCOMPtr<nsIMsgPluggableStore> msgStore; rv = in_server->GetMsgStore(getter_AddRefs(msgStore)); NS_ENSURE_SUCCESS(rv, rv); bool reusable; nsCOMPtr<nsIMsgDBHdr> newHdr; msgStore->GetNewMsgOutputStream(inbox, getter_AddRefs(newHdr), &reusable, getter_AddRefs(outputStream)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr <nsIInputStream> inputStream = do_QueryInterface(outputStream); // create a new mail parser nsRefPtr<nsParseNewMailState> newMailParser = new nsParseNewMailState; NS_ENSURE_TRUE(newMailParser, NS_ERROR_OUT_OF_MEMORY); rv = newMailParser->Init(serverFolder, inbox, nsnull, newHdr, outputStream); NS_ENSURE_SUCCESS(rv, rv); in_server->SetServerBusy(true); // Try and obtain the lock for the spool file bool usingLockFile; if (!ObtainSpoolLock(spoolPath.get(), 5, &usingLockFile)) { nsAutoString lockFile = NS_ConvertUTF8toUTF16(spoolPath); lockFile.AppendLiteral(".lock"); const PRUnichar *params[] = { lockFile.get() }; Error(MOVEMAIL_CANT_CREATE_LOCK, params, 1); return NS_ERROR_FAILURE; } // MIDDLE of the FUN : consume the mailbox data. bool isMore = true; nsCAutoString buffer; PRUint32 bytesWritten; while (isMore && NS_SUCCEEDED(lineInputStream->ReadLine(buffer, &isMore))) { // If first string is empty and we're now at EOF then abort parsing. if (buffer.IsEmpty() && !isMore) { LOG(("Empty spool file")); break; } buffer += MSG_LINEBREAK; newMailParser->HandleLine(buffer.BeginWriting(), buffer.Length()); outputStream->Write(buffer.get(), buffer.Length(), &bytesWritten); // 'From' lines delimit messages if (isMore && !strncmp(buffer.get(), "From ", 5)) { buffer.AssignLiteral("X-Mozilla-Status: 8000" MSG_LINEBREAK); newMailParser->HandleLine(buffer.BeginWriting(), buffer.Length()); outputStream->Write(buffer.get(), buffer.Length(), &bytesWritten); buffer.AssignLiteral("X-Mozilla-Status2: 00000000" MSG_LINEBREAK); newMailParser->HandleLine(buffer.BeginWriting(), buffer.Length()); outputStream->Write(buffer.get(), buffer.Length(), &bytesWritten); } } outputStream->Flush(); newMailParser->OnStopRequest(nsnull, nsnull, NS_OK); msgStore->FinishNewMessage(outputStream, newHdr); outputStream->Close(); // Truncate the spool file rv = spoolFile->SetFileSize(0); if (NS_FAILED(rv)) { const PRUnichar *params[] = { NS_ConvertUTF8toUTF16(spoolPath).get() }; Error(MOVEMAIL_CANT_TRUNCATE_SPOOL_FILE, params, 1); } if (!YieldSpoolLock(spoolPath.get(), usingLockFile)) { nsAutoString spoolLock = NS_ConvertUTF8toUTF16(spoolPath); spoolLock.AppendLiteral(".lock"); const PRUnichar *params[] = { spoolLock.get() }; Error(MOVEMAIL_CANT_DELETE_LOCK, params, 1); } in_server->SetServerBusy(false); LOG(("GetNewMail returning rv=%d", rv)); return rv; }
static void ConvertString(const std::string& aFrom, nsString& aOutTo) { aOutTo = NS_ConvertUTF8toUTF16(aFrom.c_str(), aFrom.size()); }
int MimeHeaders_write_all_headers (MimeHeaders *hdrs, MimeDisplayOptions *opt, PRBool attachment) { int status = 0; int i; PRBool wrote_any_p = PR_FALSE; NS_ASSERTION(hdrs, "1.1 <*****@*****.**> 19 Mar 1999 12:00"); if (!hdrs) return -1; /* One shouldn't be trying to read headers when one hasn't finished parsing them yet... but this can happen if the message ended prematurely, and has no body at all (as opposed to a null body, which is more normal.) So, if we try to read from the headers, let's assume that the headers are now finished. If they aren't in fact finished, then a later attempt to write to them will assert. */ if (!hdrs->done_p) { hdrs->done_p = PR_TRUE; status = MimeHeaders_build_heads_list(hdrs); if (status < 0) return 0; } char *charset = nsnull; if (opt->format_out == nsMimeOutput::nsMimeMessageSaveAs) { if (opt->override_charset) charset = PL_strdup(opt->default_charset); else { char *contentType = MimeHeaders_get(hdrs, HEADER_CONTENT_TYPE, PR_FALSE, PR_FALSE); if (contentType) charset = MimeHeaders_get_parameter(contentType, HEADER_PARM_CHARSET, nsnull, nsnull); PR_FREEIF(contentType); } } for (i = 0; i < hdrs->heads_size; i++) { char *head = hdrs->heads[i]; char *end = (i == hdrs->heads_size-1 ? hdrs->all_headers + hdrs->all_headers_fp : hdrs->heads[i+1]); char *colon, *ocolon; char *contents = end; /* Hack for BSD Mailbox delimiter. */ if (i == 0 && head[0] == 'F' && !strncmp(head, "From ", 5)) { /* For now, we don't really want this header to be output so we are going to just continue */ continue; /* colon = head + 4; contents = colon + 1; */ } else { /* Find the colon. */ for (colon = head; colon < end && *colon != ':'; colon++) ; /* Back up over whitespace before the colon. */ ocolon = colon; for (; colon > head && IS_SPACE(colon[-1]); colon--) ; contents = ocolon + 1; } /* Skip over whitespace after colon. */ while (contents < end && IS_SPACE(*contents)) contents++; /* Take off trailing whitespace... */ while (end > contents && IS_SPACE(end[-1])) end--; nsCAutoString name(Substring(head, colon)); nsCAutoString hdr_value; if ( (end - contents) > 0 ) { hdr_value = Substring(contents, end); } // MW Fixme: more? PRBool convert_charset_only = #ifdef MOZILLA_INTERNAL_API name.LowerCaseEqualsLiteral("to") || name.LowerCaseEqualsLiteral("from") || name.LowerCaseEqualsLiteral("cc") || name.LowerCaseEqualsLiteral("bcc") || name.LowerCaseEqualsLiteral("reply-to") || name.LowerCaseEqualsLiteral("sender"); #else name.Equals("to", CaseInsensitiveCompare) || name.Equals("from", CaseInsensitiveCompare) || name.Equals("cc", CaseInsensitiveCompare) || name.Equals("bcc", CaseInsensitiveCompare) || name.Equals("reply-to", CaseInsensitiveCompare) || name.Equals("sender", CaseInsensitiveCompare); #endif MimeHeaders_convert_header_value(opt, hdr_value, convert_charset_only); // if we're saving as html, we need to convert headers from utf8 to message charset, if any if (opt->format_out == nsMimeOutput::nsMimeMessageSaveAs && charset) { nsCAutoString convertedStr; if (NS_SUCCEEDED(ConvertFromUnicode(charset, NS_ConvertUTF8toUTF16(hdr_value), convertedStr))) { hdr_value = convertedStr; } } if (attachment) status = mimeEmitterAddAttachmentField(opt, name.get(), hdr_value.get()); else status = mimeEmitterAddHeaderField(opt, name.get(), hdr_value.get()); if (status < 0) return status; if (!wrote_any_p) wrote_any_p = (status > 0); } mimeEmitterAddAllHeaders(opt, hdrs->all_headers, hdrs->all_headers_fp); PR_FREEIF(charset); return 1; }
nsresult nsAddbookProtocolHandler::BuildDirectoryXML(nsIAbDirectory *aDirectory, nsString &aOutput) { NS_ENSURE_ARG_POINTER(aDirectory); nsresult rv; nsCOMPtr<nsISimpleEnumerator> cardsEnumerator; nsCOMPtr<nsIAbCard> card; aOutput.AppendLiteral("<?xml version=\"1.0\"?>\n" "<?xml-stylesheet type=\"text/css\" href=\"chrome://messagebody/content/addressbook/print.css\"?>\n" "<directory>\n"); // Get Address Book string and set it as title of XML document nsCOMPtr<nsIStringBundle> bundle; nsCOMPtr<nsIStringBundleService> stringBundleService = mozilla::services::GetStringBundleService(); if (stringBundleService) { rv = stringBundleService->CreateBundle("chrome://messenger/locale/addressbook/addressBook.properties", getter_AddRefs(bundle)); if (NS_SUCCEEDED(rv)) { nsString addrBook; rv = bundle->GetStringFromName(NS_LITERAL_STRING("addressBook").get(), getter_Copies(addrBook)); if (NS_SUCCEEDED(rv)) { aOutput.AppendLiteral("<title xmlns=\"http://www.w3.org/1999/xhtml\">"); aOutput.Append(addrBook); aOutput.AppendLiteral("</title>\n"); } } } // create a view and init it with the generated name sort order. Then, iterate // over the view, getting the card for each row, and printing them. nsString sortColumn; nsCOMPtr <nsIAbView> view = do_CreateInstance("@mozilla.org/addressbook/abview;1", &rv); view->SetView(aDirectory, nullptr, NS_LITERAL_STRING("GeneratedName"), NS_LITERAL_STRING("ascending"), sortColumn); int32_t numRows; nsCOMPtr <nsITreeView> treeView = do_QueryInterface(view, &rv); NS_ENSURE_SUCCESS(rv, rv); treeView->GetRowCount(&numRows); for (int32_t row = 0; row < numRows; row++) { nsCOMPtr <nsIAbCard> card; view->GetCardFromRow(row, getter_AddRefs(card)); nsCString xmlSubstr; rv = card->TranslateTo(NS_LITERAL_CSTRING("xml"), xmlSubstr); NS_ENSURE_SUCCESS(rv,rv); aOutput.AppendLiteral("<separator/>"); aOutput.Append(NS_ConvertUTF8toUTF16(xmlSubstr)); aOutput.AppendLiteral("<separator/>"); } aOutput.AppendLiteral("</directory>\n"); return NS_OK; }
/* void initPrintSettingsFromPrinter (in wstring aPrinterName, in nsIPrintSettings aPrintSettings); */ NS_IMETHODIMP nsPrinterEnumeratorGTK::InitPrintSettingsFromPrinter(const PRUnichar *aPrinterName, nsIPrintSettings *aPrintSettings) { DO_PR_DEBUG_LOG(("nsPrinterEnumeratorGTK::InitPrintSettingsFromPrinter()")); nsresult rv; NS_ENSURE_ARG_POINTER(aPrinterName); NS_ENSURE_ARG_POINTER(aPrintSettings); NS_ENSURE_TRUE(*aPrinterName, NS_ERROR_FAILURE); NS_ENSURE_TRUE(aPrintSettings, NS_ERROR_FAILURE); nsCOMPtr<nsIPrefBranch> pPrefs = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; nsXPIDLCString fullPrinterName, /* Full name of printer incl. driver-specific prefix */ printerName; /* "Stripped" name of printer */ fullPrinterName.Assign(NS_ConvertUTF16toUTF8(aPrinterName)); printerName.Assign(NS_ConvertUTF16toUTF8(aPrinterName)); DO_PR_DEBUG_LOG(("printerName='%s'\n", printerName.get())); PrintMethod type = pmInvalid; rv = nsDeviceContextSpecGTK::GetPrintMethod(printerName, type); if (NS_FAILED(rv)) return rv; #ifdef USE_POSTSCRIPT /* "Demangle" postscript printer name */ if (type == pmPostScript) { /* Strip the printing method name from the printer, * e.g. turn "PostScript/foobar" to "foobar" */ PRInt32 slash = printerName.FindChar('/'); if (kNotFound != slash) printerName.Cut(0, slash + 1); } #endif /* USE_POSTSCRIPT */ #ifdef SET_PRINTER_FEATURES_VIA_PREFS /* Defaults to FALSE */ pPrefs->SetBoolPref(nsPrintfCString(256, PRINTERFEATURES_PREF ".%s.has_special_printerfeatures", fullPrinterName.get()).get(), PR_FALSE); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ /* Set filename */ nsXPIDLCString filename; if (NS_FAILED(CopyPrinterCharPref(pPrefs, nsnull, printerName, "filename", filename))) { const char *path; if (!(path = PR_GetEnv("PWD"))) path = PR_GetEnv("HOME"); if (path) filename = nsPrintfCString(PATH_MAX, "%s/mozilla.ps", path); else filename.AssignLiteral("mozilla.ps"); } DO_PR_DEBUG_LOG(("Setting default filename to '%s'\n", filename.get())); aPrintSettings->SetToFileName(NS_ConvertUTF8toUTF16(filename).get()); aPrintSettings->SetIsInitializedFromPrinter(PR_TRUE); #ifdef USE_POSTSCRIPT if (type == pmPostScript) { DO_PR_DEBUG_LOG(("InitPrintSettingsFromPrinter() for PostScript printer\n")); #ifdef SET_PRINTER_FEATURES_VIA_PREFS nsPrinterFeatures printerFeatures(fullPrinterName); printerFeatures.SetSupportsPaperSizeChange(PR_TRUE); printerFeatures.SetSupportsOrientationChange(PR_TRUE); printerFeatures.SetSupportsPlexChange(PR_FALSE); printerFeatures.SetSupportsResolutionNameChange(PR_FALSE); printerFeatures.SetSupportsColorspaceChange(PR_FALSE); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetCanChangeOrientation(PR_TRUE); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ nsXPIDLCString orientation; if (NS_SUCCEEDED(CopyPrinterCharPref(pPrefs, "postscript", printerName, "orientation", orientation))) { if (orientation.LowerCaseEqualsLiteral("portrait")) { DO_PR_DEBUG_LOG(("setting default orientation to 'portrait'\n")); aPrintSettings->SetOrientation(nsIPrintSettings::kPortraitOrientation); } else if (orientation.LowerCaseEqualsLiteral("landscape")) { DO_PR_DEBUG_LOG(("setting default orientation to 'landscape'\n")); aPrintSettings->SetOrientation(nsIPrintSettings::kLandscapeOrientation); } else { DO_PR_DEBUG_LOG(("Unknown default orientation '%s'\n", orientation.get())); } } #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetOrientationRecord(0, "portrait"); printerFeatures.SetOrientationRecord(1, "landscape"); printerFeatures.SetNumOrientationRecords(2); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ /* PostScript module does not support changing the plex mode... */ #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetCanChangePlex(PR_FALSE); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ DO_PR_DEBUG_LOG(("setting default plex to '%s'\n", "default")); aPrintSettings->SetPlexName(NS_LITERAL_STRING("default").get()); #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetPlexRecord(0, "default"); printerFeatures.SetNumPlexRecords(1); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ /* PostScript module does not support changing the resolution mode... */ #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetCanChangeResolutionName(PR_FALSE); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ DO_PR_DEBUG_LOG(("setting default resolution to '%s'\n", "default")); aPrintSettings->SetResolutionName(NS_LITERAL_STRING("default").get()); #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetResolutionNameRecord(0, "default"); printerFeatures.SetNumResolutionNameRecords(1); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ /* PostScript module does not support changing the colorspace... */ #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetCanChangeColorspace(PR_FALSE); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ DO_PR_DEBUG_LOG(("setting default colorspace to '%s'\n", "default")); aPrintSettings->SetColorspace(NS_LITERAL_STRING("default").get()); #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetColorspaceRecord(0, "default"); printerFeatures.SetNumColorspaceRecords(1); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetCanChangePaperSize(PR_TRUE); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ nsXPIDLCString papername; if (NS_SUCCEEDED(CopyPrinterCharPref(pPrefs, "postscript", printerName, "paper_size", papername))) { nsPaperSizePS paper; if (paper.Find(papername)) { DO_PR_DEBUG_LOG(("setting default paper size to '%s' (%g mm/%g mm)\n", paper.Name(), paper.Width_mm(), paper.Height_mm())); aPrintSettings->SetPaperSizeUnit(nsIPrintSettings::kPaperSizeMillimeters); aPrintSettings->SetPaperWidth(paper.Width_mm()); aPrintSettings->SetPaperHeight(paper.Height_mm()); aPrintSettings->SetPaperName(NS_ConvertASCIItoUTF16(paper.Name()).get()); } else { DO_PR_DEBUG_LOG(("Unknown paper size '%s' given.\n", papername.get())); } #ifdef SET_PRINTER_FEATURES_VIA_PREFS paper.First(); int count = 0; while (!paper.AtEnd()) { printerFeatures.SetPaperRecord(count++, paper.Name(), (int)paper.Width_mm(), (int)paper.Height_mm(), !paper.IsMetric()); paper.Next(); } printerFeatures.SetNumPaperSizeRecords(count); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ } PRBool hasSpoolerCmd = (nsPSPrinterList::kTypePS == nsPSPrinterList::GetPrinterType(fullPrinterName)); #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetSupportsSpoolerCommandChange(hasSpoolerCmd); printerFeatures.SetCanChangeSpoolerCommand(hasSpoolerCmd); /* Postscript module does not pass the job title to lpr */ printerFeatures.SetSupportsJobTitleChange(PR_FALSE); printerFeatures.SetCanChangeJobTitle(PR_FALSE); /* Postscript module has no control over builtin fonts yet */ printerFeatures.SetSupportsDownloadFontsChange(PR_FALSE); printerFeatures.SetCanChangeDownloadFonts(PR_FALSE); /* Postscript module does not support multiple colorspaces * so it has to use the old way */ printerFeatures.SetSupportsPrintInColorChange(PR_TRUE); printerFeatures.SetCanChangePrintInColor(PR_TRUE); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ if (hasSpoolerCmd) { nsXPIDLCString command; if (NS_SUCCEEDED(CopyPrinterCharPref(pPrefs, "postscript", printerName, "print_command", command))) { DO_PR_DEBUG_LOG(("setting default print command to '%s'\n", command.get())); aPrintSettings->SetPrintCommand(NS_ConvertUTF8toUTF16(command).get()); } } #ifdef SET_PRINTER_FEATURES_VIA_PREFS printerFeatures.SetCanChangeNumCopies(PR_TRUE); #endif /* SET_PRINTER_FEATURES_VIA_PREFS */ return NS_OK; } #endif /* USE_POSTSCRIPT */ return NS_ERROR_UNEXPECTED; }
nsresult PluginDocument::CreateSyntheticPluginDocument() { NS_ASSERTION(!GetShell() || !GetShell()->DidInitialize(), "Creating synthetic plugin document content too late"); // make our generic document nsresult rv = MediaDocument::CreateSyntheticDocument(); NS_ENSURE_SUCCESS(rv, rv); // then attach our plugin Element* body = GetBodyElement(); if (!body) { NS_WARNING("no body on plugin document!"); return NS_ERROR_FAILURE; } // remove margins from body NS_NAMED_LITERAL_STRING(zero, "0"); body->SetAttr(kNameSpaceID_None, nsGkAtoms::marginwidth, zero, false); body->SetAttr(kNameSpaceID_None, nsGkAtoms::marginheight, zero, false); // make plugin content nsCOMPtr<nsINodeInfo> nodeInfo; nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::embed, nullptr, kNameSpaceID_XHTML, nsIDOMNode::ELEMENT_NODE); NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY); rv = NS_NewHTMLElement(getter_AddRefs(mPluginContent), nodeInfo.forget(), NOT_FROM_PARSER); NS_ENSURE_SUCCESS(rv, rv); // make it a named element mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name, NS_LITERAL_STRING("plugin"), false); // fill viewport and auto-resize NS_NAMED_LITERAL_STRING(percent100, "100%"); mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::width, percent100, false); mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::height, percent100, false); // set URL nsAutoCString src; mDocumentURI->GetSpec(src); mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::src, NS_ConvertUTF8toUTF16(src), false); // set mime type mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::type, NS_ConvertUTF8toUTF16(mMimeType), false); // This will not start the load because nsObjectLoadingContent checks whether // its document is an nsIPluginDocument body->AppendChildTo(mPluginContent, false); return NS_OK; }
void SourceBuffer::DispatchSimpleEvent(const char* aName) { MSE_DEBUG("%p Dispatching event %s to SourceBuffer", this, aName); DispatchTrustedEvent(NS_ConvertUTF8toUTF16(aName)); }
/** * The entry point for this file. A call from Navigator::mozGetUserMedia * will end up here. MediaManager is a singleton that is responsible * for handling all incoming getUserMedia calls from every window. */ nsresult MediaManager::GetUserMedia(bool aPrivileged, nsPIDOMWindow* aWindow, nsIMediaStreamOptions* aParams, nsIDOMGetUserMediaSuccessCallback* aOnSuccess, nsIDOMGetUserMediaErrorCallback* aOnError) { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); NS_ENSURE_TRUE(aParams, NS_ERROR_NULL_POINTER); NS_ENSURE_TRUE(aWindow, NS_ERROR_NULL_POINTER); NS_ENSURE_TRUE(aOnError, NS_ERROR_NULL_POINTER); NS_ENSURE_TRUE(aOnSuccess, NS_ERROR_NULL_POINTER); nsCOMPtr<nsIDOMGetUserMediaSuccessCallback> onSuccess(aOnSuccess); nsCOMPtr<nsIDOMGetUserMediaErrorCallback> onError(aOnError); /* Get options */ nsresult rv; bool fake, audio, video, picture; rv = aParams->GetFake(&fake); NS_ENSURE_SUCCESS(rv, rv); rv = aParams->GetPicture(&picture); NS_ENSURE_SUCCESS(rv, rv); rv = aParams->GetAudio(&audio); NS_ENSURE_SUCCESS(rv, rv); rv = aParams->GetVideo(&video); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIMediaDevice> audiodevice; rv = aParams->GetAudioDevice(getter_AddRefs(audiodevice)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIMediaDevice> videodevice; rv = aParams->GetVideoDevice(getter_AddRefs(videodevice)); NS_ENSURE_SUCCESS(rv, rv); // If a device was provided, make sure it support the type of stream requested. if (audiodevice) { nsString type; audiodevice->GetType(type); if (audio && !type.EqualsLiteral("audio")) { return NS_ERROR_FAILURE; } } if (videodevice) { nsString type; videodevice->GetType(type); if ((picture || video) && !type.EqualsLiteral("video")) { return NS_ERROR_FAILURE; } } // We only support "front" or "back". TBD: Send to GetUserMediaRunnable. nsString cameraType; rv = aParams->GetCamera(cameraType); NS_ENSURE_SUCCESS(rv, rv); /** * If we were asked to get a picture, before getting a snapshot, we check if * the calling page is allowed to open a popup. We do this because * {picture:true} will open a new "window" to let the user preview or select * an image, on Android. The desktop UI for {picture:true} is TBD, at which * may point we can decide whether to extend this test there as well. */ #if !defined(MOZ_WEBRTC) if (picture && !aPrivileged) { if (aWindow->GetPopupControlState() > openControlled) { nsCOMPtr<nsIPopupWindowManager> pm = do_GetService(NS_POPUPWINDOWMANAGER_CONTRACTID); if (!pm) { return NS_OK; } uint32_t permission; nsCOMPtr<nsIDocument> doc = aWindow->GetExtantDoc(); pm->TestPermission(doc->NodePrincipal(), &permission); if ((permission == nsIPopupWindowManager::DENY_POPUP)) { nsCOMPtr<nsIDOMDocument> domDoc = aWindow->GetExtantDocument(); nsGlobalWindow::FirePopupBlockedEvent( domDoc, aWindow, nullptr, EmptyString(), EmptyString() ); return NS_OK; } } } #endif static bool created = false; if (!created) { // Force MediaManager to startup before we try to access it from other threads // Hack: should init singleton earlier unless it's expensive (mem or CPU) (void) MediaManager::Get(); } // Store the WindowID in a hash table and mark as active. The entry is removed // when this window is closed or navigated away from. uint64_t windowID = aWindow->WindowID(); nsRefPtr<GetUserMediaRunnable> gUMRunnable; // This is safe since we're on main-thread, and the windowlist can only // be invalidated from the main-thread (see OnNavigation) StreamListeners* listeners = GetActiveWindows()->Get(windowID); if (!listeners) { listeners = new StreamListeners; GetActiveWindows()->Put(windowID, listeners); } // Ensure there's a thread for gum to proxy to off main thread nsIThread *mediaThread = MediaManager::GetThread(); // Create a disabled listener to act as a placeholder GetUserMediaCallbackMediaStreamListener* listener = new GetUserMediaCallbackMediaStreamListener(mediaThread, windowID); // No need for locking because we always do this in the main thread. listeners->AppendElement(listener); // Developer preference for turning off permission check. if (Preferences::GetBool("media.navigator.permission.disabled", false)) { aPrivileged = true; } /** * Pass runnables along to GetUserMediaRunnable so it can add the * MediaStreamListener to the runnable list. The last argument can * optionally be a MediaDevice object, which should provided if one was * selected by the user via the UI, or was provided by privileged code * via the device: attribute via nsIMediaStreamOptions. * * If a fake stream was requested, we force the use of the default backend. */ if (fake) { // Fake stream from default backend. gUMRunnable = new GetUserMediaRunnable( audio, video, onSuccess.forget(), onError.forget(), windowID, listener, new MediaEngineDefault() ); } else if (audiodevice || videodevice) { // Stream from provided device. gUMRunnable = new GetUserMediaRunnable( audio, video, picture, onSuccess.forget(), onError.forget(), windowID, listener, static_cast<MediaDevice*>(audiodevice.get()), static_cast<MediaDevice*>(videodevice.get()) ); } else { // Stream from default device from WebRTC backend. gUMRunnable = new GetUserMediaRunnable( audio, video, picture, onSuccess.forget(), onError.forget(), windowID, listener ); } #ifdef ANDROID if (picture) { // ShowFilePickerForMimeType() must run on the Main Thread! (on Android) NS_DispatchToMainThread(gUMRunnable); } // XXX No support for Audio or Video in Android yet #else // XXX No full support for picture in Desktop yet (needs proper UI) if (aPrivileged || fake) { mMediaThread->Dispatch(gUMRunnable, NS_DISPATCH_NORMAL); } else { // Ask for user permission, and dispatch runnable (or not) when a response // is received via an observer notification. Each call is paired with its // runnable by a GUID. nsresult rv; nsCOMPtr<nsIUUIDGenerator> uuidgen = do_GetService("@mozilla.org/uuid-generator;1", &rv); NS_ENSURE_SUCCESS(rv, rv); // Generate a call ID. nsID id; rv = uuidgen->GenerateUUIDInPlace(&id); NS_ENSURE_SUCCESS(rv, rv); char buffer[NSID_LENGTH]; id.ToProvidedString(buffer); NS_ConvertUTF8toUTF16 callID(buffer); // Store the current callback. mActiveCallbacks.Put(callID, gUMRunnable); // Construct JSON structure with both the windowID and the callID. nsAutoString data; data.Append(NS_LITERAL_STRING("{\"windowID\":")); // Convert window ID to string. char windowBuffer[32]; PR_snprintf(windowBuffer, sizeof(windowBuffer), "%llu", aWindow->GetOuterWindow()->WindowID()); data.Append(NS_ConvertUTF8toUTF16(windowBuffer)); data.Append(NS_LITERAL_STRING(", \"callID\":\"")); data.Append(callID); data.Append(NS_LITERAL_STRING("\"}")); nsCOMPtr<nsIObserverService> obs = services::GetObserverService(); obs->NotifyObservers(aParams, "getUserMedia:request", data.get()); } #endif return NS_OK; }
nsresult nsOperaProfileMigrator::CopySmartKeywords(nsINavBookmarksService* aBMS, nsIStringBundle* aBundle, PRInt64 aParentFolder) { nsresult rv; nsCOMPtr<nsIFile> smartKeywords; mOperaProfile->Clone(getter_AddRefs(smartKeywords)); smartKeywords->Append(NS_LITERAL_STRING("search.ini")); nsCOMPtr<nsILocalFile> lf(do_QueryInterface(smartKeywords)); nsINIParser parser; if (!lf || NS_FAILED(parser.Init(lf))) return NS_OK; nsString sourceNameOpera; rv = aBundle->GetStringFromName(NS_LITERAL_STRING("sourceNameOpera").get(), getter_Copies(sourceNameOpera)); NS_ENSURE_SUCCESS(rv, rv); const PRUnichar* sourceNameStrings[] = { sourceNameOpera.get() }; nsString importedSearchUrlsTitle; rv = aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchURLsFolder").get(), sourceNameStrings, 1, getter_Copies(importedSearchUrlsTitle)); NS_ENSURE_SUCCESS(rv, rv); PRInt64 keywordsFolder; rv = aBMS->CreateFolder(aParentFolder, NS_ConvertUTF16toUTF8(importedSearchUrlsTitle), nsINavBookmarksService::DEFAULT_INDEX, &keywordsFolder); NS_ENSURE_SUCCESS(rv, rv); PRInt32 sectionIndex = 1; nsCAutoString name, url, keyword; do { nsCAutoString section("Search Engine "); section.AppendInt(sectionIndex++); rv = parser.GetString(section.get(), "Name", name); if (NS_FAILED(rv)) { // No more smart keywords found, stop parsing the file. break; } if (name.IsEmpty()) continue; rv = parser.GetString(section.get(), "URL", url); if (NS_FAILED(rv) || url.IsEmpty()) continue; rv = parser.GetString(section.get(), "Key", keyword); if (NS_FAILED(rv) || keyword.IsEmpty()) continue; PRInt32 post; rv = GetInteger(parser, section.get(), "Is post", &post); if (NS_SUCCEEDED(rv) && post) continue; PRUint32 length = name.Length(); PRInt32 index = 0; do { index = name.FindChar('&', index); if ((PRUint32)index >= length - 2) break; // Assume "&&" is an escaped ampersand in the search query title. if (name.CharAt(index + 1) == '&') { name.Cut(index, 1); index += 2; continue; } name.Cut(index, 1); } while ((PRUint32)index < length); nsCOMPtr<nsIURI> uri; if (NS_FAILED(NS_NewURI(getter_AddRefs(uri), url.get())) || !uri) continue; nsCAutoString hostCStr; uri->GetHost(hostCStr); NS_ConvertASCIItoUTF16 host(hostCStr); const PRUnichar* descStrings[] = { NS_ConvertUTF8toUTF16(keyword).get(), host.get() }; nsString keywordDesc; rv = aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchUrlDesc").get(), descStrings, 2, getter_Copies(keywordDesc)); NS_ENSURE_SUCCESS(rv, rv); PRInt64 newId; rv = aBMS->InsertBookmark(keywordsFolder, uri, nsINavBookmarksService::DEFAULT_INDEX, name, &newId); NS_ENSURE_SUCCESS(rv, rv); rv = aBMS->SetKeywordForBookmark(newId, NS_ConvertUTF8toUTF16(keyword)); NS_ENSURE_SUCCESS(rv, rv); // TODO Bug 397771: set bookmark description to keywordDesc. } while (1); return rv; }
NS_IMETHODIMP nsXMLDocument::Load(const nsAString& aUrl, bool *aReturn) { bool hasHadScriptObject = true; nsIScriptGlobalObject* scriptObject = GetScriptHandlingObject(hasHadScriptObject); NS_ENSURE_STATE(scriptObject || !hasHadScriptObject); ReportUseOfDeprecatedMethod(this, "UseOfDOM3LoadMethodWarning"); NS_ENSURE_ARG_POINTER(aReturn); *aReturn = false; nsCOMPtr<nsIDocument> callingDoc = do_QueryInterface(nsContentUtils::GetDocumentFromContext()); nsIURI *baseURI = mDocumentURI; nsAutoCString charset; if (callingDoc) { baseURI = callingDoc->GetDocBaseURI(); charset = callingDoc->GetDocumentCharacterSet(); } // Create a new URI nsCOMPtr<nsIURI> uri; nsresult rv = NS_NewURI(getter_AddRefs(uri), aUrl, charset.get(), baseURI); if (NS_FAILED(rv)) { return rv; } // Check to see whether the current document is allowed to load this URI. // It's important to use the current document's principal for this check so // that we don't end up in a case where code with elevated privileges is // calling us and changing the principal of this document. // Enforce same-origin even for chrome loaders to avoid someone accidentally // using a document that content has a reference to and turn that into a // chrome document. nsCOMPtr<nsIPrincipal> principal = NodePrincipal(); if (!nsContentUtils::IsSystemPrincipal(principal)) { rv = principal->CheckMayLoad(uri, false, false); NS_ENSURE_SUCCESS(rv, rv); int16_t shouldLoad = nsIContentPolicy::ACCEPT; rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_XMLHTTPREQUEST, uri, principal, callingDoc ? callingDoc.get() : static_cast<nsIDocument*>(this), NS_LITERAL_CSTRING("application/xml"), nullptr, &shouldLoad, nsContentUtils::GetContentPolicy(), nsContentUtils::GetSecurityManager()); NS_ENSURE_SUCCESS(rv, rv); if (NS_CP_REJECTED(shouldLoad)) { return NS_ERROR_CONTENT_BLOCKED; } } else { // We're called from chrome, check to make sure the URI we're // about to load is also chrome. bool isChrome = false; if (NS_FAILED(uri->SchemeIs("chrome", &isChrome)) || !isChrome) { nsAutoCString spec; if (mDocumentURI) mDocumentURI->GetSpec(spec); nsAutoString error; error.AssignLiteral("Cross site loading using document.load is no " "longer supported. Use XMLHttpRequest instead."); nsCOMPtr<nsIScriptError> errorObject = do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = errorObject->InitWithWindowID(error, NS_ConvertUTF8toUTF16(spec), EmptyString(), 0, 0, nsIScriptError::warningFlag, "DOM", callingDoc ? callingDoc->InnerWindowID() : this->InnerWindowID()); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIConsoleService> consoleService = do_GetService(NS_CONSOLESERVICE_CONTRACTID); if (consoleService) { consoleService->LogMessage(errorObject); } return NS_ERROR_DOM_SECURITY_ERR; } } // Partial Reset, need to restore principal for security reasons and // event listener manager so that load listeners etc. will // remain. This should be done before the security check is done to // ensure that the document is reset even if the new document can't // be loaded. Note that we need to hold a strong ref to |principal| // here, because ResetToURI will null out our node principal before // setting the new one. nsRefPtr<nsEventListenerManager> elm(mListenerManager); mListenerManager = nullptr; // When we are called from JS we can find the load group for the page, // and add ourselves to it. This way any pending requests // will be automatically aborted if the user leaves the page. nsCOMPtr<nsILoadGroup> loadGroup; if (callingDoc) { loadGroup = callingDoc->GetDocumentLoadGroup(); } ResetToURI(uri, loadGroup, principal); mListenerManager = elm; // Create a channel nsCOMPtr<nsIInterfaceRequestor> req = nsContentUtils::GetSameOriginChecker(); NS_ENSURE_TRUE(req, NS_ERROR_OUT_OF_MEMORY); nsCOMPtr<nsIChannel> channel; // nsIRequest::LOAD_BACKGROUND prevents throbber from becoming active, // which in turn keeps STOP button from becoming active rv = NS_NewChannel(getter_AddRefs(channel), uri, nullptr, loadGroup, req, nsIRequest::LOAD_BACKGROUND); if (NS_FAILED(rv)) { return rv; } // StartDocumentLoad asserts that readyState is uninitialized, so // uninitialize it. SetReadyStateInternal make this transition invisible to // Web content. But before doing that, assert that the current readyState // is complete as it should be after the call to ResetToURI() above. MOZ_ASSERT(GetReadyStateEnum() == nsIDocument::READYSTATE_COMPLETE, "Bad readyState"); SetReadyStateInternal(nsIDocument::READYSTATE_UNINITIALIZED); // Prepare for loading the XML document "into oneself" nsCOMPtr<nsIStreamListener> listener; if (NS_FAILED(rv = StartDocumentLoad(kLoadAsData, channel, loadGroup, nullptr, getter_AddRefs(listener), false))) { NS_ERROR("nsXMLDocument::Load: Failed to start the document load."); return rv; } // After this point, if we error out of this method we should clear // mChannelIsPending. // Start an asynchronous read of the XML document rv = channel->AsyncOpen(listener, nullptr); if (NS_FAILED(rv)) { mChannelIsPending = false; return rv; } if (!mAsync) { nsCOMPtr<nsIThread> thread = do_GetCurrentThread(); nsAutoSyncOperation sync(this); mLoopingForSyncLoad = true; while (mLoopingForSyncLoad) { if (!NS_ProcessNextEvent(thread)) break; } // We set return to true unless there was a parsing error nsCOMPtr<nsIDOMNode> node = do_QueryInterface(GetRootElement()); if (node) { nsAutoString name, ns; if (NS_SUCCEEDED(node->GetLocalName(name)) && name.EqualsLiteral("parsererror") && NS_SUCCEEDED(node->GetNamespaceURI(ns)) && ns.EqualsLiteral("http://www.mozilla.org/newlayout/xml/parsererror.xml")) { //return is already false } else { *aReturn = true; } } } else { *aReturn = true; } return NS_OK; }
nsresult UnpackPDU(BluetoothDaemonPDU& aPDU, BluetoothProperty& aOut) { nsresult rv = UnpackPDU(aPDU, aOut.mType); if (NS_FAILED(rv)) { return rv; } uint16_t len; rv = UnpackPDU(aPDU, len); if (NS_FAILED(rv)) { return rv; } switch (aOut.mType) { case PROPERTY_BDNAME: /* fall through */ case PROPERTY_REMOTE_FRIENDLY_NAME: { const uint8_t* data = aPDU.Consume(len); if (NS_WARN_IF(!data)) { return NS_ERROR_ILLEGAL_VALUE; } // We construct an nsCString here because the string // returned from the PDU is not 0-terminated. aOut.mString = NS_ConvertUTF8toUTF16( nsCString(reinterpret_cast<const char*>(data), len)); } break; case PROPERTY_BDADDR: rv = UnpackPDU<BluetoothAddress>( aPDU, UnpackConversion<BluetoothAddress, nsAString>(aOut.mString)); break; case PROPERTY_UUIDS: { size_t numUuids = len / MAX_UUID_SIZE; aOut.mUuidArray.SetLength(numUuids); rv = UnpackPDU(aPDU, aOut.mUuidArray); } break; case PROPERTY_CLASS_OF_DEVICE: /* fall through */ case PROPERTY_ADAPTER_DISCOVERY_TIMEOUT: rv = UnpackPDU(aPDU, aOut.mUint32); break; case PROPERTY_TYPE_OF_DEVICE: rv = UnpackPDU(aPDU, aOut.mTypeOfDevice); break; case PROPERTY_SERVICE_RECORD: rv = UnpackPDU(aPDU, aOut.mServiceRecord); break; case PROPERTY_ADAPTER_SCAN_MODE: rv = UnpackPDU(aPDU, aOut.mScanMode); break; case PROPERTY_ADAPTER_BONDED_DEVICES: { /* unpack addresses */ size_t numAddresses = len / BLUETOOTH_ADDRESS_BYTES; nsAutoArrayPtr<BluetoothAddress> addresses; UnpackArray<BluetoothAddress> addressArray(addresses, numAddresses); rv = UnpackPDU(aPDU, addressArray); if (NS_FAILED(rv)) { return rv; } /* convert addresses to strings */ aOut.mStringArray.SetLength(numAddresses); ConvertArray<BluetoothAddress> convertArray(addressArray.mData, addressArray.mLength); rv = Convert(convertArray, aOut.mStringArray); } break; case PROPERTY_REMOTE_RSSI: { int8_t rssi; rv = UnpackPDU(aPDU, rssi); aOut.mInt32 = rssi; } break; case PROPERTY_REMOTE_VERSION_INFO: rv = UnpackPDU(aPDU, aOut.mRemoteInfo); break; case PROPERTY_REMOTE_DEVICE_TIMESTAMP: /* nothing to do */ break; default: break; } return rv; }
nsresult net_GetFileFromURLSpec(const nsACString &aURL, nsIFile **result) { nsresult rv; nsCOMPtr<nsILocalFile> localFile( do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv)); if (NS_FAILED(rv)) { NS_ERROR("Only nsILocalFile supported right now"); return rv; } localFile->SetFollowLinks(PR_TRUE); const nsACString *specPtr; nsCAutoString buf; if (net_NormalizeFileURL(aURL, buf)) specPtr = &buf; else specPtr = &aURL; nsCAutoString directory, fileBaseName, fileExtension; rv = net_ParseFileURL(*specPtr, directory, fileBaseName, fileExtension); if (NS_FAILED(rv)) return rv; nsCAutoString path; if (!directory.IsEmpty()) { NS_EscapeURL(directory, esc_Directory|esc_AlwaysCopy, path); if (path.Length() > 2 && path.CharAt(2) == '|') path.SetCharAt(':', 2); path.ReplaceChar('/', '\\'); } if (!fileBaseName.IsEmpty()) NS_EscapeURL(fileBaseName, esc_FileBaseName|esc_AlwaysCopy, path); if (!fileExtension.IsEmpty()) { path += '.'; NS_EscapeURL(fileExtension, esc_FileExtension|esc_AlwaysCopy, path); } NS_UnescapeURL(path); if (path.Length() != strlen(path.get())) return NS_ERROR_FILE_INVALID_PATH; // remove leading '\' if (path.CharAt(0) == '\\') path.Cut(0, 1); if (IsUTF8(path)) rv = localFile->InitWithPath(NS_ConvertUTF8toUTF16(path)); // XXX In rare cases, a valid UTF-8 string can be valid as a native // encoding (e.g. 0xC5 0x83 is valid both as UTF-8 and Windows-125x). // However, the chance is very low that a meaningful word in a legacy // encoding is valid as UTF-8. else // if path is not in UTF-8, assume it is encoded in the native charset rv = localFile->InitWithNativePath(path); if (NS_FAILED(rv)) return rv; NS_ADDREF(*result = localFile); return NS_OK; }
char* PR_CALLBACK PK11PasswordPrompt(PK11SlotInfo* slot, PRBool retry, void* arg) { nsNSSShutDownPreventionLock locker; nsresult rv = NS_OK; PRUnichar *password = nsnull; PRBool value = PR_FALSE; nsIInterfaceRequestor *ir = static_cast<nsIInterfaceRequestor*>(arg); nsCOMPtr<nsIPrompt> proxyPrompt; /* TODO: Retry should generate a different dialog message */ /* if (retry) return nsnull; */ if (!ir) { nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID)); if (!wwatch) return nsnull; nsCOMPtr<nsIPrompt> prompter; wwatch->GetNewPrompter(0, getter_AddRefs(prompter)); if (!prompter) return nsnull; NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIPrompt), prompter, NS_PROXY_SYNC, getter_AddRefs(proxyPrompt)); if (!proxyPrompt) return nsnull; } else { // The interface requestor object may not be safe, so // proxy the call to get the nsIPrompt. nsCOMPtr<nsIInterfaceRequestor> proxiedCallbacks; NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIInterfaceRequestor), ir, NS_PROXY_SYNC, getter_AddRefs(proxiedCallbacks)); // Get the desired interface nsCOMPtr<nsIPrompt> prompt(do_GetInterface(proxiedCallbacks)); if (!prompt) { NS_ASSERTION(PR_FALSE, "callbacks does not implement nsIPrompt"); return nsnull; } // Finally, get a proxy for the nsIPrompt NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIPrompt), prompt, NS_PROXY_SYNC, getter_AddRefs(proxyPrompt)); } if (PK11_ProtectedAuthenticationPath(slot)) return ShowProtectedAuthPrompt(slot, ir); nsAutoString promptString; nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv)); if (NS_FAILED(rv)) return nsnull; const PRUnichar* formatStrings[1] = { ToNewUnicode(NS_ConvertUTF8toUTF16(PK11_GetTokenName(slot))) }; rv = nssComponent->PIPBundleFormatStringFromName("CertPassPrompt", formatStrings, 1, promptString); nsMemory::Free(const_cast<PRUnichar*>(formatStrings[0])); if (NS_FAILED(rv)) return nsnull; { nsPSMUITracker tracker; if (tracker.isUIForbidden()) { rv = NS_ERROR_NOT_AVAILABLE; } else { rv = proxyPrompt->PromptPassword(nsnull, promptString.get(), &password, nsnull, nsnull, &value); } } if (NS_SUCCEEDED(rv) && value) { char* str = ToNewUTF8String(nsDependentString(password)); NS_Free(password); return str; } return nsnull; }
// General note about return values: // return 1 for a setup or xpcom type failure, return 2 for a real test failure int main(int argc, char** argv) { ScopedXPCOM xpcom("TestMsgStripRE.cpp"); if (xpcom.failed()) return 1; nsresult rv; nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv)); NS_ENSURE_SUCCESS(rv, rv); // create an nsISupportsString and stuff our literal into it nsCOMPtr<nsISupportsString> rePrefixes = do_CreateInstance("@mozilla.org/supports-string;1", &rv); NS_ENSURE_SUCCESS(rv, rv); // portable C++ expression of "SV,ÆØÅ" static const unsigned char utf8Prefixes[] = {'S', 'V', ',', 0303, 0206, 0303, 0230, 0303, 0205, '\0'}; rv = rePrefixes->SetData(NS_ConvertUTF8toUTF16(utf8Prefixes)); NS_ENSURE_SUCCESS(rv, rv); // set localizedRe pref rv = prefBranch->SetComplexValue("mailnews.localizedRe", NS_GET_IID(nsISupportsString), rePrefixes); NS_ENSURE_SUCCESS(rv, rv); // run our tests struct testInfo testInfoStructs[] = { {"SV: =?ISO-8859-1?Q?=C6blegr=F8d?=", "=?ISO-8859-1?Q?=C6blegr=F8d?=", PR_TRUE}, {"=?ISO-8859-1?Q?SV=3A=C6blegr=F8d?=", "=?ISO-8859-1?Q?=C6blegr=F8d?=", PR_TRUE}, // Note that in the next two tests, the only ISO-8859-1 chars are in the // localizedRe piece, so once they've been stripped, the re-encoding process // simply writes out ASCII rather than an ISO-8859-1 encoded string with // no actual ISO-8859-1 special characters, which seems reasonable. {"=?ISO-8859-1?Q?=C6=D8=C5=3A_Foo_bar?=", "Foo bar", PR_TRUE}, {"=?ISO-8859-1?Q?=C6=D8=C5=3AFoo_bar?=", "Foo bar", PR_TRUE} }; bool allTestsPassed = true; int result; for (unsigned int i = 0; i < NS_ARRAY_LENGTH(testInfoStructs); i++) { result = testStripRe(testInfoStructs[i].encodedInput, testInfoStructs[i].expectedOutput, testInfoStructs[i].expectedDidModify); if (result) { fail("%s, i=%d | result=%d\n", __FILE__, i, result); allTestsPassed = false; } } if (allTestsPassed) { passed("all tests passed\n"); } return allTestsPassed ? 0 : 2; }
void PR_CALLBACK HandshakeCallback(PRFileDesc* fd, void* client_data) { nsNSSShutDownPreventionLock locker; PRInt32 sslStatus; char* signer = nsnull; char* cipherName = nsnull; PRInt32 keyLength; nsresult rv; PRInt32 encryptBits; if (SECSuccess != SSL_SecurityStatus(fd, &sslStatus, &cipherName, &keyLength, &encryptBits, &signer, nsnull)) { return; } PRInt32 secStatus; if (sslStatus == SSL_SECURITY_STATUS_OFF) secStatus = nsIWebProgressListener::STATE_IS_BROKEN; else if (encryptBits >= 90) secStatus = (nsIWebProgressListener::STATE_IS_SECURE | nsIWebProgressListener::STATE_SECURE_HIGH); else secStatus = (nsIWebProgressListener::STATE_IS_SECURE | nsIWebProgressListener::STATE_SECURE_LOW); CERTCertificate *peerCert = SSL_PeerCertificate(fd); const char* caName = nsnull; // caName is a pointer only, no ownership char* certOrgName = CERT_GetOrgName(&peerCert->issuer); CERT_DestroyCertificate(peerCert); caName = certOrgName ? certOrgName : signer; const char* verisignName = "Verisign, Inc."; // If the CA name is RSA Data Security, then change the name to the real // name of the company i.e. VeriSign, Inc. if (nsCRT::strcmp((const char*)caName, "RSA Data Security, Inc.") == 0) { caName = verisignName; } nsAutoString shortDesc; const PRUnichar* formatStrings[1] = { ToNewUnicode(NS_ConvertUTF8toUTF16(caName)) }; nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv)); if (NS_SUCCEEDED(rv)) { rv = nssComponent->PIPBundleFormatStringFromName("SignedBy", formatStrings, 1, shortDesc); nsMemory::Free(const_cast<PRUnichar*>(formatStrings[0])); nsNSSSocketInfo* infoObject = (nsNSSSocketInfo*) fd->higher->secret; infoObject->SetSecurityState(secStatus); infoObject->SetShortSecurityDescription(shortDesc.get()); /* Set the SSL Status information */ nsRefPtr<nsSSLStatus> status = infoObject->SSLStatus(); if (!status) { status = new nsSSLStatus(); infoObject->SetSSLStatus(status); } CERTCertificate *serverCert = SSL_PeerCertificate(fd); if (serverCert) { nsRefPtr<nsNSSCertificate> nssc = new nsNSSCertificate(serverCert); CERT_DestroyCertificate(serverCert); serverCert = nsnull; nsCOMPtr<nsIX509Cert> prevcert; infoObject->GetPreviousCert(getter_AddRefs(prevcert)); PRBool equals_previous = PR_FALSE; if (prevcert) { nsresult rv = nssc->Equals(prevcert, &equals_previous); if (NS_FAILED(rv)) { equals_previous = PR_FALSE; } } if (equals_previous) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("HandshakeCallback using PREV cert %p\n", prevcert.get())); infoObject->SetCert(prevcert); status->mServerCert = prevcert; } else { if (status->mServerCert) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("HandshakeCallback KEEPING cert %p\n", status->mServerCert.get())); infoObject->SetCert(status->mServerCert); } else { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("HandshakeCallback using NEW cert %p\n", nssc.get())); infoObject->SetCert(nssc); status->mServerCert = nssc; } } } status->mHaveKeyLengthAndCipher = PR_TRUE; status->mKeyLength = keyLength; status->mSecretKeyLength = encryptBits; status->mCipherName.Adopt(cipherName); } PR_FREEIF(certOrgName); PR_Free(signer); }
// Override a web page NS_IMETHODIMP nsParentalControlsServiceWin::RequestURIOverrides(nsIArray *aTargets, nsIInterfaceRequestor *aWindowContext, bool *_retval) { *_retval = false; if (!mEnabled) return NS_ERROR_NOT_AVAILABLE; NS_ENSURE_ARG_POINTER(aTargets); uint32_t arrayLength = 0; aTargets->GetLength(&arrayLength); if (!arrayLength) return NS_ERROR_INVALID_ARG; if (arrayLength == 1) { nsCOMPtr<nsIURI> uri = do_QueryElementAt(aTargets, 0); if (!uri) return NS_ERROR_INVALID_ARG; return RequestURIOverride(uri, aWindowContext, _retval); } HWND hWnd = nullptr; // If we have a native window, use its handle instead nsCOMPtr<nsIWidget> widget(do_GetInterface(aWindowContext)); if (widget) hWnd = (HWND)widget->GetNativeData(NS_NATIVE_WINDOW); if (hWnd == nullptr) hWnd = GetDesktopWindow(); // The first entry should be the root uri nsAutoCString rootSpec; nsCOMPtr<nsIURI> rootURI = do_QueryElementAt(aTargets, 0); if (!rootURI) return NS_ERROR_INVALID_ARG; rootURI->GetSpec(rootSpec); if (rootSpec.IsEmpty()) return NS_ERROR_INVALID_ARG; // Allocate an array of sub uri int32_t count = arrayLength - 1; nsAutoArrayPtr<LPCWSTR> arrUrls(new LPCWSTR[count]); if (!arrUrls) return NS_ERROR_OUT_OF_MEMORY; uint32_t uriIdx = 0, idx; for (idx = 1; idx < arrayLength; idx++) { nsCOMPtr<nsIURI> uri = do_QueryElementAt(aTargets, idx); if (!uri) continue; nsAutoCString subURI; if (NS_FAILED(uri->GetSpec(subURI))) continue; arrUrls[uriIdx] = (LPCWSTR)UTF8ToNewUnicode(subURI); // allocation if (!arrUrls[uriIdx]) continue; uriIdx++; } if (!uriIdx) return NS_ERROR_INVALID_ARG; BOOL ret; nsRefPtr<IWPCWebSettings> wpcws; if (SUCCEEDED(mPC->GetWebSettings(nullptr, getter_AddRefs(wpcws)))) { wpcws->RequestURLOverride(hWnd, NS_ConvertUTF8toUTF16(rootSpec).get(), uriIdx, (LPCWSTR*)arrUrls.get(), &ret); *_retval = ret; } // Free up the allocated strings in our array for (idx = 0; idx < uriIdx; idx++) NS_Free((void*)arrUrls[idx]); return NS_OK; }
/** * Returns a list of nsILocalHandlerApp objects containing local * handlers associated with this mimeinfo. Implemented per * platform using information in this object to generate the * best list. Typically used for an "open with" style user * option. * * @return nsIArray of nsILocalHandlerApp */ NS_IMETHODIMP nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray **_retval) { nsresult rv; *_retval = nullptr; nsCOMPtr<nsIMutableArray> appList = do_CreateInstance("@mozilla.org/array;1"); if (!appList) return NS_ERROR_FAILURE; nsTArray<nsString> trackList; nsCAutoString fileExt; GetPrimaryExtension(fileExt); nsCOMPtr<nsIWindowsRegKey> regKey = do_CreateInstance("@mozilla.org/windows-registry-key;1"); if (!regKey) return NS_ERROR_FAILURE; nsCOMPtr<nsIWindowsRegKey> appKey = do_CreateInstance("@mozilla.org/windows-registry-key;1"); if (!appKey) return NS_ERROR_FAILURE; nsAutoString workingRegistryPath; bool extKnown = false; if (fileExt.IsEmpty()) { extKnown = true; // Mime type discovery is possible in some cases, through // HKEY_CLASSES_ROOT\MIME\Database\Content Type, however, a number // of file extensions related to mime type are simply not defined, // (application/rss+xml & application/atom+xml are good examples) // in which case we can only provide a generic list. nsCAutoString mimeType; GetMIMEType(mimeType); if (!mimeType.IsEmpty()) { workingRegistryPath.AppendLiteral("MIME\\Database\\Content Type\\"); workingRegistryPath.Append(NS_ConvertASCIItoUTF16(mimeType)); rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, workingRegistryPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if(NS_SUCCEEDED(rv)) { nsAutoString mimeFileExt; if (NS_SUCCEEDED(regKey->ReadStringValue(EmptyString(), mimeFileExt))) { CopyUTF16toUTF8(mimeFileExt, fileExt); extKnown = false; } } } } nsAutoString fileExtToUse; if (fileExt.First() != '.') fileExtToUse = PRUnichar('.'); fileExtToUse.Append(NS_ConvertUTF8toUTF16(fileExt)); // Note, the order in which these occur has an effect on the // validity of the resulting display list. if (!extKnown) { // 1) Get the default handler if it exists workingRegistryPath = fileExtToUse; rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, workingRegistryPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { nsAutoString appProgId; if (NS_SUCCEEDED(regKey->ReadStringValue(EmptyString(), appProgId))) { // Bug 358297 - ignore the embedded internet explorer handler if (appProgId != NS_LITERAL_STRING("XPSViewer.Document")) { nsAutoString appFilesystemCommand; if (GetProgIDVerbCommandHandler(appProgId, appFilesystemCommand, false) && !IsPathInList(appFilesystemCommand, trackList)) { ProcessPath(appList, trackList, appFilesystemCommand); } } } regKey->Close(); } // 2) list HKEY_CLASSES_ROOT\.ext\OpenWithList\ workingRegistryPath = fileExtToUse; workingRegistryPath.AppendLiteral("\\OpenWithList"); rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, workingRegistryPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { uint32_t count = 0; if (NS_SUCCEEDED(regKey->GetValueCount(&count)) && count > 0) { for (uint32_t index = 0; index < count; index++) { nsAutoString appName; if (NS_FAILED(regKey->GetValueName(index, appName))) continue; // HKEY_CLASSES_ROOT\Applications\firefox.exe = "path params" nsAutoString appFilesystemCommand; if (!GetAppsVerbCommandHandler(appName, appFilesystemCommand, false) || IsPathInList(appFilesystemCommand, trackList)) continue; ProcessPath(appList, trackList, appFilesystemCommand); } } regKey->Close(); } // 3) List HKEY_CLASSES_ROOT\.ext\OpenWithProgids, with the // different step of resolving the progids for the command handler. workingRegistryPath = fileExtToUse; workingRegistryPath.AppendLiteral("\\OpenWithProgids"); rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, workingRegistryPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { uint32_t count = 0; if (NS_SUCCEEDED(regKey->GetValueCount(&count)) && count > 0) { for (uint32_t index = 0; index < count; index++) { // HKEY_CLASSES_ROOT\.ext\OpenWithProgids\Windows.XPSReachViewer nsAutoString appProgId; if (NS_FAILED(regKey->GetValueName(index, appProgId))) continue; nsAutoString appFilesystemCommand; if (!GetProgIDVerbCommandHandler(appProgId, appFilesystemCommand, false) || IsPathInList(appFilesystemCommand, trackList)) continue; ProcessPath(appList, trackList, appFilesystemCommand); } } regKey->Close(); } // 4) Add any non configured applications located in the MRU list // HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ // Explorer\FileExts\.ext\OpenWithList workingRegistryPath = NS_LITERAL_STRING("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\"); workingRegistryPath += fileExtToUse; workingRegistryPath.AppendLiteral("\\OpenWithList"); rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, workingRegistryPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { uint32_t count = 0; if (NS_SUCCEEDED(regKey->GetValueCount(&count)) && count > 0) { for (uint32_t index = 0; index < count; index++) { nsAutoString appName, appValue; if (NS_FAILED(regKey->GetValueName(index, appName))) continue; if (appName.EqualsLiteral("MRUList")) continue; if (NS_FAILED(regKey->ReadStringValue(appName, appValue))) continue; // HKEY_CLASSES_ROOT\Applications\firefox.exe = "path params" nsAutoString appFilesystemCommand; if (!GetAppsVerbCommandHandler(appValue, appFilesystemCommand, false) || IsPathInList(appFilesystemCommand, trackList)) continue; ProcessPath(appList, trackList, appFilesystemCommand); } } } // 5) Add any non configured progids in the MRU list, with the // different step of resolving the progids for the command handler. // HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ // Explorer\FileExts\.ext\OpenWithProgids workingRegistryPath = NS_LITERAL_STRING("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\"); workingRegistryPath += fileExtToUse; workingRegistryPath.AppendLiteral("\\OpenWithProgids"); regKey->Open(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, workingRegistryPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { uint32_t count = 0; if (NS_SUCCEEDED(regKey->GetValueCount(&count)) && count > 0) { for (uint32_t index = 0; index < count; index++) { nsAutoString appIndex, appProgId; if (NS_FAILED(regKey->GetValueName(index, appProgId))) continue; nsAutoString appFilesystemCommand; if (!GetProgIDVerbCommandHandler(appProgId, appFilesystemCommand, false) || IsPathInList(appFilesystemCommand, trackList)) continue; ProcessPath(appList, trackList, appFilesystemCommand); } } regKey->Close(); } // 6) Check the perceived type value, and use this to lookup the perceivedtype // open with list. // http://msdn2.microsoft.com/en-us/library/aa969373.aspx workingRegistryPath = fileExtToUse; regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, workingRegistryPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { nsAutoString perceivedType; rv = regKey->ReadStringValue(NS_LITERAL_STRING("PerceivedType"), perceivedType); if (NS_SUCCEEDED(rv)) { nsAutoString openWithListPath(NS_LITERAL_STRING("SystemFileAssociations\\")); openWithListPath.Append(perceivedType); // no period openWithListPath.Append(NS_LITERAL_STRING("\\OpenWithList")); nsresult rv = appKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, openWithListPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { uint32_t count = 0; if (NS_SUCCEEDED(regKey->GetValueCount(&count)) && count > 0) { for (uint32_t index = 0; index < count; index++) { nsAutoString appName; if (NS_FAILED(regKey->GetValueName(index, appName))) continue; // HKEY_CLASSES_ROOT\Applications\firefox.exe = "path params" nsAutoString appFilesystemCommand; if (!GetAppsVerbCommandHandler(appName, appFilesystemCommand, false) || IsPathInList(appFilesystemCommand, trackList)) continue; ProcessPath(appList, trackList, appFilesystemCommand); } } } } } } // extKnown == false // 7) list global HKEY_CLASSES_ROOT\*\OpenWithList\ // Listing general purpose handlers, not specific to a mime type or file extension workingRegistryPath = NS_LITERAL_STRING("*\\OpenWithList"); rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, workingRegistryPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { uint32_t count = 0; if (NS_SUCCEEDED(regKey->GetValueCount(&count)) && count > 0) { for (uint32_t index = 0; index < count; index++) { nsAutoString appName; if (NS_FAILED(regKey->GetValueName(index, appName))) continue; // HKEY_CLASSES_ROOT\Applications\firefox.exe = "path params" nsAutoString appFilesystemCommand; if (!GetAppsVerbCommandHandler(appName, appFilesystemCommand, false) || IsPathInList(appFilesystemCommand, trackList)) continue; ProcessPath(appList, trackList, appFilesystemCommand); } } regKey->Close(); } // 8) General application's list - not file extension specific on windows workingRegistryPath = NS_LITERAL_STRING("Applications"); rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, workingRegistryPath, nsIWindowsRegKey::ACCESS_ENUMERATE_SUB_KEYS| nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { uint32_t count = 0; if (NS_SUCCEEDED(regKey->GetChildCount(&count)) && count > 0) { for (uint32_t index = 0; index < count; index++) { nsAutoString appName; if (NS_FAILED(regKey->GetChildName(index, appName))) continue; // HKEY_CLASSES_ROOT\Applications\firefox.exe = "path params" nsAutoString appFilesystemCommand; if (!GetAppsVerbCommandHandler(appName, appFilesystemCommand, false) || IsPathInList(appFilesystemCommand, trackList)) continue; ProcessPath(appList, trackList, appFilesystemCommand); } } } // Return to the caller *_retval = appList; NS_ADDREF(*_retval); return NS_OK; }
void Decoder::Finish(RasterImage::eShutdownIntent aShutdownIntent) { MOZ_ASSERT(NS_IsMainThread()); // Implementation-specific finalization if (!HasError()) FinishInternal(); // If the implementation left us mid-frame, finish that up. if (mInFrame && !HasError()) PostFrameStop(); // If PostDecodeDone() has not been called, we need to sent teardown // notifications. if (!IsSizeDecode() && !mDecodeDone) { // Log data errors to the error console nsCOMPtr<nsIConsoleService> consoleService = do_GetService(NS_CONSOLESERVICE_CONTRACTID); nsCOMPtr<nsIScriptError> errorObject = do_CreateInstance(NS_SCRIPTERROR_CONTRACTID); if (consoleService && errorObject && !HasDecoderError()) { nsAutoString msg(NS_LITERAL_STRING("Image corrupt or truncated: ") + NS_ConvertUTF8toUTF16(mImage.GetURIString())); if (NS_SUCCEEDED(errorObject->InitWithWindowID( msg, NS_ConvertUTF8toUTF16(mImage.GetURIString()), EmptyString(), 0, 0, nsIScriptError::errorFlag, "Image", mImage.InnerWindowID() ))) { consoleService->LogMessage(errorObject); } } bool usable = !HasDecoderError(); if (aShutdownIntent != RasterImage::eShutdownIntent_NotNeeded && !HasDecoderError()) { // If we only have a data error, we're usable if we have at least one complete frame. if (GetCompleteFrameCount() == 0) { usable = false; } } // If we're usable, do exactly what we should have when the decoder // completed. if (usable) { if (mInFrame) { PostFrameStop(); } PostDecodeDone(); } else { if (mObserver) { mObserver->OnStopDecode(NS_ERROR_FAILURE); } } } // Set image metadata before calling DecodingComplete, because DecodingComplete calls Optimize(). mImageMetadata.SetOnImage(&mImage); if (mDecodeDone) { mImage.DecodingComplete(); } }
nsresult nsAbLDAPProcessChangeLogData::GetAuthData() { if(!mInitialized) return NS_ERROR_NOT_INITIALIZED; nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID)); if (!wwatch) return NS_ERROR_FAILURE; nsCOMPtr<nsIAuthPrompt> dialog; nsresult rv = wwatch->GetNewAuthPrompter(0, getter_AddRefs(dialog)); if (NS_FAILED(rv)) return rv; if (!dialog) return NS_ERROR_FAILURE; nsCOMPtr<nsILDAPURL> url; rv = mQuery->GetReplicationURL(getter_AddRefs(url)); if (NS_FAILED(rv)) return rv; nsCAutoString serverUri; rv = url->GetSpec(serverUri); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIStringBundleService> bundleService = mozilla::services::GetStringBundleService(); NS_ENSURE_TRUE(bundleService, NS_ERROR_UNEXPECTED); nsCOMPtr<nsIStringBundle> bundle; rv = bundleService->CreateBundle("chrome://messenger/locale/addressbook/addressBook.properties", getter_AddRefs(bundle)); if (NS_FAILED (rv)) return rv ; nsString title; rv = bundle->GetStringFromName(NS_LITERAL_STRING("AuthDlgTitle").get(), getter_Copies(title)); if (NS_FAILED (rv)) return rv ; nsString desc; rv = bundle->GetStringFromName(NS_LITERAL_STRING("AuthDlgDesc").get(), getter_Copies(desc)); if (NS_FAILED (rv)) return rv ; nsString username; nsString password; bool btnResult = false; rv = dialog->PromptUsernameAndPassword(title, desc, NS_ConvertUTF8toUTF16(serverUri).get(), nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY, getter_Copies(username), getter_Copies(password), &btnResult); if(NS_SUCCEEDED(rv) && btnResult) { CopyUTF16toUTF8(username, mAuthUserID); CopyUTF16toUTF8(password, mAuthPswd); } else rv = NS_ERROR_FAILURE; return rv; }
nsresult UDPSocket::InitLocal(const nsAString& aLocalAddress, const uint16_t& aLocalPort) { nsresult rv; nsCOMPtr<nsIUDPSocket> sock = do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv); if (NS_FAILED(rv)) { return rv; } nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetOwner(), &rv); if (NS_FAILED(rv)) { return rv; } nsCOMPtr<nsIPrincipal> principal = global->PrincipalOrNull(); if (!principal) { return NS_ERROR_FAILURE; } if (aLocalAddress.IsEmpty()) { rv = sock->Init(aLocalPort, /* loopback = */ false, principal, mAddressReuse, /* optionalArgc = */ 1); } else { PRNetAddr prAddr; PR_InitializeNetAddr(PR_IpAddrAny, aLocalPort, &prAddr); PR_StringToNetAddr(NS_ConvertUTF16toUTF8(aLocalAddress).BeginReading(), &prAddr); UDPSOCKET_LOG(("%s: %s:%u", __FUNCTION__, NS_ConvertUTF16toUTF8(aLocalAddress).get(), aLocalPort)); mozilla::net::NetAddr addr; PRNetAddrToNetAddr(&prAddr, &addr); rv = sock->InitWithAddress(&addr, principal, mAddressReuse, /* optionalArgc = */ 1); } if (NS_FAILED(rv)) { return rv; } rv = sock->SetMulticastLoopback(mLoopback); if (NS_FAILED(rv)) { return rv; } mSocket = sock; // Get real local address and local port nsCOMPtr<nsINetAddr> localAddr; rv = mSocket->GetLocalAddr(getter_AddRefs(localAddr)); if (NS_FAILED(rv)) { return rv; } nsCString localAddress; rv = localAddr->GetAddress(localAddress); if (NS_FAILED(rv)) { return rv; } mLocalAddress = NS_ConvertUTF8toUTF16(localAddress); uint16_t localPort; rv = localAddr->GetPort(&localPort); if (NS_FAILED(rv)) { return rv; } mLocalPort.SetValue(localPort); mListenerProxy = new ListenerProxy(this); rv = mSocket->AsyncListen(mListenerProxy); if (NS_FAILED(rv)) { return rv; } mReadyState = SocketReadyState::Open; rv = DoPendingMcastCommand(); if (NS_FAILED(rv)) { return rv; } mOpened->MaybeResolve(JS::UndefinedHandleValue); return NS_OK; }
nsresult EventListenerManager::SetEventHandler(nsIAtom* aName, const nsAString& aBody, uint32_t aLanguage, bool aDeferCompilation, bool aPermitUntrustedEvents, Element* aElement) { NS_PRECONDITION(aLanguage != nsIProgrammingLanguage::UNKNOWN, "Must know the language for the script event listener"); // |aPermitUntrustedEvents| is set to False for chrome - events // *generated* from an unknown source are not allowed. // However, for script languages with no 'sandbox', we want to reject // such scripts based on the source of their code, not just the source // of the event. if (aPermitUntrustedEvents && aLanguage != nsIProgrammingLanguage::JAVASCRIPT) { NS_WARNING("Discarding non-JS event listener from untrusted source"); return NS_ERROR_FAILURE; } nsCOMPtr<nsIDocument> doc; nsCOMPtr<nsIScriptGlobalObject> global = GetScriptGlobalAndDocument(getter_AddRefs(doc)); if (!global) { // This can happen; for example this document might have been // loaded as data. return NS_OK; } #ifdef DEBUG nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(global); if (win) { MOZ_ASSERT(win->IsInnerWindow(), "We should not have an outer window here!"); } #endif nsresult rv = NS_OK; // return early preventing the event listener from being added // 'doc' is fetched above if (doc) { // Don't allow adding an event listener if the document is sandboxed // without 'allow-scripts'. if (doc->GetSandboxFlags() & SANDBOXED_SCRIPTS) { return NS_ERROR_DOM_SECURITY_ERR; } nsCOMPtr<nsIContentSecurityPolicy> csp; rv = doc->NodePrincipal()->GetCsp(getter_AddRefs(csp)); NS_ENSURE_SUCCESS(rv, rv); if (csp) { bool inlineOK = true; bool reportViolations = false; rv = csp->GetAllowsInlineScript(&reportViolations, &inlineOK); NS_ENSURE_SUCCESS(rv, rv); if (reportViolations) { // gather information to log with violation report nsIURI* uri = doc->GetDocumentURI(); nsAutoCString asciiSpec; if (uri) uri->GetAsciiSpec(asciiSpec); nsAutoString scriptSample, attr, tagName(NS_LITERAL_STRING("UNKNOWN")); aName->ToString(attr); nsCOMPtr<nsIDOMNode> domNode(do_QueryInterface(mTarget)); if (domNode) domNode->GetNodeName(tagName); // build a "script sample" based on what we know about this element scriptSample.Assign(attr); scriptSample.AppendLiteral(" attribute on "); scriptSample.Append(tagName); scriptSample.AppendLiteral(" element"); csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_INLINE_SCRIPT, NS_ConvertUTF8toUTF16(asciiSpec), scriptSample, 0, EmptyString(), EmptyString()); } // return early if CSP wants us to block inline scripts if (!inlineOK) { return NS_OK; } } } // This might be the first reference to this language in the global // We must init the language before we attempt to fetch its context. if (NS_FAILED(global->EnsureScriptEnvironment())) { NS_WARNING("Failed to setup script environment for this language"); // but fall through and let the inevitable failure below handle it. } nsIScriptContext* context = global->GetScriptContext(); NS_ENSURE_TRUE(context, NS_ERROR_FAILURE); NS_ENSURE_STATE(global->GetGlobalJSObject()); JSAutoRequest ar(context->GetNativeContext()); JS::Rooted<JSObject*> scope(context->GetNativeContext(), global->GetGlobalJSObject()); Listener* listener = SetEventHandlerInternal(scope, aName, EmptyString(), nsEventHandler(), aPermitUntrustedEvents); if (!aDeferCompilation) { return CompileEventHandlerInternal(listener, &aBody, aElement); } return NS_OK; }
nsAutoString QtString2NSString ( const QString &qtString ) { return NS_ConvertUTF8toUTF16( qtString.toUtf8().data() ); }
nsresult nsDOMStorage::SetDBValue(const nsAString& aKey, const nsAString& aValue, PRBool aSecure) { #ifdef MOZ_STORAGE if (!UseDB()) return NS_OK; nsresult rv = InitDB(); NS_ENSURE_SUCCESS(rv, rv); // Get the current domain for quota enforcement nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager(); if (!ssm) return NS_ERROR_FAILURE; nsCOMPtr<nsIPrincipal> subjectPrincipal; ssm->GetSubjectPrincipal(getter_AddRefs(subjectPrincipal)); nsCAutoString currentDomain; if (subjectPrincipal) { nsCOMPtr<nsIURI> unused; rv = GetPrincipalURIAndHost(subjectPrincipal, getter_AddRefs(unused), currentDomain); // Don't bail out on NS_ERROR_DOM_SECURITY_ERR, since we want to allow // trusted file:// URIs below. if (NS_FAILED(rv) && rv != NS_ERROR_DOM_SECURITY_ERR) { return rv; } if (currentDomain.IsEmpty()) { // allow chrome urls and trusted file urls to write using // the storage's domain if (nsContentUtils::IsCallerTrustedForWrite()) currentDomain = mDomain; else return NS_ERROR_DOM_SECURITY_ERR; } } else { currentDomain = mDomain; } PRInt32 quota; PRInt32 warnQuota; GetQuota(currentDomain, "a, &warnQuota); PRInt32 usage; rv = gStorageDB->SetKey(this, aKey, aValue, aSecure, quota, &usage); NS_ENSURE_SUCCESS(rv, rv); mItemsCached = PR_FALSE; if (warnQuota >= 0 && usage > warnQuota) { // try to include the window that exceeded the warn quota nsCOMPtr<nsIDOMWindow> window; JSContext *cx; nsCOMPtr<nsIJSContextStack> stack = do_GetService("@mozilla.org/js/xpc/ContextStack;1"); if (stack && NS_SUCCEEDED(stack->Peek(&cx)) && cx) { nsCOMPtr<nsIScriptContext> scriptContext; scriptContext = GetScriptContextFromJSContext(cx); if (scriptContext) { window = do_QueryInterface(scriptContext->GetGlobalObject()); } } nsCOMPtr<nsIObserverService> os = do_GetService("@mozilla.org/observer-service;1"); os->NotifyObservers(window, "dom-storage-warn-quota-exceeded", NS_ConvertUTF8toUTF16(currentDomain).get()); } BroadcastChangeNotification(); #endif return NS_OK; }
NS_IMETHODIMP FindLoginWithGUID(PRUint32 *count, const nsAString & aGUID, nsILoginInfo ***logins) { PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLoginWithGUID() Called") ); *count = 0; nsresult res = checkWallet(); NS_ENSURE_SUCCESS(res, res); QString mGUID = NSString2QtString( aGUID ); PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLoginWithGUID() Trying to find guid %s", mGUID.toUtf8().data() ) ); QString key = generateQueryWalletKey( NS_ConvertUTF8toUTF16( "*" ), NS_ConvertUTF8toUTF16( "*" ), NS_ConvertUTF8toUTF16( "*" ), NS_ConvertUTF8toUTF16( "*" ) ); QMap< QString, QMap< QString, QString > > entryMap; if( wallet->readMapList( key, entryMap ) != 0 ) return NS_OK; PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLoginWithGUID() Found %d total maps", entryMap.count() ) ); if( entryMap.count() == 0 ) return NS_OK; QMapIterator< QString, QMap< QString, QString > > iterator(entryMap); while (iterator.hasNext()) { iterator.next(); QMap< QString, QString > entry = iterator.value(); if( entry.contains( kGuidAttr ) && entry.value( kGuidAttr ) == mGUID ) { nsCOMPtr<nsILoginInfo> loginInfo = do_CreateInstance(NS_LOGININFO_CONTRACTID); NS_ADDREF((nsILoginInfo*) loginInfo); if (!loginInfo) return NS_ERROR_FAILURE; nsAutoString temp; if( entry.contains( kHostnameAttr ) ) loginInfo->SetHostname( QtString2NSString( entry.value( kHostnameAttr ) ) ); if( entry.contains( kUsernameAttr ) ) loginInfo->SetUsername(QtString2NSString( entry.value( kUsernameAttr ) ) ); if( entry.contains( kUsernameFieldAttr ) ) loginInfo->SetUsernameField(QtString2NSString( entry.value( kUsernameFieldAttr ) ) ); if( entry.contains( kPasswordAttr ) ) loginInfo->SetPassword(QtString2NSString( entry.value( kPasswordAttr ) ) ); if( entry.contains( kPasswordFieldAttr ) ) loginInfo->SetPasswordField(QtString2NSString( entry.value( kPasswordFieldAttr ) ) ); if( entry.contains( kFormSubmitURLAttr ) ) loginInfo->SetFormSubmitURL(QtString2NSString( entry.value( kFormSubmitURLAttr ) ) ); if( entry.contains( kHttpRealmAttr ) ) loginInfo->SetHttpRealm(QtString2NSString( entry.value( kHttpRealmAttr ) ) ); nsCOMPtr<nsILoginMetaInfo> loginmeta( do_QueryInterface(loginInfo, &res) ); NS_ENSURE_SUCCESS(res, res); nsAutoString aGUID ; res = loginmeta->SetGuid(QtString2NSString( entry.value( kGuidAttr ) )); NS_ENSURE_SUCCESS(res, res); nsILoginInfo **array = (nsILoginInfo**) nsMemory::Alloc(sizeof(nsILoginInfo*)); NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY); memset(array, 0, sizeof(nsILoginInfo*)); PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLoginWithGUID() Found key: %s guid: %s", iterator.key().toUtf8().data(), entry.value( kGuidAttr ).toUtf8().data() ) ); array[0] = loginInfo; *logins = array; *count = 1; return NS_OK; } if( !entry.contains( kGuidAttr ) ) { nsCOMPtr<nsIUUIDGenerator> uuidgen = do_GetService("@mozilla.org/uuid-generator;1", &res); NS_ENSURE_SUCCESS(res, res); nsID GUID; res = uuidgen->GenerateUUIDInPlace(&GUID); NS_ENSURE_SUCCESS(res, res); char GUIDChars[NSID_LENGTH]; GUID.ToProvidedString(GUIDChars); QString mGUID(GUIDChars); entry[ kGuidAttr ] = mGUID; PR_LOG( gKDEWalletLog, PR_LOG_DEBUG, ( "KDEWallet::FindLoginWithGUID() Add guid %s to key: %s", mGUID.toUtf8().data(), iterator.key().toUtf8().data() ) ); if( wallet->writeMap( iterator.key(), entry ) ) { NS_ERROR("Can not save map information"); return NS_ERROR_FAILURE; } } } return NS_OK; }
NS_INTERFACE_MAP_END // nsIDOMCSSValue NS_IMETHODIMP nsROCSSPrimitiveValue::GetCssText(nsAString& aCssText) { nsAutoString tmpStr; aCssText.Truncate(); nsresult result = NS_OK; switch (mType) { case CSS_PX : { float val = nsPresContext::AppUnitsToFloatCSSPixels(mValue.mAppUnits); tmpStr.AppendFloat(val); tmpStr.AppendLiteral("px"); break; } case CSS_IDENT : { AppendUTF8toUTF16(nsCSSKeywords::GetStringValue(mValue.mKeyword), tmpStr); break; } case CSS_STRING : case CSS_COUNTER : /* FIXME: COUNTER should use an object */ { tmpStr.Append(mValue.mString); break; } case CSS_URI : { if (mValue.mURI) { nsCAutoString specUTF8; mValue.mURI->GetSpec(specUTF8); tmpStr.AssignLiteral("url("); nsStyleUtil::AppendEscapedCSSString(NS_ConvertUTF8toUTF16(specUTF8), tmpStr); tmpStr.AppendLiteral(")"); } else { // XXXldb Any better ideas? It's good to have something that // doesn't parse so that things round-trip "correctly". tmpStr.Assign(NS_LITERAL_STRING("url(invalid-url:)")); } break; } case CSS_ATTR : { tmpStr.AppendLiteral("attr("); tmpStr.Append(mValue.mString); tmpStr.Append(PRUnichar(')')); break; } case CSS_PERCENTAGE : { tmpStr.AppendFloat(mValue.mFloat * 100); tmpStr.Append(PRUnichar('%')); break; } case CSS_NUMBER : { tmpStr.AppendFloat(mValue.mFloat); break; } case CSS_RECT : { NS_ASSERTION(mValue.mRect, "mValue.mRect should never be null"); NS_NAMED_LITERAL_STRING(comma, ", "); nsCOMPtr<nsIDOMCSSPrimitiveValue> sideCSSValue; nsAutoString sideValue; tmpStr.AssignLiteral("rect("); // get the top result = mValue.mRect->GetTop(getter_AddRefs(sideCSSValue)); if (NS_FAILED(result)) break; result = sideCSSValue->GetCssText(sideValue); if (NS_FAILED(result)) break; tmpStr.Append(sideValue + comma); // get the right result = mValue.mRect->GetRight(getter_AddRefs(sideCSSValue)); if (NS_FAILED(result)) break; result = sideCSSValue->GetCssText(sideValue); if (NS_FAILED(result)) break; tmpStr.Append(sideValue + comma); // get the bottom result = mValue.mRect->GetBottom(getter_AddRefs(sideCSSValue)); if (NS_FAILED(result)) break; result = sideCSSValue->GetCssText(sideValue); if (NS_FAILED(result)) break; tmpStr.Append(sideValue + comma); // get the left result = mValue.mRect->GetLeft(getter_AddRefs(sideCSSValue)); if (NS_FAILED(result)) break; result = sideCSSValue->GetCssText(sideValue); if (NS_FAILED(result)) break; tmpStr.Append(sideValue + NS_LITERAL_STRING(")")); break; } case CSS_RGBCOLOR : { NS_ASSERTION(mValue.mColor, "mValue.mColor should never be null"); NS_NAMED_LITERAL_STRING(comma, ", "); nsCOMPtr<nsIDOMCSSPrimitiveValue> colorCSSValue; nsAutoString colorValue; if (mValue.mColor->HasAlpha()) tmpStr.AssignLiteral("rgba("); else tmpStr.AssignLiteral("rgb("); // get the red component result = mValue.mColor->GetRed(getter_AddRefs(colorCSSValue)); if (NS_FAILED(result)) break; result = colorCSSValue->GetCssText(colorValue); if (NS_FAILED(result)) break; tmpStr.Append(colorValue + comma); // get the green component result = mValue.mColor->GetGreen(getter_AddRefs(colorCSSValue)); if (NS_FAILED(result)) break; result = colorCSSValue->GetCssText(colorValue); if (NS_FAILED(result)) break; tmpStr.Append(colorValue + comma); // get the blue component result = mValue.mColor->GetBlue(getter_AddRefs(colorCSSValue)); if (NS_FAILED(result)) break; result = colorCSSValue->GetCssText(colorValue); if (NS_FAILED(result)) break; tmpStr.Append(colorValue); if (mValue.mColor->HasAlpha()) { // get the alpha component result = mValue.mColor->GetAlpha(getter_AddRefs(colorCSSValue)); if (NS_FAILED(result)) break; result = colorCSSValue->GetCssText(colorValue); if (NS_FAILED(result)) break; tmpStr.Append(comma + colorValue); } tmpStr.Append(NS_LITERAL_STRING(")")); break; } case CSS_S : { tmpStr.AppendFloat(mValue.mFloat); tmpStr.AppendLiteral("s"); break; } case CSS_CM : case CSS_MM : case CSS_IN : case CSS_PT : case CSS_PC : case CSS_UNKNOWN : case CSS_EMS : case CSS_EXS : case CSS_DEG : case CSS_RAD : case CSS_GRAD : case CSS_MS : case CSS_HZ : case CSS_KHZ : case CSS_DIMENSION : NS_ERROR("We have a bogus value set. This should not happen"); return NS_ERROR_DOM_INVALID_ACCESS_ERR; } if (NS_SUCCEEDED(result)) { aCssText.Assign(tmpStr); } return NS_OK; }