summary refs log tree commit diff
path: root/pkgs/applications/networking/browsers/firefox/wrapper.nix
blob: 13becfc4f6297bf95a3b7fb7172fdb34fff29fae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
{ stdenv, lib, makeDesktopItem, makeWrapper, lndir, config
, replace, fetchurl, zip, unzip, jq, xdg-utils, writeText

## various stuff that can be plugged in
, ffmpeg, xorg, alsaLib, libpulseaudio, libcanberra-gtk2, libglvnd, libnotify
, gnome/*.gnome-shell*/
, browserpass, chrome-gnome-shell, uget-integrator, plasma5Packages, bukubrow, pipewire
, tridactyl-native
, fx_cast_bridge
, udev
, libkrb5
, libva
, mesa # firefox wants gbm for drm+dmabuf
}:

## configurability of the wrapper itself

browser:

let
  wrapper =
    { browserName ? browser.browserName or (lib.getName browser)
    , pname ? browserName
    , version ? lib.getVersion browser
    , desktopName ? # browserName with first letter capitalized
      (lib.toUpper (lib.substring 0 1 browserName) + lib.substring 1 (-1) browserName)
    , nameSuffix ? ""
    , icon ? browserName
    , extraNativeMessagingHosts ? []
    , pkcs11Modules ? []
    , forceWayland ? false
    , useGlvnd ? true
    , cfg ? config.${browserName} or {}

    ## Following options are needed for extra prefs & policies
    # For more information about anti tracking (german website)
    # visit https://wiki.kairaven.de/open/app/firefox
    , extraPrefs ? ""
    # For more information about policies visit
    # https://github.com/mozilla/policy-templates#enterprisepoliciesenabled
    , extraPolicies ? {}
    , firefoxLibName ? "firefox" # Important for tor package or the like
    , nixExtensions ? null
    }:

    assert forceWayland -> (browser ? gtk3); # Can only use the wayland backend if gtk3 is being used

    let
      ffmpegSupport = browser.ffmpegSupport or false;
      gssSupport = browser.gssSupport or false;
      alsaSupport = browser.alsaSupport or false;
      pipewireSupport = browser.pipewireSupport or false;

      nativeMessagingHosts =
        ([ ]
          ++ lib.optional (cfg.enableBrowserpass or false) (lib.getBin browserpass)
          ++ lib.optional (cfg.enableBukubrow or false) bukubrow
          ++ lib.optional (cfg.enableTridactylNative or false) tridactyl-native
          ++ lib.optional (cfg.enableGnomeExtensions or false) chrome-gnome-shell
          ++ lib.optional (cfg.enableUgetIntegrator or false) uget-integrator
          ++ lib.optional (cfg.enablePlasmaBrowserIntegration or false) plasma5Packages.plasma-browser-integration
          ++ lib.optional (cfg.enableFXCastBridge or false) fx_cast_bridge
          ++ extraNativeMessagingHosts
        );
      libs =   lib.optionals stdenv.isLinux [ udev libva mesa libnotify xorg.libXScrnSaver ]
            ++ lib.optional (pipewireSupport && lib.versionAtLeast version "83") pipewire
            ++ lib.optional ffmpegSupport ffmpeg
            ++ lib.optional gssSupport libkrb5
            ++ lib.optional useGlvnd libglvnd
            ++ lib.optionals (cfg.enableQuakeLive or false)
            (with xorg; [ stdenv.cc libX11 libXxf86dga libXxf86vm libXext libXt alsaLib zlib ])
            ++ lib.optional (config.pulseaudio or true) libpulseaudio
            ++ lib.optional alsaSupport alsaLib
            ++ pkcs11Modules;
      gtk_modules = [ libcanberra-gtk2 ];

      #########################
      #                       #
      #   EXTRA PREF CHANGES  #
      #                       #
      #########################
      policiesJson = writeText "policies.json" (builtins.toJSON enterprisePolicies);

      usesNixExtensions = nixExtensions != null;

      nameArray = builtins.map(a: a.name) (if usesNixExtensions then nixExtensions else []);

      # Check that every extension has a unqiue .name attribute
      # and an extid attribute
      extensions = if nameArray != (lib.unique nameArray) then
        throw "Firefox addon name needs to be unique"
      else builtins.map (a:
        if ! (builtins.hasAttr "extid" a) then
        throw "nixExtensions has an invalid entry. Missing extid attribute. Please use fetchfirefoxaddon"
        else
        a
      ) (if usesNixExtensions then nixExtensions else []);

      enterprisePolicies =
      {
        policies = lib.optionalAttrs usesNixExtensions  {
          DisableAppUpdate = true;
        } //
        lib.optionalAttrs usesNixExtensions {
          ExtensionSettings = {
            "*" = {
                blocked_install_message = "You can't have manual extension mixed with nix extensions";
                installation_mode = "blocked";
              };

          } // lib.foldr (e: ret:
              ret // {
                "${e.extid}" = {
                  installation_mode = "allowed";
                };
              }
            ) {} extensions;
          } // lib.optionalAttrs usesNixExtensions {
            Extensions = {
              Install = lib.foldr (e: ret:
                ret ++ [ "${e.outPath}/${e.extid}.xpi" ]
                ) [] extensions;
            };
          }
        // extraPolicies;
      };

      mozillaCfg =  writeText "mozilla.cfg" ''
        // First line must be a comment

        // Disables addon signature checking
        // to be able to install addons that do not have an extid
        // Security is maintained because only user whitelisted addons
        // with a checksum can be installed
        ${ lib.optionalString usesNixExtensions ''lockPref("xpinstall.signatures.required", false)'' };
        ${extraPrefs}
      '';

      #############################
      #                           #
      #   END EXTRA PREF CHANGES  #
      #                           #
      #############################

      # TODO: remove this after the next release (21.03)
      configPlugins = lib.filter (a: builtins.hasAttr a cfg) [
        "enableAdobeFlash"
        "enableAdobeReader"
        "enableBluejeans"
        "enableDjvu"
        "enableFriBIDPlugin"
        "enableGoogleTalkPlugin"
        "enableMPlayer"
        "enableVLC"
        "icedtea"
        "jre"
      ];
      pluginsError =
        "Your configuration mentions ${lib.concatMapStringsSep ", " (p: browserName + "." + p) configPlugins}. All plugin related options have been removed, since Firefox from version 52 onwards no longer supports npapi plugins (see https://support.mozilla.org/en-US/kb/npapi-plugins).";

    in if configPlugins != [] then throw pluginsError else
      (stdenv.mkDerivation {
      inherit pname version;

      desktopItem = makeDesktopItem {
        name = browserName;
        exec = "${browserName}${nameSuffix} %U";
        inherit icon;
        comment = "";
        desktopName = "${desktopName}${nameSuffix}${lib.optionalString forceWayland " (Wayland)"}";
        genericName = "Web Browser";
        categories = "Network;WebBrowser;";
        mimeType = lib.concatStringsSep ";" [
          "text/html"
          "text/xml"
          "application/xhtml+xml"
          "application/vnd.mozilla.xul+xml"
          "x-scheme-handler/http"
          "x-scheme-handler/https"
          "x-scheme-handler/ftp"
        ];
      };

      nativeBuildInputs = [ makeWrapper lndir ];
      buildInputs = lib.optional (browser ? gtk3) browser.gtk3;


      buildCommand = lib.optionalString stdenv.isDarwin ''
        mkdir -p $out/Applications
        cp -R --no-preserve=mode,ownership ${browser}/Applications/${browserName}.app $out/Applications
        rm -f $out${browser.execdir or "/bin"}/${browserName}
      '' + ''
        if [ ! -x "${browser}${browser.execdir or "/bin"}/${browserName}" ]
        then
            echo "cannot find executable file \`${browser}${browser.execdir or "/bin"}/${browserName}'"
            exit 1
        fi

        #########################
        #                       #
        #   EXTRA PREF CHANGES  #
        #                       #
        #########################
        # Link the runtime. The executable itself has to be copied,
        # because it will resolve paths relative to its true location.
        # Any symbolic links have to be replicated as well.
        cd "${browser}"
        find . -type d -exec mkdir -p "$out"/{} \;

        find . -type f \( -not -name "${browserName}" \) -exec ln -sT "${browser}"/{} "$out"/{} \;

        find . -type f -name "${browserName}" -print0 | while read -d $'\0' f; do
          cp -P --no-preserve=mode,ownership "${browser}/$f" "$out/$f"
          chmod a+rwx "$out/$f"
        done

        # fix links and absolute references
        cd "${browser}"

        find . -type l -print0 | while read -d $'\0' l; do
          target="$(readlink "$l" | ${replace}/bin/replace-literal -es -- "${browser}" "$out")"
          ln -sfT "$target" "$out/$l"
        done

        # This will not patch binaries, only "text" files.
        # Its there for the wrapper mostly.
        cd "$out"
        ${replace}/bin/replace-literal -esfR -- "${browser}" "$out"

        # create the wrapper

        executablePrefix="$out${browser.execdir or "/bin"}"
        executablePath="$executablePrefix/${browserName}"

        if [ ! -x "$executablePath" ]
        then
            echo "cannot find executable file \`${browser}${browser.execdir or "/bin"}/${browserName}'"
            exit 1
        fi

        if [ ! -L "$executablePath" ]
        then
          # Careful here, the file at executablePath may already be
          # a wrapper. That is why we postfix it with -old instead
          # of -wrapped.
          oldExe="$executablePrefix"/".${browserName}"-old
          mv "$executablePath" "$oldExe"
        else
          oldExe="$(readlink -v --canonicalize-existing "$executablePath")"
        fi

        if [ ! -x "${browser}${browser.execdir or "/bin"}/${browserName}" ]
        then
            echo "cannot find executable file \`${browser}${browser.execdir or "/bin"}/${browserName}'"
            exit 1
        fi

        makeWrapper "$oldExe" \
          "$out${browser.execdir or "/bin"}/${browserName}${nameSuffix}" \
            --prefix LD_LIBRARY_PATH ':' "$libs" \
            --suffix-each GTK_PATH ':' "$gtk_modules" \
            --prefix PATH ':' "${xdg-utils}/bin" \
            --suffix PATH ':' "$out${browser.execdir or "/bin"}" \
            --set MOZ_APP_LAUNCHER "${browserName}${nameSuffix}" \
            --set MOZ_SYSTEM_DIR "$out/lib/mozilla" \
            --set MOZ_LEGACY_PROFILES 1 \
            --set MOZ_ALLOW_DOWNGRADE 1 \
            ${lib.optionalString forceWayland ''
              --set MOZ_ENABLE_WAYLAND "1" \
            ''}${lib.optionalString (browser ? gtk3)
                ''--prefix XDG_DATA_DIRS : "$GSETTINGS_SCHEMAS_PATH" \
                  --suffix XDG_DATA_DIRS : '${gnome.adwaita-icon-theme}/share'
                ''
            }
        #############################
        #                           #
        #   END EXTRA PREF CHANGES  #
        #                           #
        #############################

        if [ -e "${browser}/share/icons" ]; then
            mkdir -p "$out/share"
            ln -s "${browser}/share/icons" "$out/share/icons"
        else
            for res in 16 32 48 64 128; do
            mkdir -p "$out/share/icons/hicolor/''${res}x''${res}/apps"
            icon=( "${browser}/lib/"*"/browser/chrome/icons/default/default''${res}.png" )
              if [ -e "$icon" ]; then ln -s "$icon" \
                "$out/share/icons/hicolor/''${res}x''${res}/apps/${browserName}.png"
              fi
            done
        fi

        install -D -t $out/share/applications $desktopItem/share/applications/*

        mkdir -p $out/lib/mozilla/native-messaging-hosts
        for ext in ${toString nativeMessagingHosts}; do
            ln -sLt $out/lib/mozilla/native-messaging-hosts $ext/lib/mozilla/native-messaging-hosts/*
        done

        mkdir -p $out/lib/mozilla/pkcs11-modules
        for ext in ${toString pkcs11Modules}; do
            ln -sLt $out/lib/mozilla/pkcs11-modules $ext/lib/mozilla/pkcs11-modules/*
        done


        #########################
        #                       #
        #   EXTRA PREF CHANGES  #
        #                       #
        #########################
        # user customization
        mkdir -p $out/lib/${firefoxLibName}

        # creating policies.json
        mkdir -p "$out/lib/${firefoxLibName}/distribution"

        POL_PATH="$out/lib/${firefoxLibName}/distribution/policies.json"
        rm -f "$POL_PATH"
        cat ${policiesJson} >> "$POL_PATH"

        # preparing for autoconfig
        mkdir -p "$out/lib/${firefoxLibName}/defaults/pref"

        echo 'pref("general.config.filename", "mozilla.cfg");' > "$out/lib/${firefoxLibName}/defaults/pref/autoconfig.js"
        echo 'pref("general.config.obscure_value", 0);' >> "$out/lib/${firefoxLibName}/defaults/pref/autoconfig.js"

        cat > "$out/lib/${firefoxLibName}/mozilla.cfg" < ${mozillaCfg}

        mkdir -p $out/lib/${firefoxLibName}/distribution/extensions

        #############################
        #                           #
        #   END EXTRA PREF CHANGES  #
        #                           #
        #############################
      '';

      preferLocalBuild = true;

      libs = lib.makeLibraryPath libs + ":" + lib.makeSearchPathOutput "lib" "lib64" libs;
      gtk_modules = map (x: x + x.gtkModule) gtk_modules;

      passthru = { unwrapped = browser; };

      disallowedRequisites = [ stdenv.cc ];

      meta = browser.meta // {
        description = browser.meta.description;
        hydraPlatforms = [];
        priority = (browser.meta.priority or 0) - 1; # prefer wrapper over the package
      };
    });
in lib.makeOverridable wrapper