~simpoir/landscape-client/py3fix-network-usage

« back to all changes in this revision

Viewing changes to apt-update/apt-update.c

  • Committer: Alberto Donato
  • Date: 2011-11-04 11:42:10 UTC
  • mto: This revision was merged to the branch mainline in revision 395.
  • Revision ID: alberto.donato@canonical.com-20111104114210-lezbvimeiz1i3ze5
Added apt-update wrapper.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#define _GNU_SOURCE
 
2
#include <sys/resource.h>
 
3
#include <sys/types.h>
 
4
#include <sys/stat.h>
 
5
#include <grp.h>
 
6
#include <unistd.h>
 
7
#include <stdlib.h>
 
8
#include <string.h>
 
9
#include <errno.h>
 
10
#include <stdio.h>
 
11
#include <pwd.h>
 
12
 
 
13
int main(int argc, char *argv[], char *envp[])
 
14
{
 
15
  char *apt_argv[] = {"/usr/bin/apt-get", "-q", "update", NULL};
 
16
  char *apt_envp[] = {"PATH=/bin:/usr/bin", NULL, NULL};
 
17
 
 
18
  // Set the HOME environment variable
 
19
  struct passwd *pwd = getpwuid(geteuid());
 
20
  if (!pwd) {
 
21
    fprintf(stderr, "error: Unable to find passwd entry for uid %d (%s)\n",
 
22
            geteuid(), strerror(errno));
 
23
    exit(1);
 
24
  }
 
25
  if (asprintf(&apt_envp[1], "HOME=%s", pwd->pw_dir) == -1) {
 
26
    perror("error: Unable to create HOME environment variable");
 
27
    exit(1);
 
28
  }
 
29
 
 
30
  // Drop any supplementary group
 
31
  if (setgroups(0, NULL) == -1) {
 
32
    perror("error: Unable to set supplementary groups IDs");
 
33
    exit(1);
 
34
  }
 
35
 
 
36
  // Set real/effective gid and uid
 
37
  if (setregid(pwd->pw_gid, pwd->pw_gid) == -1) {
 
38
    fprintf(stderr, "error: Unable to set real and effective gid (%s)\n",
 
39
            strerror(errno));
 
40
    exit(1);
 
41
  }
 
42
  if (setreuid(pwd->pw_uid, pwd->pw_uid) == -1) {
 
43
    perror("error: Unable to set real and effective uid");
 
44
    exit(1);
 
45
  }
 
46
 
 
47
  // Close all file descriptors except the standard ones
 
48
  struct rlimit rlp;
 
49
  if (getrlimit(RLIMIT_NOFILE, &rlp) == -1) {
 
50
    perror("error: Unable to determine file descriptor limits");
 
51
    exit(1);
 
52
  }
 
53
  int file_max;
 
54
  if (rlp.rlim_max == RLIM_INFINITY || rlp.rlim_max > 4096)
 
55
    file_max = 4096;
 
56
  else
 
57
    file_max = rlp.rlim_max;
 
58
  int file;
 
59
  for (file = 3; file < file_max; file++) {
 
60
    close(file);
 
61
  }
 
62
 
 
63
  // Set umask to 022
 
64
  umask(S_IWGRP | S_IWOTH);
 
65
 
 
66
  if (chdir("/") == -1) {
 
67
    perror("error: Unable to change working directory");
 
68
    exit(1);
 
69
  }
 
70
 
 
71
  // Run apt-get update
 
72
  execve(apt_argv[0], apt_argv, apt_envp);
 
73
  perror("error: Unable to execute apt-get");
 
74
  return 1;
 
75
}