Bug 868120 - B2G MMS: Add 'mms.debugging.enabled' pref for MMS debug messages to make sure whether message is sent by SMS or MMS. r=vyang
authorChia-hung Tai <ctai@mozilla.com>
Mon, 06 May 2013 09:57:16 -0700
changeset 141942 bdaaedfc41f770434fa1c2c83550aae85d6d6651
parent 141941 0af678fcaeef72e17e898d387a7ff4a068160aa9
child 141943 390c431a2082e6ea9d4adcbe583080d793bcd656
push id2579
push userakeybl@mozilla.com
push dateMon, 24 Jun 2013 18:52:47 +0000
treeherdermozilla-beta@b69b7de8a05a [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersvyang
bugs868120
milestone23.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 868120 - B2G MMS: Add 'mms.debugging.enabled' pref for MMS debug messages to make sure whether message is sent by SMS or MMS. r=vyang
dom/mms/src/ril/MmsService.js
modules/libpref/src/init/all.js
--- a/dom/mms/src/ril/MmsService.js
+++ b/dom/mms/src/ril/MmsService.js
@@ -11,17 +11,23 @@ const {classes: Cc, interfaces: Ci, util
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 
 Cu.import("resource://gre/modules/NetUtil.jsm");
 
 const RIL_MMSSERVICE_CONTRACTID = "@mozilla.org/mms/rilmmsservice;1";
 const RIL_MMSSERVICE_CID = Components.ID("{217ddd76-75db-4210-955d-8806cd8d87f9}");
 
-const DEBUG = false;
+let DEBUG = false;
+
+// Read debug setting from pref.
+try {
+  let debugPref = Services.prefs.getBoolPref("mms.debugging.enabled");
+  DEBUG = DEBUG || debugPref;
+} catch (e) {}
 
 const kSmsSendingObserverTopic           = "sms-sending";
 const kSmsSentObserverTopic              = "sms-sent";
 const kSmsFailedObserverTopic            = "sms-failed";
 const kSmsReceivedObserverTopic          = "sms-received";
 
 const kNetworkInterfaceStateChangedTopic = "network-interface-state-changed";
 const kXpcomShutdownObserverTopic        = "xpcom-shutdown";
@@ -137,29 +143,29 @@ XPCOMUtils.defineLazyGetter(this, "gMmsC
     connectTimer: Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer),
 
     disconnectTimer: Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer),
 
     /**
      * Callback when |connectTimer| is timeout or cancelled by shutdown.
      */
     onConnectTimerTimeout: function onConnectTimerTimeout() {
-      debug("onConnectTimerTimeout: " + this.pendingCallbacks.length
-            + " pending callbacks");
+      if (DEBUG) debug("onConnectTimerTimeout: " + this.pendingCallbacks.length
+                       + " pending callbacks");
       while (this.pendingCallbacks.length) {
         let callback = this.pendingCallbacks.shift();
         callback(false);
       }
     },
 
     /**
      * Callback when |disconnectTimer| is timeout or cancelled by shutdown.
      */
     onDisconnectTimerTimeout: function onDisconnectTimerTimeout() {
-      debug("onDisconnectTimerTimeout: deactivate the MMS data call.");
+      if (DEBUG) debug("onDisconnectTimerTimeout: deactivate the MMS data call.");
       if (this.connected) {
         gRIL.deactivateDataCallByType("mms");
       }
     },
 
     init: function init() {
       Services.obs.addObserver(this, kNetworkInterfaceStateChangedTopic,
                                false);
@@ -169,33 +175,33 @@ XPCOMUtils.defineLazyGetter(this, "gMmsC
       }, this);
 
       try {
         this.mmsc = Services.prefs.getCharPref("ril.mms.mmsc");
         this.proxy = Services.prefs.getCharPref("ril.mms.mmsproxy");
         this.port = Services.prefs.getIntPref("ril.mms.mmsport");
         this.updateProxyInfo();
       } catch (e) {
-        debug("Unable to initialize the MMS proxy settings from the" +
-              "preference. This could happen at the first-run. Should be" +
-              "available later.");
+        if (DEBUG) debug("Unable to initialize the MMS proxy settings from the" +
+                         "preference. This could happen at the first-run. Should be" +
+                         "available later.");
         this.clearMmsProxySettings();
       }
       this.connected = gRIL.getDataCallStateByType("mms") ==
         Ci.nsINetworkInterface.NETWORK_STATE_CONNECTED;
     },
 
     /**
      * Return the roaming status of voice call.
      *
      * @return true if voice call is roaming.
      */
     isVoiceRoaming: function isVoiceRoaming() {
       let isRoaming = gRIL.rilContext.voice.roaming;
-      debug("isVoiceRoaming = " + isRoaming);
+      if (DEBUG) debug("isVoiceRoaming = " + isRoaming);
       return isRoaming;
     },
 
     /**
      * Acquire the MMS network connection.
      *
      * @param callback
      *        Callback function when either the connection setup is done,
@@ -206,17 +212,17 @@ XPCOMUtils.defineLazyGetter(this, "gMmsC
      *              callback is done; false otherwise.
      */
     acquire: function acquire(callback) {
       this.connectTimer.cancel();
 
       // If the MMS network is not yet connected, buffer the
       // MMS request and try to setup the MMS network first.
       if (!this.connected) {
-        debug("acquire: buffer the MMS request and setup the MMS data call.");
+        if (DEBUG) debug("acquire: buffer the MMS request and setup the MMS data call.");
         this.pendingCallbacks.push(callback);
         gRIL.setupDataCallByType("mms");
 
         // Set a timer to clear the buffered MMS requests if the
         // MMS network fails to be connected within a time period.
         this.connectTimer.
           initWithCallback(this.onConnectTimerTimeout.bind(this),
                            TIME_TO_BUFFER_MMS_REQUESTS,
@@ -247,25 +253,25 @@ XPCOMUtils.defineLazyGetter(this, "gMmsC
       }
     },
 
     /**
      * Update the MMS proxy info.
      */
     updateProxyInfo: function updateProxyInfo() {
       if (this.proxy === null || this.port === null) {
-        debug("updateProxyInfo: proxy or port is not yet decided." );
+        if (DEBUG) debug("updateProxyInfo: proxy or port is not yet decided." );
         return;
       }
 
       this.proxyInfo =
         gpps.newProxyInfo("http", this.proxy, this.port,
                           Ci.nsIProxyInfo.TRANSPARENT_PROXY_RESOLVES_HOST,
                           -1, null);
-      debug("updateProxyInfo: " + JSON.stringify(this.proxyInfo));
+      if (DEBUG) debug("updateProxyInfo: " + JSON.stringify(this.proxyInfo));
     },
 
     /**
      * Clear the MMS proxy settings.
      */
     clearMmsProxySettings: function clearMmsProxySettings() {
       this.mmsc = null;
       this.proxy = null;
@@ -292,18 +298,18 @@ XPCOMUtils.defineLazyGetter(this, "gMmsC
           this.connected =
             gRIL.getDataCallStateByType("mms") ==
               Ci.nsINetworkInterface.NETWORK_STATE_CONNECTED;
 
           if (!this.connected) {
             return;
           }
 
-          debug("Got the MMS network connected! Resend the buffered " +
-                "MMS requests: number: " + this.pendingCallbacks.length);
+          if (DEBUG) debug("Got the MMS network connected! Resend the buffered " +
+                           "MMS requests: number: " + this.pendingCallbacks.length);
           this.connectTimer.cancel();
           while (this.pendingCallbacks.length) {
             let callback = this.pendingCallbacks.shift();
             callback(true);
           }
           break;
         }
         case kPrefenceChangedObserverTopic: {
@@ -319,18 +325,18 @@ XPCOMUtils.defineLazyGetter(this, "gMmsC
               case "ril.mms.mmsport":
                 this.port = Services.prefs.getIntPref("ril.mms.mmsport");
                 this.updateProxyInfo();
                 break;
               default:
                 break;
             }
           } catch (e) {
-            debug("Failed to update the MMS proxy settings from the" +
-                  "preference.");
+            if (DEBUG) debug("Failed to update the MMS proxy settings from the" +
+                             "preference.");
             this.clearMmsProxySettings();
           }
           break;
         }
         case kXpcomShutdownObserverTopic: {
           Services.obs.removeObserver(this, kXpcomShutdownObserverTopic);
           this.shutdown();
         }
@@ -353,24 +359,24 @@ MmsProxyFilter.prototype = {
 
   applyFilter: function applyFilter(proxyService, uri, proxyInfo) {
     let url = uri.prePath + uri.path;
     if (url.endsWith("/")) {
       url = url.substr(0, url.length - 1);
     }
 
     if (this.url != url) {
-      debug("applyFilter: content uri = " + this.url +
-            " is not matched url = " + url + " .");
+      if (DEBUG) debug("applyFilter: content uri = " + this.url +
+                       " is not matched url = " + url + " .");
       return proxyInfo;
     }
     // Fall-through, reutrn the MMS proxy info.
-    debug("applyFilter: MMSC is matched: " +
-          JSON.stringify({ url: this.url,
-                           proxyInfo: gMmsConnection.proxyInfo }));
+    if (DEBUG) debug("applyFilter: MMSC is matched: " +
+                     JSON.stringify({ url: this.url,
+                                      roxyInfo: gMmsConnection.proxyInfo }));
     return gMmsConnection.proxyInfo ? gMmsConnection.proxyInfo : proxyInfo;
   }
 };
 
 XPCOMUtils.defineLazyGetter(this, "gMmsTransactionHelper", function () {
   return {
     /**
      * Send MMS request to MMSC.
@@ -394,17 +400,17 @@ XPCOMUtils.defineLazyGetter(this, "gMmsT
           // Connection timeout or failed. Report error.
           gMmsConnection.release();
           if (callback) {
             callback(0, null);
           }
           return;
         }
 
-        debug("sendRequest: register proxy filter to " + url);
+        if (DEBUG) debug("sendRequest: register proxy filter to " + url);
         let proxyFilter = new MmsProxyFilter(url);
         gpps.registerFilter(proxyFilter, 0);
 
         let releaseMmsConnectionAndCallback = (function (httpStatus, data) {
           gpps.unregisterFilter(proxyFilter);
           // Always release the MMS network connection before callback.
           gMmsConnection.release();
           if (callback) {
@@ -435,55 +441,55 @@ XPCOMUtils.defineLazyGetter(this, "gMmsT
           } catch (e) {}
 
           if (uaProfUrl) {
             xhr.setRequestHeader(uaProfTagname, uaProfUrl);
           }
 
           // Setup event listeners
           xhr.onerror = function () {
-            debug("xhr error, response headers: " +
-                  xhr.getAllResponseHeaders());
+            if (DEBUG) debug("xhr error, response headers: " +
+                             xhr.getAllResponseHeaders());
             releaseMmsConnectionAndCallback(xhr.status, null);
           };
           xhr.onreadystatechange = function () {
             if (xhr.readyState != Ci.nsIXMLHttpRequest.DONE) {
               return;
             }
 
             let data = null;
             switch (xhr.status) {
               case HTTP_STATUS_OK: {
-                debug("xhr success, response headers: "
-                      + xhr.getAllResponseHeaders());
+                if (DEBUG) debug("xhr success, response headers: "
+                                 + xhr.getAllResponseHeaders());
 
                 let array = new Uint8Array(xhr.response);
                 if (false) {
                   for (let begin = 0; begin < array.length; begin += 20) {
                     let partial = array.subarray(begin, begin + 20);
-                    debug("res: " + JSON.stringify(partial));
+                    if (DEBUG) debug("res: " + JSON.stringify(partial));
                   }
                 }
 
                 data = {array: array, offset: 0};
                 break;
               }
               default: {
-                debug("xhr done, but status = " + xhr.status);
+                if (DEBUG) debug("xhr done, but status = " + xhr.status);
                 break;
               }
             }
 
             releaseMmsConnectionAndCallback(xhr.status, data);
           }
 
           // Send request
           xhr.send(istream);
         } catch (e) {
-          debug("xhr error, can't send: " + e.message);
+          if (DEBUG) debug("xhr error, can't send: " + e.message);
           releaseMmsConnectionAndCallback(0, null);
         }
       }).bind(this, method, url, istream, callback));
     },
 
     /**
      * Count number of recipients(to, cc, bcc fields).
      *
@@ -532,17 +538,17 @@ XPCOMUtils.defineLazyGetter(this, "gMmsT
       }
 
       let totalRecipients = 0;
       try {
         totalRecipients += this.countRecipients(msg.headers["to"]);
         totalRecipients += this.countRecipients(msg.headers["cc"]);
         totalRecipients += this.countRecipients(msg.headers["bcc"]);
       } catch (ex) {
-        debug("Exception caught : " + ex);
+        if (DEBUG) debug("Exception caught : " + ex);
         return false;
       }
 
       if (totalRecipients < 1 ||
           totalRecipients > MMS.MMS_MAX_TOTAL_RECIPIENTS) {
         return false;
       }
 
@@ -702,17 +708,17 @@ function SendTransaction(msg) {
   msg.headers["x-mms-message-class"] = "personal";
   msg.headers["x-mms-expiry"] = 7 * 24 * 60 * 60;
   msg.headers["x-mms-priority"] = 129;
   msg.headers["x-mms-read-report"] = true;
   msg.headers["x-mms-delivery-report"] = true;
 
   if (!gMmsTransactionHelper.checkMaxValuesParameters(msg)) {
     //We should notify end user that the header format is wrong.
-    debug("Check max values parameters fail.");
+    if (DEBUG) debug("Check max values parameters fail.");
     throw new Error("Check max values parameters fail.");
   }
   let messageSize = 0;
 
   if (msg.content) {
     messageSize = msg.content.length;
   } else if (msg.parts) {
     for (let i = 0; i < msg.parts.length; i++) {
@@ -748,32 +754,32 @@ function SendTransaction(msg) {
     // Assign to Content-Type
     msg.headers["content-type"] = contentType;
   }
 
   // Assign to X-Mms-Message-Size
   msg.headers["x-mms-message-size"] = messageSize;
   // TODO: bug 809832 - support customizable max incoming/outgoing message size
 
-  debug("msg: " + JSON.stringify(msg));
+  if (DEBUG) debug("msg: " + JSON.stringify(msg));
 
   this.msg = msg;
 }
 SendTransaction.prototype = {
   istreamComposed: false,
 
   /**
    * @param parts
    *        'parts' property of a parsed MMS message.
    * @param callback [optional]
    *        A callback function that takes zero argument.
    */
   loadBlobs: function loadBlobs(parts, callback) {
     let callbackIfValid = function callbackIfValid() {
-      debug("All parts loaded: " + JSON.stringify(parts));
+      if (DEBUG) debug("All parts loaded: " + JSON.stringify(parts));
       if (callback) {
         callback();
       }
     }
 
     if (!parts || !parts.length) {
       callbackIfValid();
       return;
@@ -1045,17 +1051,17 @@ MmsService.prototype = {
    * like Costcontrol, Notification and Message app... etc.
    *
    * @param aName
    *        The system message name.
    * @param aDomMessage
    *        The nsIDOMMozMmsMessage object.
    */
   broadcastMmsSystemMessage: function broadcastMmsSystemMessage(aName, aDomMessage) {
-    debug("Broadcasting the MMS system message: " + aName);
+    if (DEBUG) debug("Broadcasting the MMS system message: " + aName);
 
     // Sadly we cannot directly broadcast the aDomMessage object
     // because the system message mechamism will rewrap the object
     // based on the content window, which needs to know the properties.
     gSystemMessenger.broadcastMessage(aName, {
       type:           aDomMessage.type,
       id:             aDomMessage.id,
       delivery:       aDomMessage.delivery,
@@ -1100,17 +1106,17 @@ MmsService.prototype = {
 
   /**
    * Callback for retrieveMessage.
    */
   retrieveMessageCallback: function retrieveMessageCallback(wish,
                                                             savableMessage,
                                                             mmsStatus,
                                                             retrievedMessage) {
-    debug("retrievedMessage = " + JSON.stringify(retrievedMessage));
+    if (DEBUG) debug("retrievedMessage = " + JSON.stringify(retrievedMessage));
 
     // The absence of the field does not indicate any default
     // value. So we go check the same field in the retrieved
     // message instead.
     if (wish == null && retrievedMessage) {
       wish = retrievedMessage.headers["x-mms-delivery-report"];
     }
 
@@ -1142,17 +1148,17 @@ MmsService.prototype = {
                                               : MMS.MMS_PDU_STATUS_DEFERRED,
                                       reportAllowed);
       transaction.run();
 
       if (!success) {
         // At this point we could send a message to content to notify the user
         // that storing an incoming MMS failed, most likely due to a full disk.
         // The end user has to retrieve the MMS again.
-        debug("Could not store MMS " + domMessage.id +
+        if (DEBUG) debug("Could not store MMS " + domMessage.id +
               ", error code " + rv);
         return;
       }
 
       this.broadcastReceivedMessageEvent(domMessage);
     }).bind(this));
   },
 
@@ -1162,17 +1168,17 @@ MmsService.prototype = {
   saveReceivedMessageCallback: function saveReceivedMessageCallback(savableMessage,
                                                                     rv,
                                                                     domMessage) {
     let success = Components.isSuccessCode(rv);
     if (!success) {
       // At this point we could send a message to content to notify the
       // user that storing an incoming MMS notification indication failed,
       // ost likely due to a full disk.
-      debug("Could not store MMS " + JSON.stringify(savableMessage) +
+      if (DEBUG) debug("Could not store MMS " + JSON.stringify(savableMessage) +
             ", error code " + rv);
       // Because MMSC will resend the notification indication once we don't
       // response the notification. Hope the end user will clean some space
       // for the resent notification indication.
       return;
     }
 
     // For X-Mms-Report-Allowed and X-Mms-Transaction-Id
@@ -1223,18 +1229,18 @@ MmsService.prototype = {
    *        The parsed MMS message object.
    */
   handleNotificationIndication: function handleNotificationIndication(notification) {
     let transactionId = notification.headers["x-mms-transaction-id"];
     gMobileMessageDatabaseService.getMessageRecordByTransactionId(transactionId,
         (function (aRv, aMessageRecord) {
       if (Ci.nsIMobileMessageCallback.SUCCESS_NO_ERROR === aRv
           && aMessageRecord) {
-        debug("We already got the NotificationIndication with transactionId = "
-              + transactionId + " before.");
+        if (DEBUG) debug("We already got the NotificationIndication with transactionId = "
+                         + transactionId + " before.");
         return;
       }
 
       let savableMessage = this.convertIntermediateToSavable(notification);
 
       gMobileMessageDatabaseService
         .saveReceivedMessage(savableMessage,
                              this.saveReceivedMessageCallback.bind(this, savableMessage));
@@ -1251,17 +1257,17 @@ MmsService.prototype = {
     // TODO Bug 850140 Two things we need to do in the future:
     //
     // 1. Use gMobileMessageDatabaseService.setMessageDelivery() to reset
     // the delivery status to "success" or "error" for a specific receiver.
     //
     // 2. Fire "mms-delivery-success" or "mms-delivery-error" observer
     // topics to MobileMessageManager.
     let messageId = msg.headers["message-id"];
-    debug("handleDeliveryIndication: got delivery report for " + messageId);
+    if (DEBUG) debug("handleDeliveryIndication: got delivery report for " + messageId);
   },
 
   /**
    * A utility function to convert the MmsParameters dictionary object
    * to a database-savable message.
    *
    * @param aParams
    *        The MmsParameters dictionay object.
@@ -1273,17 +1279,17 @@ MmsService.prototype = {
    * A name for multipart object SHALL be encoded using name-parameter for Content-Type
    * header in WSP multipart headers. In decoding, name-parameter of Content-Type SHALL
    * be used if available. If name-parameter of Content-Type is not available, filename
    * parameter of Content-Disposition header SHALL be used if available. If neither
    * name-parameter of Content-Type header nor filename parameter of Content-Disposition
    * header is available, Content-Location header SHALL be used if available.
    */
   createSavableFromParams: function createSavableFromParams(aParams) {
-    debug("createSavableFromParams: aParams: " + JSON.stringify(aParams));
+    if (DEBUG) debug("createSavableFromParams: aParams: " + JSON.stringify(aParams));
     let message = {};
     let smil = aParams.smil;
 
     // |message.headers|
     let headers = message["headers"] = {};
     let receivers = aParams.receivers;
     if (receivers.length != 0) {
       let headersTo = headers["to"] = [];
@@ -1343,114 +1349,118 @@ MmsService.prototype = {
     }
 
     // The following attributes are needed for saving message into DB.
     message["type"] = "mms";
     message["deliveryStatusRequested"] = true;
     message["timestamp"] = Date.now();
     message["receivers"] = receivers;
 
-    debug("createSavableFromParams: message: " + JSON.stringify(message));
+    if (DEBUG) debug("createSavableFromParams: message: " + JSON.stringify(message));
     return message;
   },
 
   // nsIMmsService
 
   send: function send(aParams, aRequest) {
-    debug("send: aParams: " + JSON.stringify(aParams));
+    if (DEBUG) debug("send: aParams: " + JSON.stringify(aParams));
     if (aParams.receivers.length == 0) {
       aRequest.notifySendMmsMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
       return;
     }
 
     let self = this;
 
     let sendTransactionCb = function sendTransactionCb(aRecordId, aIsSentSuccess) {
-      debug("The success status of sending transaction: " + aIsSentSuccess);
+      if (DEBUG) debug("The success status of sending transaction: " + aIsSentSuccess);
       gMobileMessageDatabaseService
         .setMessageDelivery(aRecordId,
                             null,
                             aIsSentSuccess ? DELIVERY_SENT : DELIVERY_ERROR,
                             aIsSentSuccess ? null : DELIVERY_STATUS_ERROR,
                             function notifySetDeliveryResult(aRv, aDomMessage) {
-        debug("Marking the delivery state/staus is done. Notify sent or failed.");
+        if (DEBUG) debug("Marking the delivery state/staus is done. Notify sent or failed.");
         // TODO bug 832140 handle !Components.isSuccessCode(aRv)
         if (!aIsSentSuccess) {
+          if (DEBUG) debug("Send MMS fail. aParams.receivers = " +
+                           JSON.stringify(aParams.receivers));
           aRequest.notifySendMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
           Services.obs.notifyObservers(aDomMessage, kSmsFailedObserverTopic, null);
           return;
         }
 
+        if (DEBUG) debug("Send MMS successful. aParams.receivers = " +
+                         JSON.stringify(aParams.receivers));
         self.broadcastSentMessageEvent(domMessage);
         aRequest.notifyMessageSent(aDomMessage);
       });
     };
 
     let savableMessage = this.createSavableFromParams(aParams);
     gMobileMessageDatabaseService
       .saveSendingMessage(savableMessage,
                           function notifySendingResult(aRv, aDomMessage) {
-      debug("Saving sending message is done. Start to send.");
+      if (DEBUG) debug("Saving sending message is done. Start to send.");
       // TODO bug 832140 handle !Components.isSuccessCode(aRv)
       Services.obs.notifyObservers(aDomMessage, kSmsSendingObserverTopic, null);
       let sendTransaction;
       try {
         sendTransaction = new SendTransaction(savableMessage);
       } catch (e) {
-        debug("Exception: fail to create a SendTransaction instance.");
+        if (DEBUG) debug("Exception: fail to create a SendTransaction instance.");
         sendTransactionCb(aDomMessage.id, false);
         return;
       }
       sendTransaction.run(function callback(aMmsStatus, aMsg) {
         let isSentSuccess = (aMmsStatus == MMS.MMS_PDU_ERROR_OK);
-        debug("The sending status of sendTransaction.run(): " + aMmsStatus);
+        if (DEBUG) debug("The sending status of sendTransaction.run(): " + aMmsStatus);
         sendTransactionCb(aDomMessage.id, isSentSuccess);
       });
     });
   },
 
   retrieve: function retrieve(id, aRequest) {
     gMobileMessageDatabaseService.getMessageRecordById(id,
         (function notifyResult(aRv, aMessageRecord) {
       if (Ci.nsIMobileMessageCallback.SUCCESS_NO_ERROR != aRv) {
-        debug("Function getMessageRecordById() return error.");
+        if (DEBUG) debug("Function getMessageRecordById() return error.");
         aRequest.notifyGetMessageFailed(aRv);
         return;
       }
       if ("mms" != aMessageRecord.type) {
-        debug("Type of message record is not mms");
+        if (DEBUG) debug("Type of message record is not mms");
         aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
         return;
       }
       if (!aMessageRecord.headers ||
           !aMessageRecord.headers["x-mms-content-location"]) {
-        debug("Can't find mms content url in database.");
+        if (DEBUG) debug("Can't find mms content url in database.");
         aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
         return;
       }
 
       // Cite 6.2 "Multimedia Message Notification" in OMA-TS-MMS_ENC-V1_3-20110913-A:
       //   The field has only one format, relative. The recipient client calculates this
       //   length of time relative to the time it receives the notification.
       let expiriedDate = aMessageRecord.timestamp +
         aMessageRecord.headers["x-mms-expiry"] * 1000;
       if (expiriedDate < Date.now()) {
         aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.NOT_FOUND_ERROR);
-        debug("This notification indication is expired.");
+        if (DEBUG) debug("This notification indication is expired.");
         return;
       }
 
       let url =  aMessageRecord.headers["x-mms-content-location"].uri;
       // For X-Mms-Report-Allowed
       let wish = aMessageRecord.headers["x-mms-delivery-report"];
       this.retrieveMessage(url, (function responseNotify(mmsStatus, retrievedMsg) {
         // If the mmsStatus is still MMS_PDU_STATUS_DEFERRED after retry,
         // we should not store it into database.
         if (MMS.MMS_PDU_STATUS_RETRIEVED !== mmsStatus) {
-          debug("RetrieveMessage fail after retry.");
+          if (DEBUG) debug("RetrieveMessage fail after retry.");
           aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
           return;
         }
         // In OMA-TS-MMS_ENC-V1_3, Table 5 in page 25. This header field
         // (x-mms-transaction-id) SHALL be present when the MMS Proxy relay
         // seeks an acknowledgement for the MM delivered though M-Retrieve.conf
         // PDU during deferred retrieval. This transaction ID is used by the MMS
         // Client and MMS Proxy-Relay to provide linkage between the originated
@@ -1461,26 +1471,26 @@ MmsService.prototype = {
         // value. So we go checking the same field in retrieved
         // message instead.
         if (wish == null && retrievedMsg) {
           wish = retrievedMsg.headers["x-mms-delivery-report"];
         }
         let reportAllowed = this.getReportAllowed(this.confSendDeliveryReport,
                                                   wish);
 
-        debug("retrievedMsg = " + JSON.stringify(retrievedMsg));
+        if (DEBUG) debug("retrievedMsg = " + JSON.stringify(retrievedMsg));
         aMessageRecord = this.mergeRetrievalConfirmation(retrievedMsg, aMessageRecord);
         gMobileMessageDatabaseService.saveReceivedMessage(aMessageRecord,
                                                           (function (rv, domMessage) {
           let success = Components.isSuccessCode(rv);
           if (!success) {
             // At this point we could send a message to content to
             // notify the user that storing an incoming MMS failed, most
             // likely due to a full disk.
-            debug("Could not store MMS " + domMessage.id +
+            if (DEBUG) debug("Could not store MMS " + domMessage.id +
                   ", error code " + rv);
             aRequest.notifyGetMessageFailed(Ci.nsIMobileMessageCallback.INTERNAL_ERROR);
             return;
           }
           // Notifying observers a new MMS message is retrieved.
           aRequest.notifyMessageGot(domMessage);
           this.broadcastReceivedMessageEvent(domMessage);
           let transaction = new AcknowledgeTransaction(transactionId, reportAllowed);
@@ -1493,27 +1503,27 @@ MmsService.prototype = {
   // nsIWapPushApplication
 
   receiveWapPush: function receiveWapPush(array, length, offset, options) {
     let data = {array: array, offset: offset};
     let msg = MMS.PduHelper.parse(data, null);
     if (!msg) {
       return false;
     }
-    debug("receiveWapPush: msg = " + JSON.stringify(msg));
+    if (DEBUG) debug("receiveWapPush: msg = " + JSON.stringify(msg));
 
     switch (msg.type) {
       case MMS.MMS_PDU_TYPE_NOTIFICATION_IND:
         this.handleNotificationIndication(msg);
         break;
       case MMS.MMS_PDU_TYPE_DELIVERY_IND:
         this.handleDeliveryIndication(msg);
         break;
       default:
-        debug("Unsupported X-MMS-Message-Type: " + msg.type);
+        if (DEBUG) debug("Unsupported X-MMS-Message-Type: " + msg.type);
         break;
     }
   },
 };
 
 this.NSGetFactory = XPCOMUtils.generateNSGetFactory([MmsService]);
 
 let debug;
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -4182,16 +4182,19 @@ pref("wap.UAProf.tagname", "x-wap-profil
 pref("dom.mms.retrieval_mode", "manual");
 
 pref("dom.mms.sendRetryCount", 3);
 pref("dom.mms.sendRetryInterval", 300000);
 
 pref("dom.mms.retrievalRetryCount", 4);
 pref("dom.mms.retrievalRetryIntervals", "60000,300000,600000,1800000");
 
+// Debug enabler for MMS.
+pref("mms.debugging.enabled", false);
+
 // If the user puts a finger down on an element and we think the user
 // might be executing a pan gesture, how long do we wait before
 // tentatively deciding the gesture is actually a tap and activating
 // the target element?
 pref("ui.touch_activation.delay_ms", 100);
 
 // nsMemoryInfoDumper can watch a fifo in the temp directory and take various
 // actions when the fifo is written to.  Disable this in general.