summaryrefslogtreecommitdiff
path: root/src/pacman/util.c
blob: 4cb93156b8e9e739bb86acbf28798dfade104d05 (plain)
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/*
 *  util.c
 * 
 *  Copyright (c) 2002-2006 by Judd Vinet <jvinet@zeroflux.org>
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 
 *  USA.
 */

#include "config.h"

#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/time.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <ctype.h>
#include <dirent.h>
#include <unistd.h>
#include <limits.h>

#include <alpm.h>
#include <alpm_list.h>

/* pacman */
#include "util.h"
#include "conf.h"

extern config_t *config;

int needs_transaction()
{
  if(config->op != PM_OP_MAIN && config->op != PM_OP_QUERY && config->op != PM_OP_DEPTEST) {
    if((config->op == PM_OP_SYNC && !config->op_s_sync &&
        (config->op_s_search || config->group || config->op_q_list || config->op_q_info
         || config->flags & PM_TRANS_FLAG_PRINTURIS))
       || config->op == PM_OP_DEPTEST
       || (strcmp(alpm_option_get_root(), "/") != 0)) {
      /* special case: PM_OP_SYNC can be used w/ config->op_s_search by any user */
      /* special case: ignore root user check if -r is specified, fall back on
       * normal FS checking */
      return(0);
    } else {
      return(1);
    }
  }
  return(0);
}

/* gets the current screen column width */
int getcols()
{
  if(!isatty(1)) {
    /* We will default to 80 columns if we're not a tty
     * this seems a fairly standard file width.
     */
    return 80;
  } else {
#ifdef TIOCGSIZE
    struct ttysize win;
    if(ioctl(1, TIOCGSIZE, &win) == 0) {
      return win.ts_cols;
    }
#elif defined(TIOCGWINSZ)
    struct winsize win;
    if(ioctl(1, TIOCGWINSZ, &win) == 0) {
      return win.ws_col;
    }
#endif
    /* If we can't figure anything out, we'll just assume 80 columns */
    /* TODO any problems caused by this assumption? */
    return 80;
  }
  /* Original envvar way - prone to display issues
  const char *cenv = getenv("COLUMNS");
  if(cenv != NULL) {
    return atoi(cenv);
  }
  return -1;
  */
}

/* does the same thing as 'mkdir -p' */
int makepath(const char *path)
{
  char *orig, *str, *ptr;
  char full[PATH_MAX+1] = "";
  mode_t oldmask;

  oldmask = umask(0000);

  orig = strdup(path);
  str = orig;
  while((ptr = strsep(&str, "/"))) {
    if(strlen(ptr)) {
      struct stat buf;

      /* TODO we should use strncat */
      strcat(full, "/");
      strcat(full, ptr);
      if(stat(full, &buf)) {
        if(mkdir(full, 0755)) {
          free(orig);
          umask(oldmask);
          return(1);
        }
      }
    }
  }
  free(orig);
  umask(oldmask);
  return(0);
}

/* does the same thing as 'rm -rf' */
int rmrf(const char *path)
{
  int errflag = 0;
  struct dirent *dp;
  DIR *dirp;

  if(!unlink(path)) {
    return(0);
  } else {
    if(errno == ENOENT) {
      return(0);
    } else if(errno == EPERM) {
      /* fallthrough */
    } else if(errno == EISDIR) {
      /* fallthrough */
    } else if(errno == ENOTDIR) {
      return(1);
    } else {
      /* not a directory */
      return(1);
    }

    if((dirp = opendir(path)) == (DIR *)-1) {
      return(1);
    }
    for(dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
      if(dp->d_ino) {
        char name[PATH_MAX];
        sprintf(name, "%s/%s", path, dp->d_name);
        if(strcmp(dp->d_name, "..") && strcmp(dp->d_name, ".")) {
          errflag += rmrf(name);
        }
      }
    }
    closedir(dirp);
    if(rmdir(path)) {
      errflag++;
    }
    return(errflag);
  }
}

/* output a string, but wrap words properly with a specified indentation
 */
void indentprint(const char *str, int indent)
{
  const char *p = str;
  int cidx = indent;

  while(*p) {
    if(*p == ' ') {
      const char *next = NULL;
      int len;
      p++;
      if(p == NULL || *p == ' 'continue;
      next = strchr(p, ' ');
      if(next == NULL) {
        next = p + mbstowcs(NULL, p, 0);
      }
      len = next - p;
      if(len > (getcols() - cidx - 1)) {
        /* newline */
        int i;
        fprintf(stdout"\n");
        for(i = 0; i < indent; i++) {
          fprintf(stdout" ");
        }
        cidx = indent;
      } else {
        printf(" ");
        cidx++;
      }
    }
    fprintf(stdout"%c", *p);
    p++;
    cidx++;
  }
}

/* Convert a string to uppercase
 */
char *strtoupper(char *str)
{
  char *ptr = str;

  while(*ptr) {
    (*ptr) = toupper(*ptr);
    ptr++;
  }
  return str;
}

/* Trim whitespace and newlines from a string
 */
char *strtrim(char *str)
{
  char *pch = str;

  if(str == NULL || *str == '\0') {
    /* string is empty, so we're done. */
    return(str);
  }

  while(isspace(*pch)) {
    pch++;
  }
  if(pch != str) {
    memmove(str, pch, (strlen(pch) + 1));
  }
  
  /* check if there wasn't anything but whitespace in the string. */
  if(*str == '\0') {
    return(str);
  }

  pch = (str + (strlen(str) - 1));
  while(isspace(*pch)) {
    pch--;
  }
  *++pch = '\0';

  return(str);
}

/* Helper function for strreplace */
static void _strnadd(char **str, const char *append, unsigned int count)
{
  if(*str) {
    *str = realloc(*str, strlen(*str) + count + 1);
  } else {
    *str = calloc(sizeof(char), count + 1);
  }

  strncat(*str, append, count);
}

/* Replace all occurances of 'needle' with 'replace' in 'str', returning
 * a new string (must be free'd) */
char *strreplace(const char *str, const char *needle, const char *replace)
{
  const char *p, *q;
  p = q = str;

  char *newstr = NULL;
  unsigned int needlesz = strlen(needle),
               replacesz = strlen(replace);

  while (1) {
    q = strstr(p, needle);
    if(!q) { /* not found */
      if(*p) {
        /* add the rest of 'p' */
        _strnadd(&newstr, p, strlen(p));
      }
      break;
    } else { /* found match */
      if(q > p){
        /* add chars between this occurance and last occurance, if any */
        _strnadd(&newstr, p, q - p);
      }
      _strnadd(&newstr, replace, replacesz);
      p = q + needlesz;
    }
  }

  return newstr;
}

void list_display(const char *title, const alpm_list_t *list)
{
  const alpm_list_t *i;
  int cols, len;

  len = mbstowcs(NULL, title, 0);
  printf("%s ", title);

  if(list) {
    for(i = list, cols = len; i; i = alpm_list_next(i)) {
      char *str = alpm_list_getdata(i);
      int s = mbstowcs(NULL, str, 0) + 2;
      int maxcols = getcols();
      if(s + cols >= maxcols) {
        int i;
        cols = len;
        printf("\n");
        for (i = 0; i <= len; ++i) {
          printf(" ");
        }
      }
      printf("%s  ", str);
      cols += s;
    }
    printf("\n");
  } else {
    printf(_("None\n"));
  }
}

/* Display a list of transaction targets.
 * `pkgs` should be a list of pmsyncpkg_t's,
 * retrieved from a transaction object
 */
/* TODO move to output.c? or just combine util and output */
void display_targets(const alpm_list_t *syncpkgs)
{
  char *str;
  const alpm_list_t *i, *j;
  alpm_list_t *targets = NULL, *to_remove = NULL;
  /* TODO these are some messy variable names */
  unsigned long size = 0, isize = 0, rsize = 0, dispsize = 0;
  double mbsize = 0.0, mbisize = 0.0, mbrsize = 0.0, mbdispsize = 0.0;

  for(i = syncpkgs; i; i = alpm_list_next(i)) {
    pmsyncpkg_t *sync = alpm_list_getdata(i);
    pmpkg_t *pkg = alpm_sync_get_pkg(sync);

    /* If this sync record is a replacement, the data member contains
     * a list of packages to be removed due to the package that is being
     * installed. */
    if(alpm_sync_get_type(sync) == PM_SYNC_TYPE_REPLACE) {
      alpm_list_t *to_replace = alpm_sync_get_data(sync);
      
      for(j = to_replace; j; j = alpm_list_next(j)) {
        pmpkg_t *rp = alpm_list_getdata(j);
        const char *name = alpm_pkg_get_name(rp);

        if(!alpm_list_find_str(to_remove, name)) {
          rsize += alpm_pkg_get_isize(rp);
          to_remove = alpm_list_add(to_remove, strdup(name));
        }
      }
    }

    dispsize = alpm_pkg_get_size(pkg);
    size += dispsize;
    isize += alpm_pkg_get_isize(pkg);

    /* print the package size with the output if ShowSize option set */
    if(config->showsize) {
      /* Convert byte size to MB */
      mbdispsize = dispsize / (1024.0 * 1024.0);

      asprintf(&str, "%s-%s [%.1f MB]", alpm_pkg_get_name(pkg),
          alpm_pkg_get_version(pkg), (mbdispsize < 0.1 ? 0.1 : mbdispsize));
    } else {
      asprintf(&str, "%s-%s", alpm_pkg_get_name(pkg),
          alpm_pkg_get_version(pkg));
    }
    targets = alpm_list_add(targets, str);
  }

  /* Convert byte sizes to MB */
  mbsize = size / (1024.0 * 1024.0);
  mbisize = isize / (1024.0 * 1024.0);
  mbrsize = rsize / (1024.0 * 1024.0);

  /* start displaying information */
  printf("\n");

  if(to_remove) {
    list_display(_("Remove:"), to_remove);
    printf("\n");
    FREELIST(to_remove);
  
    /* round up if size is really small */
    if(mbrsize < 0.1) {
      mbrsize = 0.1;
    }
    printf(_("Total Removed Size:   %.2f MB\n"), mbrsize);
  }

  list_display(_("Targets:"), targets);
  printf("\n");

  /* round up if size is really small */
  if(mbsize < 0.1) {
    mbsize = 0.1;
  }
  printf(_("Total Package Size:   %.2f MB\n"), mbsize);
  
  /* TODO because all pkgs don't include isize, this is a crude hack */
  if(mbisize > mbsize) {
    /*round up if size is really small */
    if(mbisize < 0.1) {
      mbisize = 0.1;
    }
    printf(_("Total Installed Size:   %.2f MB\n"), mbisize);
  }

  FREELIST(targets);
}

/* presents a prompt and gets a Y/N answer */
/* TODO there must be a better way */
int yesno(char *fmt, ...)
{
  char response[32];
  va_list args;

  if(config->noconfirm) {
    return(1);
  }

  va_start(args, fmt);
  /* Use stderr so questions are always displayed when redirecting output */
  vfprintf(stderr, fmt, args);
  va_end(args);

  if(fgets(response, 32stdin)) {
    if(strlen(response) != 0) {
      strtrim(response);
    }

    if(!strcasecmp(response, _("Y")) || !strcasecmp(response, _("YES")) || strlen(response) == 0) {
      return(1);
    }
  }
  return(0);
}

int pm_printf(pmloglevel_t level, const char *format, ...)
{
  int ret;
  va_list args;

  /* print the message using va_arg list */
  va_start(args, format);
  ret = pm_vfprintf(stdout, level, format, args);
  va_end(args);

  return(ret);
}

int pm_fprintf(FILE *stream, pmloglevel_t level, const char *format, ...)
{
  int ret;
  va_list args;

  /* print the message using va_arg list */
  va_start(args, format);
  ret = pm_vfprintf(stream, level, format, args);
  va_end(args);

  return(ret);
}

int pm_vfprintf(FILE *stream, pmloglevel_t level, const char *format, va_list args)
{
  int ret = 0;

  /* if current logmask does not overlap with level, do not print msg */
  if(!(config->logmask & level)) {
    return ret;
  }

#if defined(PACMAN_DEBUG)
  /* If debug is on, we'll timestamp the output */
  if(config->logmask & PM_LOG_DEBUG) {
    time_t t;
    struct tm *tmp;
    char timestr[10] = {0};

    t = time(NULL);
    tmp = localtime(&t);
    strftime(timestr, 9"%H:%M:%S", tmp);
    timestr[8] = '\0';

    printf("[%s] ", timestr);
  }
#endif

  /* print a prefix to the message */
  switch(level) {
    case PM_LOG_DEBUG:
      fprintf(stream, _("debug: "));
      break;
    case PM_LOG_ERROR:
      fprintf(stream, _("error: "));
      break;
    case PM_LOG_WARNING:
      fprintf(stream, _("warning: "));
      break;
    case PM_LOG_FUNCTION:
      /* TODO we should increase the indent level when this occurs so we can see
       * program flow easier.  It'll be fun */
      fprintf(stream, _("function: "));
      break;
    default:
      break;
  }

  /* print the message using va_arg list */
  ret = vfprintf(stream, format, args);
  return(ret);
}

/* vim: set ts=2 sw=2 noet: */