char const* optarg;
int const ind = tr_optind;
- while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+ while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
{
if (c == 'g')
{
tr_sessionLoadSettings(&settings, configDir, MY_CONFIG_NAME);
/* the command line overrides defaults */
- if (parseCommandLine(&settings, argc, (char const**)argv))
+ if (parseCommandLine(&settings, argc, (char const**)argv) != 0)
{
return EXIT_FAILURE;
}
}
/* Check the options for validity */
- if (!torrentPath)
+ if (torrentPath == NULL)
{
fprintf(stderr, "No torrent specified!\n");
return EXIT_FAILURE;
tor = tr_torrentNew(ctor, NULL, NULL);
tr_ctorFree(ctor);
- if (!tor)
+ if (tor == NULL)
{
fprintf(stderr, "Failed opening torrent file `%s'\n", torrentPath);
tr_sessionClose(h);
int c;
char const* optarg;
- while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+ while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
{
switch (c)
{
char const* optarg;
int const ind = tr_optind;
- while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+ while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
{
if (c == 'g')
{
tr_ctor* ctor = tr_ctorNew(session);
int err = tr_ctorSetMetainfoFromFile(ctor, filename);
- if (!err)
+ if (err == 0)
{
tr_torrentNew(ctor, &err, NULL);
char timestr[64];
tr_logGetTimeStr(timestr, sizeof(timestr));
- if (name)
+ if (name != NULL)
{
tr_sys_file_write_fmt(logfile, "[%s] %s %s (%s:%d)" TR_NATIVE_EOL_STR, NULL, timestr, name, message, file, line);
}
}
#ifdef HAVE_SYSLOG
+
else /* daemon... write to syslog */
{
int priority;
break;
}
- if (name)
+ if (name != NULL)
{
syslog(priority, "%s %s (%s:%d)", name, message, file, line);
}
}
#else
+
(void)level;
+
#endif
}
tr_optind = 1;
- while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+ while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
{
switch (c)
{
static void daemon_reconfigure(void* arg UNUSED)
{
- if (!mySession)
+ if (mySession == NULL)
{
tr_logAddInfo("Deferring reload until session is fully started.");
seenHUP = true;
pid_filename = NULL;
tr_variantDictFindStr(settings, key_pidfile, &pid_filename, NULL);
- if (pid_filename && *pid_filename)
+ if (pid_filename != NULL && *pid_filename != '\0')
{
tr_error* error = NULL;
tr_sys_file_t fp = tr_sys_file_open(pid_filename, TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, 0666, &error);
tr_watchdir_free(watchdir);
- if (status_ev)
+ if (status_ev != NULL)
{
event_del(status_ev);
event_free(status_ev);
tr_snprintf(s, sizeof(s), "%d %s", seconds, seconds == 1 ? "second" : "seconds");
tr_snprintf(t, sizeof(t), "%d %s", total_seconds, total_seconds == 1 ? "second" : "seconds");
- if (days)
+ if (days != 0)
{
- if (days >= 4 || !hours)
+ if (days >= 4 || hours == 0)
{
tr_strlcpy(b, d, sizeof(b));
}
tr_snprintf(b, sizeof(b), "%s, %s", d, h);
}
}
- else if (hours)
+ else if (hours != 0)
{
- if (hours >= 4 || !minutes)
+ if (hours >= 4 || minutes == 0)
{
tr_strlcpy(b, h, sizeof(b));
}
tr_snprintf(b, sizeof(b), "%s, %s", h, m);
}
}
- else if (minutes)
+ else if (minutes != 0)
{
- if (minutes >= 4 || !seconds)
+ if (minutes >= 4 || seconds == 0)
{
tr_strlcpy(b, m, sizeof(b));
}
static char* strlmem(char* buf, int64_t bytes, size_t buflen)
{
- if (!bytes)
+ if (bytes == 0)
{
tr_strlcpy(buf, "None", buflen);
}
char* end = NULL;
long const num = strtol(arg, &end, 10);
- if (*end)
+ if (*end != '\0')
{
fprintf(stderr, "Not a number: \"%s\"\n", arg);
showUsage();
char* b64 = NULL;
uint8_t* buf = tr_loadFile(filename, &len, NULL);
- if (buf)
+ if (buf != NULL)
{
b64 = tr_base64_encode(buf, len, NULL);
tr_free(buf);
static void addIdArg(tr_variant* args, char const* id, char const* fallback)
{
- if (!id || !*id)
+ if (id == NULL || *id == '\0')
{
id = fallback;
- if (!id || !*id)
+ if (id == NULL || *id == '\0')
{
fprintf(stderr, "No torrent specified! Please use the -t option first.\n");
id = "-1"; /* no torrent will have this ID, so will act as a no-op */
else if (strcmp(id, "all") != 0)
{
char const* pch;
- bool isList = strchr(id, ',') || strchr(id, '-');
+ bool isList = strchr(id, ',') != NULL || strchr(id, '-') != NULL;
bool isNum = true;
- for (pch = id; isNum && *pch; ++pch)
+ for (pch = id; isNum && *pch != '\0'; ++pch)
{
if (!isdigit(*pch))
{
int time;
bool success = false;
- if (arg && (strlen(arg) == 4))
+ if (arg != NULL && strlen(arg) == 4)
{
char const hh[3] = { arg[0], arg[1], '\0' };
char const mm[3] = { arg[2], arg[3], '\0' };
{
int days = 0;
- if (arg)
+ if (arg != NULL)
{
int i;
int valueCount;
tr_free(values);
}
- if (days)
+ if (days != 0)
{
tr_variantDictAddInt(args, key, days);
}
{
tr_variant* files = tr_variantDictAddList(args, key, 100);
- if (!*arg)
+ if (*arg == '\0')
{
fprintf(stderr, "No files specified!\n");
arg = "-1"; /* no file will have this index, so should be a no-op */
tr_variantDictFindInt(t, TR_KEY_peersGettingFromUs, &fromUs);
tr_variantDictFindInt(t, TR_KEY_peersSendingToUs, &toUs);
- if (fromUs && toUs)
+ if (fromUs != 0 && toUs != 0)
{
tr_strlcpy(buf, "Up & Down", buflen);
}
- else if (toUs)
+ else if (toUs != 0)
{
tr_strlcpy(buf, "Downloading", buflen);
}
- else if (fromUs)
+ else if (fromUs != 0)
{
int64_t leftUntilDone = 0;
tr_variantDictFindInt(t, TR_KEY_leftUntilDone, &leftUntilDone);
{
tr_variant* args, * torrents;
- if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)) && (tr_variantDictFindList(args, TR_KEY_torrents, &torrents)))
+ if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &torrents))
{
int ti, tCount;
printf(" Corrupt DL: %s\n", buf);
}
- if (tr_variantDictFindStr(t, TR_KEY_errorString, &str, NULL) && str && *str && tr_variantDictFindInt(t, TR_KEY_error, &i) && i)
+ if (tr_variantDictFindStr(t, TR_KEY_errorString, &str, NULL) && str != NULL && *str != '\0' &&
+ tr_variantDictFindInt(t, TR_KEY_error, &i) && i != 0)
{
switch (i)
{
printf("HISTORY\n");
- if (tr_variantDictFindInt(t, TR_KEY_addedDate, &i) && i)
+ if (tr_variantDictFindInt(t, TR_KEY_addedDate, &i) && i != 0)
{
time_t const tt = i;
printf(" Date added: %s", ctime(&tt));
}
- if (tr_variantDictFindInt(t, TR_KEY_doneDate, &i) && i)
+ if (tr_variantDictFindInt(t, TR_KEY_doneDate, &i) && i != 0)
{
time_t const tt = i;
printf(" Date finished: %s", ctime(&tt));
}
- if (tr_variantDictFindInt(t, TR_KEY_startDate, &i) && i)
+ if (tr_variantDictFindInt(t, TR_KEY_startDate, &i) && i != 0)
{
time_t const tt = i;
printf(" Date started: %s", ctime(&tt));
}
- if (tr_variantDictFindInt(t, TR_KEY_activityDate, &i) && i)
+ if (tr_variantDictFindInt(t, TR_KEY_activityDate, &i) && i != 0)
{
time_t const tt = i;
printf(" Latest activity: %s", ctime(&tt));
}
- if (tr_variantDictFindInt(t, TR_KEY_secondsDownloading, &i) && (i > 0))
+ if (tr_variantDictFindInt(t, TR_KEY_secondsDownloading, &i) && i > 0)
{
printf(" Downloading Time: %s\n", tr_strltime(buf, i, sizeof(buf)));
}
- if (tr_variantDictFindInt(t, TR_KEY_secondsSeeding, &i) && (i > 0))
+ if (tr_variantDictFindInt(t, TR_KEY_secondsSeeding, &i) && i > 0)
{
printf(" Seeding Time: %s\n", tr_strltime(buf, i, sizeof(buf)));
}
printf("ORIGINS\n");
- if (tr_variantDictFindInt(t, TR_KEY_dateCreated, &i) && i)
+ if (tr_variantDictFindInt(t, TR_KEY_dateCreated, &i) && i != 0)
{
time_t const tt = i;
printf(" Date created: %s", ctime(&tt));
printf(" Public torrent: %s\n", (boolVal ? "No" : "Yes"));
}
- if (tr_variantDictFindStr(t, TR_KEY_comment, &str, NULL) && str && *str)
+ if (tr_variantDictFindStr(t, TR_KEY_comment, &str, NULL) && str != NULL && *str != '\0')
{
printf(" Comment: %s\n", str);
}
- if (tr_variantDictFindStr(t, TR_KEY_creator, &str, NULL) && str && *str)
+ if (tr_variantDictFindStr(t, TR_KEY_creator, &str, NULL) && str != NULL && *str != '\0')
{
printf(" Creator: %s\n", str);
}
{
tr_variant* args, * torrents;
- if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)) && (tr_variantDictFindList(args, TR_KEY_torrents, &torrents)))
+ if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &torrents))
{
int i, in;
break;
}
- printf("%3d: %3.0f%% %-8s %-3s %9s %s\n", j, floor(100.0 * percent), pristr, (wanted ? "Yes" : "No"), sizestr, filename);
+ printf("%3d: %3.0f%% %-8s %-3s %9s %s\n", j, floor(100.0 * percent), pristr, wanted ? "Yes" : "No",
+ sizestr, filename);
}
}
}
printf(" ");
- if (!(i % 64))
+ if (i % 64 == 0)
{
printf("\n ");
}
if (tr_variantDictFindBool(args, TR_KEY_port_is_open, &boolVal))
{
- printf("Port is open: %s\n", (boolVal ? "Yes" : "No"));
+ printf("Port is open: %s\n", boolVal ? "Yes" : "No");
}
}
}
{
tr_variant* args, * list;
- if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)) && (tr_variantDictFindList(args, TR_KEY_torrents, &list)))
+ if (tr_variantDictFindDict(top, TR_KEY_arguments, &args) && tr_variantDictFindList(args, TR_KEY_torrents, &list))
{
int i, n;
int64_t total_size = 0;
int64_t error;
char errorMark;
- if (sizeWhenDone)
+ if (sizeWhenDone != 0)
{
tr_snprintf(doneStr, sizeof(doneStr), "%d%%", (int)(100.0 * (sizeWhenDone - leftUntilDone) / sizeWhenDone));
}
strlsize(haveStr, sizeWhenDone - leftUntilDone, sizeof(haveStr));
- if (leftUntilDone || eta != -1)
+ if (leftUntilDone != 0 || eta != -1)
{
etaToString(etaStr, sizeof(etaStr), eta);
}
char buf[512];
tr_variant* t;
- for (i = 0; ((t = tr_variantListChild(trackerStats, i))); ++i)
+ for (i = 0; (t = tr_variantListChild(trackerStats, i)) != NULL; ++i)
{
int64_t downloadCount;
bool hasAnnounced;
{
tr_variant* args;
- if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)))
+ if (tr_variantDictFindDict(top, TR_KEY_arguments, &args))
{
int64_t i;
char buf[64];
if (tr_variantDictFindBool(args, TR_KEY_port_forwarding_enabled, &boolVal))
{
- printf(" Portforwarding enabled: %s\n", (boolVal ? "Yes" : "No"));
+ printf(" Portforwarding enabled: %s\n", boolVal ? "Yes" : "No");
}
if (tr_variantDictFindBool(args, TR_KEY_utp_enabled, &boolVal))
if (tr_variantDictFindBool(args, TR_KEY_dht_enabled, &boolVal))
{
- printf(" Distributed hash table enabled: %s\n", (boolVal ? "Yes" : "No"));
+ printf(" Distributed hash table enabled: %s\n", boolVal ? "Yes" : "No");
}
if (tr_variantDictFindBool(args, TR_KEY_lpd_enabled, &boolVal))
{
- printf(" Local peer discovery enabled: %s\n", (boolVal ? "Yes" : "No"));
+ printf(" Local peer discovery enabled: %s\n", boolVal ? "Yes" : "No");
}
if (tr_variantDictFindBool(args, TR_KEY_pex_enabled, &boolVal))
{
- printf(" Peer exchange allowed: %s\n", (boolVal ? "Yes" : "No"));
+ printf(" Peer exchange allowed: %s\n", boolVal ? "Yes" : "No");
}
if (tr_variantDictFindStr(args, TR_KEY_encryption, &str, NULL))
printf(" Turtle schedule: %02d:%02d - %02d:%02d ", (int)(altBegin / 60), (int)(altBegin % 60), (int)(altEnd / 60),
(int)(altEnd % 60));
- if (altDay & TR_SCHED_SUN)
+ if ((altDay & TR_SCHED_SUN) != 0)
{
printf("Sun ");
}
- if (altDay & TR_SCHED_MON)
+ if ((altDay & TR_SCHED_MON) != 0)
{
printf("Mon ");
}
- if (altDay & TR_SCHED_TUES)
+ if ((altDay & TR_SCHED_TUES) != 0)
{
printf("Tue ");
}
- if (altDay & TR_SCHED_WED)
+ if ((altDay & TR_SCHED_WED) != 0)
{
printf("Wed ");
}
- if (altDay & TR_SCHED_THURS)
+ if ((altDay & TR_SCHED_THURS) != 0)
{
printf("Thu ");
}
- if (altDay & TR_SCHED_FRI)
+ if ((altDay & TR_SCHED_FRI) != 0)
{
printf("Fri ");
}
- if (altDay & TR_SCHED_SAT)
+ if ((altDay & TR_SCHED_SAT) != 0)
{
printf("Sat ");
}
if (tr_variantDictFindBool(args, TR_KEY_start_added_torrents, &boolVal))
{
- printf(" Autostart added torrents: %s\n", (boolVal ? "Yes" : "No"));
+ printf(" Autostart added torrents: %s\n", boolVal ? "Yes" : "No");
}
if (tr_variantDictFindBool(args, TR_KEY_trash_original_torrent_files, &boolVal))
{
- printf(" Delete automatically added torrents: %s\n", (boolVal ? "Yes" : "No"));
+ printf(" Delete automatically added torrents: %s\n", boolVal ? "Yes" : "No");
}
}
}
{
tr_variant* args, * d;
- if ((tr_variantDictFindDict(top, TR_KEY_arguments, &args)))
+ if (tr_variantDictFindDict(top, TR_KEY_arguments, &args))
{
char buf[512];
int64_t up, down, secs, sessions;
fprintf(stderr, "got response (len %d):\n--------\n%*.*s\n--------\n", (int)len, (int)len, (int)len, (char const*)response);
}
- if (tr_variantFromJson(&top, response, len))
+ if (tr_variantFromJson(&top, response, len) != 0)
{
tr_logAddNamedError(MY_NAME, "Unable to parse response \"%*.*s\"", (int)len, (int)len, (char const*)response);
status |= EXIT_FAILURE;
curl_easy_setopt(curl, CURLOPT_VERBOSE, debug);
curl_easy_setopt(curl, CURLOPT_ENCODING, ""); /* "" tells curl to fill in the blanks with what it was compiled to support */
- if (netrc)
+ if (netrc != NULL)
{
curl_easy_setopt(curl, CURLOPT_NETRC_FILE, netrc);
}
- if (auth)
+ if (auth != NULL)
{
curl_easy_setopt(curl, CURLOPT_USERPWD, auth);
}
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); /* since most certs will be self-signed, do not verify against CA */
}
- if (sessionId)
+ if (sessionId != NULL)
{
char* h = tr_strdup_printf("%s: %s", TR_RPC_SESSION_ID_HEADER, sessionId);
struct curl_slist* custom_headers = curl_slist_append(NULL, h);
fprintf(stderr, "posting:\n--------\n%s\n--------\n", json);
}
- if ((res = curl_easy_perform(curl)))
+ if ((res = curl_easy_perform(curl)) != CURLE_OK)
{
tr_logAddNamedError(MY_NAME, " (%s) %s", rpcurl_http, curl_easy_strerror(res));
status |= EXIT_FAILURE;
tr_free(json);
evbuffer_free(buf);
- if (curl != 0)
+ if (curl != NULL)
{
curl_easy_cleanup(curl);
}
if (benc != NULL)
{
tr_variantFree(*benc);
- *benc = 0;
+ *benc = NULL;
}
return status;
{
tr_variant* args;
- if (*sset)
+ if (*sset != NULL)
{
args = tr_variantDictFind(*sset, ARGUMENTS);
}
{
tr_variant* args;
- if (*tset)
+ if (*tset != NULL)
{
args = tr_variantDictFind(*tset, ARGUMENTS);
}
int c;
int status = EXIT_SUCCESS;
char const* optarg;
- tr_variant* sset = 0;
- tr_variant* tset = 0;
- tr_variant* tadd = 0;
+ tr_variant* sset = NULL;
+ tr_variant* tset = NULL;
+ tr_variant* tadd = NULL;
*id = '\0';
- while ((c = tr_getopt(getUsage(), argc, argv, opts, &optarg)))
+ while ((c = tr_getopt(getUsage(), argc, argv, opts, &optarg)) != TR_OPT_DONE)
{
int const stepMode = getOptMode(c);
- if (!stepMode) /* meta commands */
+ if (stepMode == 0) /* meta commands */
{
switch (c)
{
case 'a': /* add torrent */
- if (sset != 0)
+ if (sset != NULL)
{
status |= flush(rpcurl, &sset);
}
- if (tadd != 0)
+ if (tadd != NULL)
{
status |= flush(rpcurl, &tadd);
}
- if (tset != 0)
+ if (tset != NULL)
{
addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
status |= flush(rpcurl, &tset);
break;
case 't': /* set current torrent */
- if (tadd != 0)
+ if (tadd != NULL)
{
status |= flush(rpcurl, &tadd);
}
- if (tset != 0)
+ if (tset != NULL)
{
addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
status |= flush(rpcurl, &tset);
break;
case TR_OPT_UNK:
- if (tadd)
+ if (tadd != NULL)
{
tr_variant* args = tr_variantDictFind(tadd, ARGUMENTS);
char* tmp = getEncodedMetainfo(optarg);
- if (tmp)
+ if (tmp != NULL)
{
tr_variantDictAddStr(args, TR_KEY_metainfo, tmp);
}
args = tr_variantDictAddDict(top, ARGUMENTS, 0);
fields = tr_variantDictAddList(args, TR_KEY_fields, 0);
- if (tset != 0)
+ if (tset != NULL)
{
addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
status |= flush(rpcurl, &tset);
}
else if (stepMode == (MODE_SESSION_SET | MODE_TORRENT_SET))
{
- tr_variant* targs = 0;
- tr_variant* sargs = 0;
+ tr_variant* targs = NULL;
+ tr_variant* sargs = NULL;
- if (*id)
+ if (*id != '\0')
{
targs = ensure_tset(&tset);
}
switch (c)
{
case 'd':
- if (targs)
+ if (targs != NULL)
{
tr_variantDictAddInt(targs, TR_KEY_downloadLimit, numarg(optarg));
tr_variantDictAddBool(targs, TR_KEY_downloadLimited, true);
break;
case 'D':
- if (targs)
+ if (targs != NULL)
{
tr_variantDictAddBool(targs, TR_KEY_downloadLimited, false);
}
break;
case 'u':
- if (targs)
+ if (targs != NULL)
{
tr_variantDictAddInt(targs, TR_KEY_uploadLimit, numarg(optarg));
tr_variantDictAddBool(targs, TR_KEY_uploadLimited, true);
break;
case 'U':
- if (targs)
+ if (targs != NULL)
{
tr_variantDictAddBool(targs, TR_KEY_uploadLimited, false);
}
break;
case 930:
- if (targs)
+ if (targs != NULL)
{
tr_variantDictAddInt(targs, TR_KEY_peer_limit, atoi(optarg));
}
{
tr_variant* args;
- if (tadd)
+ if (tadd != NULL)
{
args = tr_variantDictFind(tadd, ARGUMENTS);
}
}
else if (c == 961) /* set location */
{
- if (tadd)
+ if (tadd != NULL)
{
tr_variant* args = tr_variantDictFind(tadd, ARGUMENTS);
tr_variantDictAddStr(args, TR_KEY_download_dir, optarg);
case 's': /* start */
{
- if (tadd)
+ if (tadd != NULL)
{
tr_variantDictAddBool(tr_variantDictFind(tadd, TR_KEY_arguments), TR_KEY_paused, false);
}
case 'S': /* stop */
{
- if (tadd)
+ if (tadd != NULL)
{
tr_variantDictAddBool(tr_variantDictFind(tadd, TR_KEY_arguments), TR_KEY_paused, true);
}
{
tr_variant* top;
- if (tset != 0)
+ if (tset != NULL)
{
addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
status |= flush(rpcurl, &tset);
{
tr_variant* top;
- if (tset != 0)
+ if (tset != NULL)
{
addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
status |= flush(rpcurl, &tset);
}
}
- if (tadd != 0)
+ if (tadd != NULL)
{
status |= flush(rpcurl, &tadd);
}
- if (tset != 0)
+ if (tset != NULL)
{
addIdArg(tr_variantDictFind(tset, ARGUMENTS), id, NULL);
status |= flush(rpcurl, &tset);
}
- if (sset != 0)
+ if (sset != NULL)
{
status |= flush(rpcurl, &sset);
}
UseSSL = true;
*rpcurl = tr_strdup_printf("%s/rpc/", s + 8);
}
- else if (delim) /* user passed in both host and port */
+ else if (delim != NULL) /* user passed in both host and port */
{
*host = tr_strndup(s, delim - s);
*port = atoi(delim + 1);
char* end;
int const i = strtol(s, &end, 10);
- if (!*end) /* user passed in a port */
+ if (*end == '\0') /* user passed in a port */
{
*port = i;
}
GtkSpinButton* spin = GTK_SPIN_BUTTON(w);
double const currentValue = gtk_spin_button_get_value(spin);
- if (((int)(currentValue * 100) != (int)(value * 100)))
+ if ((int)(currentValue * 100) != (int)(value * 100))
{
g_signal_handler_block(spin, tag);
gtk_spin_button_set_value(spin, value);
***/
/* honor_limits_check */
- if (n)
+ if (n != 0)
{
int i;
bool const baseline = tr_torrentUsesSessionLimits(torrents[0]);
}
/* down_limited_check */
- if (n)
+ if (n != 0)
{
int i;
bool const baseline = tr_torrentUsesSpeedLimit(torrents[0], TR_DOWN);
}
/* down_limit_spin */
- if (n)
+ if (n != 0)
{
int i;
- unsigned const int baseline = tr_torrentGetSpeedLimit_KBps(torrents[0], TR_DOWN);
+ unsigned int const baseline = tr_torrentGetSpeedLimit_KBps(torrents[0], TR_DOWN);
for (i = 1; i < n; ++i)
{
- if (baseline != (tr_torrentGetSpeedLimit_KBps(torrents[i], TR_DOWN)))
+ if (baseline != tr_torrentGetSpeedLimit_KBps(torrents[i], TR_DOWN))
{
break;
}
}
/* up_limited_check */
- if (n)
+ if (n != 0)
{
int i;
bool const baseline = tr_torrentUsesSpeedLimit(torrents[0], TR_UP);
}
/* up_limit_sping */
- if (n)
+ if (n != 0)
{
int i;
unsigned int const baseline = tr_torrentGetSpeedLimit_KBps(torrents[0], TR_UP);
for (i = 1; i < n; ++i)
{
- if (baseline != (tr_torrentGetSpeedLimit_KBps(torrents[i], TR_UP)))
+ if (baseline != tr_torrentGetSpeedLimit_KBps(torrents[i], TR_UP))
{
break;
}
}
/* bandwidth_combo */
- if (n)
+ if (n != 0)
{
int i;
int const baseline = tr_torrentGetPriority(torrents[0]);
}
/* ratio_combo */
- if (n)
+ if (n != 0)
{
int i;
int const baseline = tr_torrentGetRatioMode(torrents[0]);
}
/* ratio_spin */
- if (n)
+ if (n != 0)
{
double const baseline = tr_torrentGetRatioLimit(torrents[0]);
set_double_spin_if_different(di->ratio_spin, di->ratio_spin_tag, baseline);
}
/* idle_combo */
- if (n)
+ if (n != 0)
{
int i;
int const baseline = tr_torrentGetIdleMode(torrents[0]);
}
/* idle_spin */
- if (n)
+ if (n != 0)
{
int const baseline = tr_torrentGetIdleLimit(torrents[0]);
set_int_spin_if_different(di->idle_spin, di->idle_spin_tag, baseline);
}
/* max_peers_spin */
- if (n)
+ if (n != 0)
{
int const baseline = tr_torrentGetPeerLimit(torrents[0]);
set_int_spin_if_different(di->max_peers_spin, di->max_peers_spin_tag, baseline);
tr_variantDictAddBool(args, key, value);
ids = tr_variantDictAddList(args, TR_KEY_ids, g_slist_length(di->ids));
- for (l = di->ids; l; l = l->next)
+ for (l = di->ids; l != NULL; l = l->next)
{
tr_variantListAddInt(ids, GPOINTER_TO_INT(l->data));
}
tr_variantDictAddInt(args, key, value);
ids = tr_variantDictAddList(args, TR_KEY_ids, g_slist_length(di->ids));
- for (l = di->ids; l; l = l->next)
+ for (l = di->ids; l != NULL; l = l->next)
{
tr_variantListAddInt(ids, GPOINTER_TO_INT(l->data));
}
tr_variantDictAddReal(args, key, value);
ids = tr_variantDictAddList(args, TR_KEY_ids, g_slist_length(di->ids));
- for (l = di->ids; l; l = l->next)
+ for (l = di->ids; l != NULL; l = l->next)
{
tr_variantListAddInt(ids, GPOINTER_TO_INT(l->data));
}
char buf[64];
struct tm tm;
- if (!t)
+ if (t == 0)
{
return g_strdup(_("N/A"));
}
mixed_date |= (date != infos[i]->dateCreated);
}
- gboolean const empty_creator = !*creator;
+ gboolean const empty_creator = *creator == '\0';
gboolean const empty_date = date == 0;
if (mixed_date || mixed_creator)
if (!stats[i]->finished)
{
- allFinished = FALSE;
+ allFinished = false;
}
}
{
str = mixed;
}
- else if ((baseline <= 0) || (stats[0]->activity == TR_STATUS_STOPPED))
+ else if (baseline <= 0 || stats[0]->activity == TR_STATUS_STOPPED)
{
str = stateString;
}
size += infos[i]->totalSize;
pieces += infos[i]->pieceCount;
- if (!pieceSize)
+ if (pieceSize == 0)
{
pieceSize = infos[i]->pieceSize;
}
tr_strlsize(sizebuf, size, sizeof(sizebuf));
- if (!size)
+ if (size == 0)
{
str = "";
}
{
char piecebuf[128];
tr_formatter_mem_B(piecebuf, pieceSize, sizeof(piecebuf));
- g_snprintf(buf, sizeof(buf), ngettext("%1$s (%2$'d piece @ %3$s)", "%1$s (%2$'d pieces @ %3$s)",
- pieces), sizebuf, pieces, piecebuf);
+ g_snprintf(buf, sizeof(buf), ngettext("%1$s (%2$'d piece @ %3$s)", "%1$s (%2$'d pieces @ %3$s)", pieces), sizebuf,
+ pieces, piecebuf);
str = buf;
}
else
tr_strlsize(total, haveUnchecked + haveValid, sizeof(total));
tr_strlsize(unver, haveUnchecked, sizeof(unver));
- if (!haveUnchecked && !leftUntilDone)
+ if (haveUnchecked == 0 && leftUntilDone == 0)
{
g_snprintf(buf, sizeof(buf), _("%1$s (%2$s%%)"), total, buf2);
}
- else if (!haveUnchecked)
+ else if (haveUnchecked == 0)
{
g_snprintf(buf, sizeof(buf), _("%1$s (%2$s%% of %3$s%% Available)"), total, buf2, avail);
}
tr_strlsize(dbuf, d, sizeof(dbuf));
tr_strlsize(fbuf, f, sizeof(fbuf));
- if (f)
+ if (f != 0)
{
g_snprintf(buf, sizeof(buf), _("%1$s (+%2$s corrupt)"), dbuf, fbuf);
}
}
}
- if (!str || !*str)
+ if (str == NULL || *str == '\0')
{
str = _("No errors");
}
g_string_append_printf(gstr, "<b>%s</b>\n%s\n \n", markup, addr);
g_free(markup);
- for (pch = flagstr; pch && *pch; ++pch)
+ for (pch = flagstr; pch != NULL && *pch != '\0'; ++pch)
{
char const* s = NULL;
break;
}
- if (s)
+ if (s != NULL)
{
g_string_append_printf(gstr, "%c: %s\n", *pch, s);
}
}
- if (gstr->len) /* remove the last linefeed */
+ if (gstr->len != 0) /* remove the last linefeed */
{
g_string_set_size(gstr, gstr->len - 1);
}
view_columns[n++] = PEER_COL_CLIENT;
/* remove any existing columns */
- while ((c = gtk_tree_view_get_column(peer_view, 0)))
+ while ((c = gtk_tree_view_get_column(peer_view, 0)) != NULL)
{
gtk_tree_view_remove_column(peer_view, c);
}
{
g_string_append(gstr, st->isBackup ? "<i>" : "<b>");
- if (key)
+ if (key != NULL)
{
str = g_markup_printf_escaped("%s - %s", st->host, key);
}
char* url = g_strdup(gtk_entry_get_text(GTK_ENTRY(e)));
g_strstrip(url);
- if (url && *url)
+ if (url != NULL && *url != '\0')
{
if (tr_urlIsValidTracker(url))
{
(GDestroyNotify)gtk_tree_row_reference_free);
di->trackers_filtered = gtk_tree_model_filter_new(GTK_TREE_MODEL(di->tracker_store), NULL);
- gtk_tree_model_filter_set_visible_func(GTK_TREE_MODEL_FILTER(di->trackers_filtered),
- trackerVisibleFunc, di, NULL);
+ gtk_tree_model_filter_set_visible_func(GTK_TREE_MODEL_FILTER(di->trackers_filtered), trackerVisibleFunc, di, NULL);
hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, GUI_PAD_BIG);
int incomplete = 0;
int const count = g_slist_length(torrent_ids);
- if (!count)
+ if (count == 0)
{
return;
}
tr_torrent* tor = gtr_core_find_torrent(core, id);
tr_stat const* stat = tr_torrentStat(tor);
- if (stat->leftUntilDone)
+ if (stat->leftUntilDone != 0)
{
++incomplete;
}
- if (stat->peersConnected)
+ if (stat->peersConnected != 0)
{
++connected;
}
secondary_text = g_string_new(NULL);
- if (!incomplete && !connected)
+ if (incomplete == 0 && connected == 0)
{
g_string_assign(secondary_text,
ngettext("Once removed, continuing the transfer will require the torrent file or magnet link.",
}
else
{
- if (connected)
+ if (connected != 0)
{
g_string_append(secondary_text, ngettext("One of these torrents is connected to peers.",
"Some of these torrents are connected to peers.", connected));
}
- if (connected && incomplete)
+ if (connected != 0 && incomplete != 0)
{
g_string_append(secondary_text, "\n");
}
- if (incomplete)
+ if (incomplete != 0)
{
g_string_assign(secondary_text, ngettext("One of these torrents has not finished downloading.",
"Some of these torrents have not finished downloading.", incomplete));
d = gtk_message_dialog_new_with_markup(parent, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE,
"<big><b>%s</b></big>", primary_text->str);
- if (secondary_text->len)
+ if (secondary_text->len != 0)
{
gtk_message_dialog_format_secondary_markup(GTK_MESSAGE_DIALOG(d), "%s", secondary_text->str);
}
gtk_dialog_add_buttons(GTK_DIALOG(d), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
- (delete_files ? GTK_STOCK_DELETE : GTK_STOCK_REMOVE), GTK_RESPONSE_ACCEPT, NULL);
+ delete_files ? GTK_STOCK_DELETE : GTK_STOCK_REMOVE, GTK_RESPONSE_ACCEPT, NULL);
gtk_dialog_set_default_response(GTK_DIALOG(d), GTK_RESPONSE_CANCEL);
gtk_dialog_set_alternative_button_order(GTK_DIALOG(d), GTK_RESPONSE_ACCEPT, GTK_RESPONSE_CANCEL, -1);
g_signal_connect(d, "response", G_CALLBACK(on_remove_dialog_response), dd);
{
data->torrentId = -1;
- if (data->timeout_tag)
+ if (data->timeout_tag != 0)
{
g_source_remove(data->timeout_tag);
data->timeout_tag = 0;
uint64_t const have = refresh_data->refresh_file_stat[index].bytesCompleted;
int const prog = size ? (int)((100.0 * have) / size) : 1;
- if ((priority != old_priority) || (enabled != old_enabled) || (have != old_have) || (prog != old_prog))
+ if (priority != old_priority || enabled != old_enabled || have != old_have || prog != old_prog)
{
/* Changing a value in the sort column can trigger a resort
* which breaks this foreach () call. (See #3529)
* sorting until we finish walking the tree. */
if (!refresh_data->resort_needed)
{
- if ((refresh_data->resort_needed =
- ((refresh_data->sort_column_id == FC_PRIORITY) && (priority != old_priority)) ||
- ((refresh_data->sort_column_id == FC_ENABLED) && (enabled != old_enabled))))
+ if ((refresh_data->resort_needed = (refresh_data->sort_column_id == FC_PRIORITY && priority != old_priority) ||
+ (refresh_data->sort_column_id == FC_ENABLED && enabled != old_enabled)))
{
refresh_data->resort_needed = TRUE;
gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE( data->model),
while (gtk_tree_model_iter_next(model, &child));
}
- prog = sub_size ? (int)((100.0 * have) / sub_size) : 1;
+ prog = sub_size != 0 ? (int)(100.0 * have / sub_size) : 1;
- if ((size != sub_size) || (have != old_have) || (priority != old_priority) || (enabled != old_enabled) ||
- (prog != old_prog))
+ if (size != sub_size || have != old_have || priority != old_priority || enabled != old_enabled || prog != old_prog)
{
char size_str[64];
tr_strlsize(size_str, sub_size, sizeof size_str);
while (gtk_tree_model_iter_next(model, &child));
}
- if (parent)
+ if (parent != NULL)
{
func(model, NULL, parent, data);
}
{
struct SubtreeForeachData* data = gdata;
- if (!gtk_tree_path_compare(path, data->path) || gtk_tree_path_is_descendant(path, data->path))
+ if (gtk_tree_path_compare(path, data->path) == 0 || gtk_tree_path_is_descendant(path, data->path))
{
unsigned int i;
gtk_tree_model_get(model, iter, FC_INDEX, &i, -1);
{
gboolean enabled;
gtk_tree_model_get(model, iter, FC_ENABLED, &enabled, -1);
- g_object_set(renderer, "inconsistent", (enabled == MIXED), "active", (enabled == TRUE), NULL);
+ g_object_set(renderer, "inconsistent", enabled == MIXED, "active", enabled == TRUE, NULL);
}
static void renderPriority(GtkTreeViewColumn* column UNUSED, GtkCellRenderer* renderer, GtkTreeModel* model, GtkTreeIter* iter,
/* if the file's not done, walk up the directory tree until we find
* an ancestor that exists, and open that instead */
- if (filename && (prog < 100 || !g_file_test(filename, G_FILE_TEST_EXISTS)))
+ if (filename != NULL && (prog < 100 || !g_file_test(filename, G_FILE_TEST_EXISTS)))
{
do
{
g_free(filename);
filename = tmp;
}
- while (filename && *filename && !g_file_test(filename, G_FILE_TEST_EXISTS));
+ while (filename != NULL && *filename != '\0' && !g_file_test(filename, G_FILE_TEST_EXISTS));
}
- if ((handled = filename && *filename))
+ if ((handled = filename != NULL && *filename != '\0'))
{
gtr_open_file(filename);
}
tr_torrent* tor;
gboolean handled = FALSE;
- if (!col || !path)
+ if (col == NULL || path == NULL)
{
return FALSE;
}
cid = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(col), TR_COLUMN_ID_KEY));
tor = gtr_core_find_torrent(data->core, data->torrentId);
- if ((tor != NULL) && ((cid == FC_PRIORITY) || (cid == FC_ENABLED)))
+ if (tor != NULL && (cid == FC_PRIORITY || cid == FC_ENABLED))
{
GtkTreeIter iter;
GArray* indices = getActiveFilesForPath(view, path);
GtkTreeView* treeview = GTK_TREE_VIEW(w);
FileData* data = gdata;
- if ((event->type == GDK_BUTTON_PRESS) && (event->button == 1) && !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) &&
+ if (event->type == GDK_BUTTON_PRESS && event->button == 1 && (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) == 0 &&
getAndSelectEventPath(treeview, event, &col, &path))
{
handled = onViewPathToggled(treeview, col, path, data);
{
name = g_strdup(host);
}
- else if (dot)
+ else if (dot != NULL)
{
name = g_strndup(host, dot - host);
}
switch (type)
{
case ACTIVITY_FILTER_DOWNLOADING:
- return (st->activity == TR_STATUS_DOWNLOAD) || (st->activity == TR_STATUS_DOWNLOAD_WAIT);
+ return st->activity == TR_STATUS_DOWNLOAD || st->activity == TR_STATUS_DOWNLOAD_WAIT;
case ACTIVITY_FILTER_SEEDING:
- return (st->activity == TR_STATUS_SEED) || (st->activity == TR_STATUS_SEED_WAIT);
+ return st->activity == TR_STATUS_SEED || st->activity == TR_STATUS_SEED_WAIT;
case ACTIVITY_FILTER_ACTIVE:
- return (st->peersSendingToUs > 0) || (st->peersGettingFromUs > 0) || (st->webseedsSendingToUs > 0) ||
- (st->activity == TR_STATUS_CHECK);
+ return st->peersSendingToUs > 0 || st->peersGettingFromUs > 0 || st->webseedsSendingToUs > 0 ||
+ st->activity == TR_STATUS_CHECK;
case ACTIVITY_FILTER_PAUSED:
return st->activity == TR_STATUS_STOPPED;
return st->finished == TRUE;
case ACTIVITY_FILTER_VERIFYING:
- return (st->activity == TR_STATUS_CHECK) || (st->activity == TR_STATUS_CHECK_WAIT);
+ return st->activity == TR_STATUS_CHECK || st->activity == TR_STATUS_CHECK_WAIT;
case ACTIVITY_FILTER_ERROR:
return st->error != 0;
{
gboolean ret = FALSE;
- if (!key || !*key)
+ if (key == NULL || *key == '\0')
{
ret = TRUE;
}
text = (char const*)g_object_get_qdata(o, TEXT_KEY);
- return (tor != NULL) && test_tracker(tor, data->active_tracker_type, data->active_tracker_host) &&
+ return tor != NULL && test_tracker(tor, data->active_tracker_type, data->active_tracker_host) &&
test_torrent_activity(tor, data->active_activity_type) && testText(tor, text);
}
gtk_tree_model_get(model, iter, MC_ACTIVITY, &activity, -1);
- if ((activity == TR_STATUS_DOWNLOAD_WAIT) || (activity == TR_STATUS_SEED_WAIT))
+ if (activity == TR_STATUS_DOWNLOAD_WAIT || activity == TR_STATUS_SEED_WAIT)
{
++counts->queued_count;
}
{
struct cbdata* data = gdata;
- if (!data->is_closing && !data->refresh_actions_tag)
+ if (!data->is_closing && data->refresh_actions_tag == 0)
{
data->refresh_actions_tag = gdk_threads_add_idle(refresh_actions, data);
}
static void on_main_window_size_allocated(GtkWidget* gtk_window, GtkAllocation* alloc UNUSED, gpointer gdata UNUSED)
{
GdkWindow* gdk_window = gtk_widget_get_window(gtk_window);
- gboolean const isMaximized = (gdk_window != NULL) && (gdk_window_get_state(gdk_window) & GDK_WINDOW_STATE_MAXIMIZED);
+ gboolean const isMaximized = gdk_window != NULL && (gdk_window_get_state(gdk_window) & GDK_WINDOW_STATE_MAXIMIZED) != 0;
gtr_pref_int_set(TR_KEY_main_window_is_maximized, isMaximized);
break;
case TR_RPC_TORRENT_ADDED:
- if ((tor = gtr_core_find_torrent(data->core, data->torrent_id)))
+ if ((tor = gtr_core_find_torrent(data->core, data->torrent_id)) != NULL)
{
gtr_core_add_torrent(data->core, tor, true);
}
bool changed;
tr_variant* oldval = tr_variantDictFind(oldvals, key);
- if (!oldval)
+ if (oldval == NULL)
{
changed = true;
}
signal(sig, SIG_DFL);
raise(sig);
}
- else if ((sig == SIGINT) || (sig == SIGTERM))
+ else if (sig == SIGINT || sig == SIGTERM)
{
g_message(_("Got signal %d; trying to shut down cleanly. Do it again if it gets stuck."), sig);
gtr_actions_handler("quit", sighandler_cbdata);
sighandler_cbdata = cbdata;
/* ensure the directories are created */
- if ((str = gtr_pref_string_get(TR_KEY_download_dir)))
+ if ((str = gtr_pref_string_get(TR_KEY_download_dir)) != NULL)
{
g_mkdir_with_parents(str, 0777);
}
- if ((str = gtr_pref_string_get(TR_KEY_incomplete_dir)))
+ if ((str = gtr_pref_string_get(TR_KEY_incomplete_dir)) != NULL)
{
g_mkdir_with_parents(str, 0777);
}
/* GApplication emits an 'activate' signal when bootstrapping the primary.
* Ordinarily we handle that by presenting the main window, but if the user
* user started Transmission minimized, ignore that initial signal... */
- if (cbdata->is_iconified && (cbdata->activation_count == 1))
+ if (cbdata->is_iconified && cbdata->activation_count == 1)
{
return;
}
g_slist_foreach(tmp, (GFunc)gtk_widget_destroy, NULL);
g_slist_free(tmp);
- if (cbdata->prefs)
+ if (cbdata->prefs != NULL)
{
gtk_widget_destroy(GTK_WIDGET(cbdata->prefs));
}
- if (cbdata->wind)
+ if (cbdata->wind != NULL)
{
gtk_widget_destroy(GTK_WIDGET(cbdata->wind));
}
g_object_unref(cbdata->core);
- if (cbdata->icon)
+ if (cbdata->icon != NULL)
{
g_object_unref(cbdata->icon);
}
cbdata->is_closing = true;
/* stop the update timer */
- if (cbdata->timer)
+ if (cbdata->timer != 0)
{
g_source_remove(cbdata->timer);
cbdata->timer = 0;
}
/* stop the refresh-actions timer */
- if (cbdata->refresh_actions_tag)
+ if (cbdata->refresh_actions_tag != 0)
{
g_source_remove(cbdata->refresh_actions_tag);
cbdata->refresh_actions_tag = 0;
static void flush_torrent_errors(struct cbdata* cbdata)
{
- if (cbdata->error_list)
+ if (cbdata->error_list != NULL)
{
show_torrent_errors(cbdata->wind, ngettext("Couldn't add corrupt torrent", "Couldn't add corrupt torrents",
g_slist_length(cbdata->error_list)), &cbdata->error_list);
}
- if (cbdata->duplicates_list)
+ if (cbdata->duplicates_list != NULL)
{
show_torrent_errors(cbdata->wind, ngettext("Couldn't add duplicate torrent", "Couldn't add duplicate torrents",
g_slist_length(cbdata->duplicates_list)), &cbdata->duplicates_list);
{
struct cbdata* cbdata = gdata;
- if (cbdata->wind)
+ if (cbdata->wind != NULL)
{
gtk_window_set_urgency_hint(cbdata->wind, FALSE);
}
g_signal_connect(w, "focus-in-event", G_CALLBACK(on_main_window_focus_in), cbdata);
- if (cbdata->wind)
+ if (cbdata->wind != NULL)
{
gtk_window_set_urgency_hint(cbdata->wind, TRUE);
}
{
bool const show = gtr_pref_flag_get(key);
- if (show && !cbdata->icon)
+ if (show && cbdata->icon == NULL)
{
cbdata->icon = gtr_icon_new(cbdata->core);
}
- else if (!show && cbdata->icon)
+ else if (!show && cbdata->icon != NULL)
{
g_clear_object(&cbdata->icon);
}
static gboolean update_model_loop(gpointer gdata)
{
- gboolean const done = global_sigcount;
+ gboolean const done = global_sigcount != 0;
if (!done)
{
}
else if (g_strcmp0(action_name, "edit-preferences") == 0)
{
- if (NULL == data->prefs)
+ if (data->prefs == NULL)
{
data->prefs = gtr_prefs_dialog_new(data->wind, G_OBJECT(data->core));
g_signal_connect(data->prefs, "destroy", G_CALLBACK(gtk_widget_destroyed), &data->prefs);
}
else if (g_strcmp0(action_name, "toggle-message-log") == 0)
{
- if (!data->msgwin)
+ if (data->msgwin == NULL)
{
GtkWidget* win = gtr_message_log_window_new(data->wind, data->core);
g_signal_connect(win, "destroy", G_CALLBACK(on_message_window_closed), NULL);
tr_metainfo_builder const* b = ui->builder;
GtkDialog* d = GTK_DIALOG(ui->progress_dialog);
GtkProgressBar* p = GTK_PROGRESS_BAR(ui->progress_bar);
- double const fraction = b->pieceCount ? ((double)b->pieceIndex / b->pieceCount) : 0;
+ double const fraction = b->pieceCount != 0 ? (double)b->pieceIndex / b->pieceCount : 0;
char* base = g_path_get_basename(b->top);
/* progress label */
}
/* progress bar */
- if (!b->pieceIndex)
+ if (b->pieceIndex == 0)
{
str = g_strdup("");
}
tracker_text = gtk_text_buffer_get_text(ui->announce_text_buffer, &start, &end, FALSE);
tracker_strings = g_strsplit(tracker_text, "\n", 0);
- for (i = 0; tracker_strings[i];)
+ for (i = 0; tracker_strings[i] != NULL;)
{
++i;
}
trackers = g_new0(tr_tracker_info, i);
- for (i = n = tier = 0; tracker_strings[i]; ++i)
+ for (i = n = tier = 0; tracker_strings[i] != NULL; ++i)
{
char const* str = tracker_strings[i];
- if (!*str)
+ if (*str == '\0')
{
++tier;
}
g_string_append(gstr, "<i>");
- if (!filename)
+ if (filename == NULL)
{
g_string_append(gstr, _("No source selected"));
}
MakeMetaUI* ui = user_data;
char** uris = gtk_selection_data_get_uris(selection_data);
- if (uris && uris[0])
+ if (uris != NULL && uris[0] != NULL)
{
char const* uri = uris[0];
gchar* filename = g_filename_from_uri(uri, NULL, NULL);
g_strlcpy(buf, asctime(&tm), sizeof(buf));
- if ((eoln = strchr(buf, '\n')))
+ if ((eoln = strchr(buf, '\n')) != NULL)
{
*eoln = '\0';
}
{
FILE* fp = fopen(filename, "w+");
- if (!fp)
+ if (fp == NULL)
{
- GtkWidget* w = gtk_message_dialog_new(parent, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, _(
- "Couldn't save \"%s\""), filename);
+ GtkWidget* w = gtk_message_dialog_new(parent, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, _("Couldn't save \"%s\""),
+ filename);
gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(w), "%s", g_strerror(errno));
g_signal_connect_swapped(w, "response", G_CALLBACK(gtk_widget_destroy), w);
gtk_widget_show(w);
break;
}
- fprintf(fp, "%s\t%s\t%s\t%s\n", date, levelStr, (node->name ? node->name : ""),
- (node->message ? node->message : ""));
+ fprintf(fp, "%s\t%s\t%s\t%s\n", date, levelStr, node->name != NULL ? node->name : "",
+ node->message != NULL ? node->message : "");
g_free(date);
}
while (gtk_tree_model_iter_next(model, &iter));
static unsigned int sequence = 0;
char const* default_name = g_get_application_name();
- for (i = head; i && i->next; i = i->next)
+ for (i = head; i != NULL && i->next != NULL; i = i->next)
{
- char const* name = i->name ? i->name : default_name;
+ char const* name = i->name != NULL ? i->name : default_name;
gtk_list_store_insert_with_values(store, NULL, 0,
COL_TR_MSG, i,
{
tr_log_message* msgs = tr_logGetQueue();
- if (msgs)
+ if (msgs != NULL)
{
/* add the new messages and append them to the end of
* our persistent list */
tr_log_message* tail = addMessages(data->store, msgs);
- if (myTail)
+ if (myTail != NULL)
{
myTail->next = msgs;
}
{
TrNotification* n = data;
- if (n->core)
+ if (n->core != NULL)
{
g_object_unref(G_OBJECT(n->core));
}
result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, NULL);
- if (!result || !g_variant_is_of_type(result, G_VARIANT_TYPE("(as)")))
+ if (result == NULL || !g_variant_is_of_type(result, G_VARIANT_TYPE("(as)")))
{
- if (result)
+ if (result != NULL)
{
g_variant_unref(result);
}
g_variant_get(result, "(^a&s)", &caps);
- for (i = 0; caps[i]; i++)
+ for (i = 0; caps[i] != NULL; i++)
{
if (g_strcmp0(caps[i], "actions") == 0)
{
result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, NULL);
- if (!result || !g_variant_is_of_type(result, G_VARIANT_TYPE("(u)")))
+ if (result == NULL || !g_variant_is_of_type(result, G_VARIANT_TYPE("(u)")))
{
- if (result)
+ if (result != NULL)
{
g_variant_unref(result);
}
char const* val;
g_snprintf(key, sizeof(key), "recent-download-dir-%d", i + 1);
- if ((val = gtr_pref_string_get(tr_quark_new(key, TR_BAD_SIZE))))
+ if ((val = gtr_pref_string_get(tr_quark_new(key, TR_BAD_SIZE))) != NULL)
{
list = g_slist_append(list, (void*)val);
}
}
/* if it was already in the list, remove it */
- if ((l = g_slist_find_custom(list, dir, (GCompareFunc)g_strcmp0)))
+ if ((l = g_slist_find_custom(list, dir, (GCompareFunc)g_strcmp0)) != NULL)
{
list = g_slist_delete_link(list, l);
}
/* make local copies of the strings that aren't
* invalidated by gtr_pref_string_set() */
- for (l = list; l; l = l->next)
+ for (l = list; l != NULL; l = l->next)
{
l->data = g_strdup(l->data);
}
/* save the first N_RECENT directories */
- for (l = list, i = 0; l && (i < N_RECENT); ++i, l = l->next)
+ for (l = list, i = 0; l != NULL && i < N_RECENT; ++i, l = l->next)
{
char key[64];
g_snprintf(key, sizeof(key), "recent-download-dir-%d", i + 1);
static void removeOldTorrent(struct OpenData* o)
{
- if (o->tor)
+ if (o->tor != NULL)
{
gtr_file_list_clear(o->file_list);
tr_torrentRemove(o->tor, FALSE, NULL);
{
struct OpenData* o = gdata;
- if (o->tor)
+ if (o->tor != NULL)
{
if (response != GTK_RESPONSE_ACCEPT)
{
gboolean const isLocalFile = tr_ctorGetSourceFile(o->ctor) != NULL;
gtk_widget_set_sensitive(o->trash_check, isLocalFile);
- if (!o->tor)
+ if (o->tor == NULL)
{
gtr_file_list_clear(o->file_list);
gtk_widget_set_sensitive(o->file_list, FALSE);
char* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(b));
/* maybe instantiate a torrent */
- if (filename || !o->tor)
+ if (filename != NULL || o->tor == NULL)
{
int err = 0;
- int new_file = 0;
+ bool new_file = false;
int duplicate_id = 0;
tr_torrent* torrent;
- if (filename && (!o->filename || !tr_sys_path_is_same(filename, o->filename, NULL)))
+ if (filename != NULL && (o->filename == NULL || !tr_sys_path_is_same(filename, o->filename, NULL)))
{
g_free(o->filename);
o->filename = g_strdup(filename);
tr_ctorSetMetainfoFromFile(o->ctor, o->filename);
- new_file = 1;
+ new_file = true;
}
tr_ctorSetDownloadDir(o->ctor, TR_FORCE, o->downloadDir);
tr_ctorSetPaused(o->ctor, TR_FORCE, TRUE);
tr_ctorSetDeleteSource(o->ctor, FALSE);
- if ((torrent = tr_torrentNew(o->ctor, &err, &duplicate_id)))
+ if ((torrent = tr_torrentNew(o->ctor, &err, &duplicate_id)) != NULL)
{
removeOldTorrent(o);
o->tor = torrent;
{
tr_torrent* tor;
- if (duplicate_id)
+ if (duplicate_id != 0)
{
tor = gtr_core_find_torrent(o->core, duplicate_id);
}
struct OpenData* data = gdata;
char* fname = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(b));
- if (fname && (!data->downloadDir || !tr_sys_path_is_same(fname, data->downloadDir, NULL)))
+ if (fname != NULL && (data->downloadDir == NULL || !tr_sys_path_is_same(fname, data->downloadDir, NULL)))
{
g_free(data->downloadDir);
data->downloadDir = g_strdup(fname);
list = get_recent_destinations();
- for (walk = list; walk; walk = walk->next)
+ for (walk = list; walk != NULL; walk = walk->next)
{
gtk_file_chooser_add_shortcut_folder(GTK_FILE_CHOOSER(w), walk->data, NULL);
}
* so that it creates the tor/gtor objects */
w = source_chooser;
- if (data->filename)
+ if (data->filename != NULL)
{
gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(w), data->filename);
}
addTorrentFilters(GTK_FILE_CHOOSER(w));
g_signal_connect(w, "response", G_CALLBACK(onOpenDialogResponse), core);
- if ((folder = gtr_pref_string_get(TR_KEY_open_dialog_dir)))
+ if ((folder = gtr_pref_string_get(TR_KEY_open_dialog_dir)) != NULL)
{
gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(w), folder);
}
char* url = g_strdup(gtk_entry_get_text(GTK_ENTRY(e)));
g_strstrip(url);
- if (url)
+ if (url != NULL)
{
handled = gtr_core_add_from_url(user_data, url);
}
else if (response == GTK_RESPONSE_CANCEL)
{
- handled = TRUE;
+ handled = true;
}
if (handled)
static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info const* info, tr_stat const* st)
{
- int const isDone = st->leftUntilDone == 0;
+ bool const isDone = st->leftUntilDone == 0;
uint64_t const haveTotal = st->haveUnchecked + st->haveValid;
- int const isSeed = st->haveValid >= info->totalSize;
+ bool const isSeed = st->haveValid >= info->totalSize;
char buf1[32], buf2[32], buf3[32], buf4[32], buf5[32], buf6[32];
double seedRatio;
- gboolean const hasSeedRatio = tr_torrentGetSeedRatio(tor, &seedRatio);
+ bool const hasSeedRatio = tr_torrentGetSeedRatio(tor, &seedRatio);
if (!isDone) /* downloading */
{
}
/* add time when downloading */
- if ((st->activity == TR_STATUS_DOWNLOAD) || (hasSeedRatio && (st->activity == TR_STATUS_SEED)))
+ if (st->activity == TR_STATUS_DOWNLOAD || (hasSeedRatio && st->activity == TR_STATUS_SEED))
{
int const eta = st->eta;
g_string_append(gstr, " - ");
static char* getShortTransferString(tr_torrent const* tor, tr_stat const* st, double uploadSpeed_KBps,
double downloadSpeed_KBps, char* buf, size_t buflen)
{
- int const haveMeta = tr_torrentHasMetadata(tor);
- int const haveUp = haveMeta && st->peersGettingFromUs > 0;
- int const haveDown = haveMeta && ((st->peersSendingToUs > 0) || (st->webseedsSendingToUs > 0));
+ bool const haveMeta = tr_torrentHasMetadata(tor);
+ bool const haveUp = haveMeta && st->peersGettingFromUs > 0;
+ bool const haveDown = haveMeta && (st->peersSendingToUs > 0 || st->webseedsSendingToUs > 0);
if (haveDown)
{
static void getStatusString(GString* gstr, tr_torrent const* tor, tr_stat const* st, double const uploadSpeed_KBps,
double const downloadSpeed_KBps)
{
- if (st->error)
+ if (st->error != 0)
{
char const* fmt[] =
{
g_string_append_printf(gstr, _("Downloading metadata from %1$'d %2$s (%3$d%% done)"), st->peersConnected,
ngettext("peer", "peers", st->peersConnected), (int)(100.0 * st->metadataPercentComplete));
}
- else if (st->peersSendingToUs && st->webseedsSendingToUs)
+ else if (st->peersSendingToUs != 0 && st->webseedsSendingToUs != 0)
{
/* Downloading from 2 of 3 peer (s) and 2 webseed (s) */
g_string_append_printf(gstr, _("Downloading from %1$'d of %2$'d %3$s and %4$'d %5$s"), st->peersSendingToUs,
st->peersConnected, ngettext("peer", "peers", st->peersConnected), st->webseedsSendingToUs,
ngettext("web seed", "web seeds", st->webseedsSendingToUs));
}
- else if (st->webseedsSendingToUs)
+ else if (st->webseedsSendingToUs != 0)
{
/* Downloading from 3 web seed (s) */
g_string_append_printf(gstr, _("Downloading from %1$'d %2$s"), st->webseedsSendingToUs,
}
}
- if ((st->activity != TR_STATUS_CHECK_WAIT) && (st->activity != TR_STATUS_CHECK) &&
- (st->activity != TR_STATUS_DOWNLOAD_WAIT) && (st->activity != TR_STATUS_SEED_WAIT) &&
- (st->activity != TR_STATUS_STOPPED))
+ if (st->activity != TR_STATUS_CHECK_WAIT && st->activity != TR_STATUS_CHECK && st->activity != TR_STATUS_DOWNLOAD_WAIT &&
+ st->activity != TR_STATUS_SEED_WAIT && st->activity != TR_STATUS_STOPPED)
{
char buf[256];
getShortTransferString(tor, st, uploadSpeed_KBps, downloadSpeed_KBps, buf, sizeof(buf));
- if (*buf)
+ if (*buf != '\0')
{
g_string_append_printf(gstr, " - %s", buf);
}
{
TorrentCellRenderer* self = TORRENT_CELL_RENDERER(cell);
- if (self && self->priv->tor)
+ if (self != NULL && self->priv->tor != NULL)
{
int w, h;
struct TorrentCellRendererPrivate* p = self->priv;
get_size_full(TORRENT_CELL_RENDERER(cell), widget, &w, &h);
}
- if (width)
+ if (width != NULL)
{
*width = w;
}
- if (height)
+ if (height != NULL)
{
*height = h;
}
- if (x_offset)
+ if (x_offset != NULL)
{
*x_offset = cell_area ? cell_area->x : 0;
}
- if (y_offset)
+ if (y_offset != NULL)
{
int xpad, ypad;
gtk_cell_renderer_get_padding(cell, &xpad, &ypad);
{
static GdkRGBA const red = { 1.0, 0, 0, 0 };
- if (st->error)
+ if (st->error != 0)
{
*setme = red;
}
{
double d;
- if ((st->activity == TR_STATUS_SEED) && tr_torrentGetSeedRatio(tor, &d))
+ if (st->activity == TR_STATUS_SEED && tr_torrentGetSeedRatio(tor, &d))
{
*seed = true;
d = MAX(0.0, st->seedRatioPercentDone);
struct TorrentCellRendererPrivate* p = cell->priv;
tr_torrent const* tor = p->tor;
tr_stat const* st = tr_torrentStatCached((tr_torrent*)tor);
- gboolean const active = (st->activity != TR_STATUS_STOPPED) && (st->activity != TR_STATUS_DOWNLOAD_WAIT) &&
- (st->activity != TR_STATUS_SEED_WAIT);
+ gboolean const active = st->activity != TR_STATUS_STOPPED && st->activity != TR_STATUS_DOWNLOAD_WAIT &&
+ st->activity != TR_STATUS_SEED_WAIT;
double const percentDone = get_percent_done(tor, st, &seed);
gboolean const sensitive = active || st->error;
GString* gstr_stat = p->gstr1;
tr_torrent const* tor = p->tor;
tr_stat const* st = tr_torrentStatCached((tr_torrent*)tor);
tr_info const* inf = tr_torrentInfo(tor);
- gboolean const active = (st->activity != TR_STATUS_STOPPED) && (st->activity != TR_STATUS_DOWNLOAD_WAIT) &&
- (st->activity != TR_STATUS_SEED_WAIT);
+ gboolean const active = st->activity != TR_STATUS_STOPPED && st->activity != TR_STATUS_DOWNLOAD_WAIT &&
+ st->activity != TR_STATUS_SEED_WAIT;
double const percentDone = get_percent_done(tor, st, &seed);
gboolean const sensitive = active || st->error;
GString* gstr_prog = p->gstr1;
gtk_widget_set_direction(widget, GTK_TEXT_DIR_RTL);
#endif
- if (self && self->priv->tor)
+ if (self != NULL && self->priv->tor != NULL)
{
struct TorrentCellRendererPrivate* p = self->priv;
{
TorrentCellRenderer* r = TORRENT_CELL_RENDERER(o);
- if (r && r->priv)
+ if (r != NULL && r->priv != NULL)
{
g_string_free(r->priv->gstr1, TRUE);
g_string_free(r->priv->gstr2, TRUE);
static int core_is_disposed(TrCore const* core)
{
- return !core || !core->priv->sorted_model;
+ return core == NULL || core->priv->sorted_model == NULL;
}
G_DEFINE_TYPE(TrCore, tr_core, G_TYPE_OBJECT)
{
core_add_to_busy(core, 1);
}
+
static void core_dec_busy(TrCore* core)
{
core_add_to_busy(core, -1);
static gboolean is_valid_eta(int t)
{
- return (t != TR_ETA_NOT_AVAIL) && (t != TR_ETA_UNKNOWN);
+ return t != TR_ETA_NOT_AVAIL && t != TR_ETA_UNKNOWN;
}
static int compare_eta(int a, int b)
gtk_tree_model_get(m, b, MC_TORRENT, &tb, -1);
sb = tr_torrentStatCached(tb);
- if (!ret)
+ if (ret == 0)
{
ret = compare_ratio(sa->ratio, sb->ratio);
}
- if (!ret)
+ if (ret == 0)
{
ret = compare_by_queue(m, a, b, user_data);
}
ret = compare_double(aUp + aDown, bUp + bDown);
- if (!ret)
+ if (ret == 0)
{
tr_stat const* const sa = tr_torrentStatCached(ta);
tr_stat const* const sb = tr_torrentStatCached(tb);
ret = compare_uint64(sa->peersSendingToUs + sa->peersGettingFromUs, sb->peersSendingToUs + sb->peersGettingFromUs);
}
- if (!ret)
+ if (ret == 0)
{
ret = compare_by_queue(m, a, b, user_data);
}
gtk_tree_model_get(m, a, MC_TORRENT, &ta, -1);
gtk_tree_model_get(m, b, MC_TORRENT, &tb, -1);
- if (!ret)
+ if (ret == 0)
{
ret = compare_time(tr_torrentStatCached(ta)->addedDate, tr_torrentStatCached(tb)->addedDate);
}
- if (!ret)
+ if (ret == 0)
{
ret = compare_by_name(m, a, b, u);
}
gtk_tree_model_get(m, b, MC_TORRENT, &t, -1);
ib = tr_torrentInfo(t);
- if (!ret)
+ if (ret == 0)
{
ret = compare_uint64(ia->totalSize, ib->totalSize);
}
- if (!ret)
+ if (ret == 0)
{
ret = compare_by_name(m, a, b, u);
}
gtk_tree_model_get(m, b, MC_TORRENT, &t, -1);
sb = tr_torrentStatCached(t);
- if (!ret)
+ if (ret == 0)
{
ret = compare_double(sa->percentComplete, sb->percentComplete);
}
- if (!ret)
+ if (ret == 0)
{
ret = compare_double(sa->seedRatioPercentDone, sb->seedRatioPercentDone);
}
- if (!ret)
+ if (ret == 0)
{
ret = compare_by_ratio(m, a, b, u);
}
gtk_tree_model_get(m, a, MC_TORRENT, &ta, -1);
gtk_tree_model_get(m, b, MC_TORRENT, &tb, -1);
- if (!ret)
+ if (ret == 0)
{
ret = compare_eta(tr_torrentStatCached(ta)->eta, tr_torrentStatCached(tb)->eta);
}
- if (!ret)
+ if (ret == 0)
{
ret = compare_by_name(m, a, b, u);
}
gtk_tree_model_get(m, a, MC_ACTIVITY, &sa, MC_TORRENT, &ta, -1);
gtk_tree_model_get(m, b, MC_ACTIVITY, &sb, MC_TORRENT, &tb, -1);
- if (!ret)
+ if (ret == 0)
{
ret = compare_int(sa, sb);
}
- if (!ret)
+ if (ret == 0)
{
ret = compare_by_queue(m, a, b, u);
}
{
char const* name;
- while ((name = g_dir_read_name(dir)))
+ while ((name = g_dir_read_name(dir)) != NULL)
{
char* filename = g_build_filename(dirname, name, NULL);
GFile* file = g_file_new_for_path(filename);
GFile* dir = g_file_new_for_path(gtr_pref_string_get(TR_KEY_watch_dir));
struct TrCorePrivate* p = core->priv;
- if (p->monitor && (!is_enabled || !g_file_equal(dir, p->monitor_dir)))
+ if (p->monitor != NULL && (!is_enabled || !g_file_equal(dir, p->monitor_dir)))
{
g_signal_handler_disconnect(p->monitor, p->monitor_tag);
g_file_monitor_cancel(p->monitor);
p->monitor_tag = 0;
}
- if (is_enabled && !p->monitor)
+ if (is_enabled && p->monitor == NULL)
{
GFileMonitor* m = g_file_monitor_directory(dir, 0, NULL, NULL);
core_watchdir_scan(core);
{
tr_session* session = gtr_core_session(core);
- if (session)
+ if (session != NULL)
{
core->priv->session = NULL;
gtr_pref_save(session);
so delegate to the GTK+ thread before calling notify's dbus code... */
static void on_torrent_completeness_changed(tr_torrent* tor, tr_completeness completeness, bool was_running, void* gcore)
{
- if (was_running && (completeness != TR_LEECH) && (tr_torrentStat(tor)->sizeWhenDone != 0))
+ if (was_running && completeness != TR_LEECH && tr_torrentStat(tor)->sizeWhenDone != 0)
{
struct notify_callback_data* data = g_new(struct notify_callback_data, 1);
data->core = gcore;
for (i = 0; i < inf->trackerCount; ++i)
{
- for (pch = inf->trackers[i].announce; *pch; ++pch)
+ for (pch = inf->trackers[i].announce; *pch != '\0'; ++pch)
{
hash = (hash << 4) ^ (hash >> 28) ^ *pch;
}
static gboolean is_torrent_active(tr_stat const* st)
{
- return (st->peersSendingToUs > 0) || (st->peersGettingFromUs > 0) || (st->activity == TR_STATUS_CHECK);
+ return st->peersSendingToUs > 0 || st->peersGettingFromUs > 0 || st->activity == TR_STATUS_CHECK;
}
void gtr_core_add_torrent(TrCore* core, tr_torrent* tor, gboolean do_notify)
tr_ctorSetDeleteSource(ctor, FALSE);
tor = tr_torrentNew(ctor, NULL, NULL);
- if (tor && do_trash)
+ if (tor != NULL && do_trash)
{
char const* config = tr_sessionGetConfigDir(session);
char const* source = tr_ctorGetSourceFile(ctor);
if (source != NULL)
{
/* #1294: don't delete the .torrent file if it's our internal copy */
- int const is_internal = (strstr(source, config) == source);
+ bool const is_internal = strstr(source, config) == source;
if (!is_internal)
{
/* don't complain about .torrent files in the watch directory
* that have already been added... that gets annoying and we
* don't want to be nagging users to clean up their watch dirs */
- if (!tr_ctorGetSourceFile(ctor) || !core->priv->adding_from_watch_dir)
+ if (tr_ctorGetSourceFile(ctor) == NULL || !core->priv->adding_from_watch_dir)
{
core_emit_err(core, err, inf.name);
}
g_message(_("Couldn't read \"%s\": %s"), g_file_get_parse_name(G_FILE(file)), error->message);
g_error_free(error);
}
- else if (!tr_ctorSetMetainfo(data->ctor, (uint8_t const*)contents, length))
+ else if (tr_ctorSetMetainfo(data->ctor, (uint8_t const*)contents, length) == 0)
{
core_add_ctor(data->core, data->ctor, data->do_prompt, data->do_notify);
}
/* updating the model triggers off resort/refresh,
so don't do it unless something's actually changed... */
- if ((newActive != oldActive) || (newActivity != oldActivity) || (newFinished != oldFinished) ||
- (newPriority != oldPriority) || (newQueuePosition != oldQueuePosition) || (newError != oldError) ||
- (newActivePeerCount != oldActivePeerCount) || (newDownloadPeerCount != oldDownloadPeerCount) ||
- (newUploadPeerCount != oldUploadPeerCount) || (newTrackers != oldTrackers) ||
- gtr_compare_double(newUpSpeed, oldUpSpeed, 2) || gtr_compare_double(newDownSpeed, oldDownSpeed, 2) ||
- gtr_compare_double(newRecheckProgress, oldRecheckProgress, 2))
+ if (newActive != oldActive || newActivity != oldActivity || newFinished != oldFinished || newPriority != oldPriority ||
+ newQueuePosition != oldQueuePosition || newError != oldError || newActivePeerCount != oldActivePeerCount ||
+ newDownloadPeerCount != oldDownloadPeerCount || newUploadPeerCount != oldUploadPeerCount ||
+ newTrackers != oldTrackers || gtr_compare_double(newUpSpeed, oldUpSpeed, 2) != 0 ||
+ gtr_compare_double(newDownSpeed, oldDownSpeed, 2) != 0 ||
+ gtr_compare_double(newRecheckProgress, oldRecheckProgress, 2) != 0)
{
gtk_list_store_set(GTK_LIST_STORE(model), iter,
MC_ACTIVE, newActive,
*cookie = g_variant_get_uint32(g_variant_get_child_value(response, 0));
}
- success = (response != NULL) && (err == NULL);
+ success = response != NULL && err == NULL;
/* logging */
if (success)
int const tag = (int)intVal;
struct pending_request_data* data = g_hash_table_lookup(pendingRequests, &tag);
- if (data)
+ if (data != NULL)
{
if (data->response_func)
{
tr_session* session;
tr_torrent* tor = NULL;
- if ((session = gtr_core_session(core)))
+ if ((session = gtr_core_session(core)) != NULL)
{
tor = tr_torrentFindFromId(session, id);
}
GtkWidget* w = gtk_entry_new();
char const* value = gtr_pref_string_get(key);
- if (value)
+ if (value != NULL)
{
gtk_entry_set_text(GTK_ENTRY(w), value);
}
rules = g_strsplit(whitelist, ",", 0);
- for (i = 0; rules && rules[i]; ++i)
+ for (i = 0; rules != NULL && rules[i] != NULL; ++i)
{
GtkTreeIter iter;
char const* s = rules[i];
gtk_widget_set_sensitive(data->portSpin, FALSE);
gtk_label_set_markup(GTK_LABEL(data->portLabel), _("<i>Testing TCP port…</i>"));
- if (!data->portTag)
+ if (data->portTag == 0)
{
data->portTag = g_signal_connect(data->core, "port-tested", G_CALLBACK(onPortTested), data);
}
{
GtkWidget* menu = gtr_action_get_widget("/main-window-popup");
- gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, (event ? event->button : 0), (event ? event->time : 0));
+ gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, event != NULL ? event->button : 0, event != NULL ? event->time : 0);
}
static void view_row_activated(GtkTreeView* tree_view UNUSED, GtkTreePath* path UNUSED, GtkTreeViewColumn* column UNUSED,
{
PrivateData* p = get_private_data(self);
- if (p && p->core && gtr_core_session(p->core))
+ if (p != NULL && p->core != NULL && gtr_core_session(p->core) != NULL)
{
updateSpeeds(p);
updateStats(p);
{
GtkWidget* w = GTK_WIDGET(win);
- if (w && gtk_widget_get_realized(w))
+ if (w != NULL && gtk_widget_get_realized(w))
{
GdkDisplay* display = gtk_widget_get_display(w);
GdkCursor* cursor = isBusy ? gdk_cursor_new_for_display(display, GDK_WATCH) : NULL;
char* tr_strlsize(char* buf, guint64 bytes, size_t buflen)
{
- if (!bytes)
+ if (bytes == 0)
{
g_strlcpy(buf, Q_("None"), buflen);
}
g_snprintf(m, sizeof(m), ngettext("%'d minute", "%'d minutes", minutes), minutes);
g_snprintf(s, sizeof(s), ngettext("%'d second", "%'d seconds", seconds), seconds);
- if (days)
+ if (days != 0)
{
- if (days >= 4 || !hours)
+ if (days >= 4 || hours == 0)
{
g_strlcpy(buf, d, buflen);
}
g_snprintf(buf, buflen, "%s, %s", d, h);
}
}
- else if (hours)
+ else if (hours != 0)
{
- if (hours >= 4 || !minutes)
+ if (hours >= 4 || minutes == 0)
{
g_strlcpy(buf, h, buflen);
}
g_snprintf(buf, buflen, "%s, %s", h, m);
}
}
- else if (minutes)
+ else if (minutes != 0)
{
- if (minutes >= 4 || !seconds)
+ if (minutes >= 4 || seconds == 0)
{
g_strlcpy(buf, m, buflen);
}
char host[1024];
char const* pch;
- if ((pch = strstr(url, "://")))
+ if ((pch = strstr(url, "://")) != NULL)
{
size_t const hostlen = strcspn(pch + 3, ":/");
size_t const copylen = MIN(hostlen, sizeof(host) - 1);
char const* first_dot = strchr(host, '.');
char const* last_dot = strrchr(host, '.');
- if ((first_dot) && (last_dot) && (first_dot != last_dot))
+ if (first_dot != NULL && last_dot != NULL && first_dot != last_dot)
{
g_strlcpy(buf, first_dot + 1, buflen);
}
static gboolean gtr_is_supported_url(char const* str)
{
- return (str != NULL) && (g_str_has_prefix(str, "ftp://") || g_str_has_prefix(str, "http://") ||
+ return str != NULL && (g_str_has_prefix(str, "ftp://") || g_str_has_prefix(str, "http://") ||
g_str_has_prefix(str, "https://"));
}
gboolean gtr_is_magnet_link(char const* str)
{
- return (str != NULL) && (g_str_has_prefix(str, "magnet:?"));
+ return str != NULL && g_str_has_prefix(str, "magnet:?");
}
gboolean gtr_is_hex_hashcode(char const* str)
{
int i;
- if (!str || (strlen(str) != 40))
+ if (str == NULL || strlen(str) != 40)
{
return FALSE;
}
GError* err = NULL;
trashed = g_file_trash(file, NULL, &err);
- if (err)
+ if (err != NULL)
{
g_message("Unable to trash file \"%s\": %s", filename, err->message);
tr_error_set_literal(error, err->code, err->message);
GError* err = NULL;
g_file_delete(file, NULL, &err);
- if (err)
+ if (err != NULL)
{
g_message("Unable to delete file \"%s\": %s", filename, err->message);
tr_error_clear(error);
{
static char* uri = NULL;
- if (!uri)
+ if (uri == NULL)
{
char const* fmt = "https://transmissionbt.com/help/gtk/%d.%dx";
uri = g_strdup_printf(fmt, MAJOR_VERSION, MINOR_VERSION / 10);
void gtr_open_uri(char const* uri)
{
- if (uri)
+ if (uri != NULL)
{
gboolean opened = FALSE;
g_string_append_printf(gstr, _("Transmission doesn't know how to use \"%s\""), url);
- if (gtr_is_magnet_link(url) && (strstr(url, xt) == NULL))
+ if (gtr_is_magnet_link(url) && strstr(url, xt) == NULL)
{
g_string_append_printf(gstr, "\n \n");
g_string_append_printf(gstr, _("This magnet link appears to be intended for something other than BitTorrent. "
{
char* s = text[i];
- if (s && (gtr_is_supported_url(s) || gtr_is_magnet_link(s) || gtr_is_hex_hashcode(s)))
+ if (s != NULL && (gtr_is_supported_url(s) || gtr_is_magnet_link(s) || gtr_is_hex_hashcode(s)))
{
gtk_entry_set_text(GTK_ENTRY(e), s);
break;
"&compact=1"
"&supportcrypto=1",
req->url,
- strchr(req->url, '?') ? '&' : '?',
+ strchr(req->url, '?') != NULL ? '&' : '?',
escaped_info_hash,
PEER_ID_LEN, PEER_ID_LEN, req->peer_id,
req->port,
evbuffer_add_printf(buf, "&requirecrypto=1");
}
- if (req->corrupt)
+ if (req->corrupt != 0)
{
evbuffer_add_printf(buf, "&corrupt=%" PRIu64, req->corrupt);
}
str = get_event_string(req);
- if (str && *str)
+ if (str != NULL && *str != '\0')
{
evbuffer_add_printf(buf, "&event=%s", str);
}
str = req->tracker_id_str;
- if (str && *str)
+ if (str != NULL && *str != '\0')
{
evbuffer_add_printf(buf, "&trackerid=%s", str);
}
ipv6 = tr_globalIPv6();
- if (ipv6)
+ if (ipv6 != NULL)
{
char ipv6_readable[INET6_ADDRSTRLEN];
evutil_inet_ntop(AF_INET6, ipv6, ipv6_readable, INET6_ADDRSTRLEN);
continue;
}
- if ((port < 0) || (port > USHRT_MAX))
+ if (port < 0 || port > USHRT_MAX)
{
continue;
}
else
{
tr_variant benc;
- bool const variant_loaded = !tr_variantFromBenc(&benc, msg, msglen);
+ bool const variant_loaded = tr_variantFromBenc(&benc, msg, msglen) == 0;
if (tr_env_key_exists("TR_CURL_VERBOSE"))
{
tr_variant* flags;
size_t len;
char const* str;
- bool const variant_loaded = !tr_variantFromBenc(&top, msg, msglen);
+ bool const variant_loaded = tr_variantFromBenc(&top, msg, msglen) == 0;
if (tr_env_key_exists("TR_CURL_VERBOSE"))
{
struct evbuffer* buf = evbuffer_new();
evbuffer_add_printf(buf, "%s", req->url);
- delimiter = strchr(req->url, '?') ? '&' : '?';
+ delimiter = strchr(req->url, '?') != NULL ? '&' : '?';
for (i = 0; i < req->info_hash_count; ++i)
{
{
struct tr_scrape_response_row* row;
- if (evbuffer_get_length(buf) < (sizeof(uint32_t) * 3))
+ if (evbuffer_get_length(buf) < sizeof(uint32_t) * 3)
{
break;
}
char* errmsg;
size_t const buflen = evbuffer_get_length(buf);
- if ((action == TAU_ACTION_ERROR) && (buflen > 0))
+ if (action == TAU_ACTION_ERROR && buflen > 0)
{
errmsg = tr_strndup(evbuffer_pullup(buf, -1), buflen);
}
request->response.did_connect = true;
request->response.did_timeout = false;
- if ((action == TAU_ACTION_ANNOUNCE) && (buflen >= 3 * sizeof(uint32_t)))
+ if (action == TAU_ACTION_ANNOUNCE && buflen >= 3 * sizeof(uint32_t))
{
tr_announce_response* resp = &request->response;
resp->interval = evbuffer_read_ntoh_32(buf);
{
char* errmsg;
- if ((action == TAU_ACTION_ERROR) && (buflen > 0))
+ if (action == TAU_ACTION_ERROR && buflen > 0)
{
errmsg = tr_strndup(evbuffer_pullup(buf, -1), buflen);
}
{
assert(t->dns_request == NULL);
- if (t->addr)
+ if (t->addr != NULL)
{
evutil_freeaddrinfo(t->addr);
}
tracker->dns_request = NULL;
- if (errcode)
+ if (errcode != 0)
{
char* errmsg = tr_strdup_printf(_("DNS Lookup failed: %s"), evutil_gai_strerror(errcode));
dbgmsg(tracker->key, "%s", errmsg);
{
struct tau_announce_request* req = tr_ptrArrayNth(reqs, i);
- if (!req->sent_at)
+ if (req->sent_at == 0)
{
dbgmsg(tracker->key, "sending announce req %p", (void*)req);
req->sent_at = now;
{
struct tau_scrape_request* req = tr_ptrArrayNth(reqs, i);
- if (!req->sent_at)
+ if (req->sent_at == 0)
{
dbgmsg(tracker->key, "sending scrape req %p", (void*)req);
req->sent_at = now;
char* errmsg;
size_t const buflen = buf ? evbuffer_get_length(buf) : 0;
- if ((action == TAU_ACTION_ERROR) && (buflen > 0))
+ if (action == TAU_ACTION_ERROR && buflen > 0)
{
errmsg = tr_strndup(evbuffer_pullup(buf, -1), buflen);
}
time_t const now = time(NULL);
bool const cancel_all = tracker->close_at && (tracker->close_at <= now);
- if (tracker->connecting_at && (tracker->connecting_at + TAU_REQUEST_TTL < now))
+ if (tracker->connecting_at != 0 && tracker->connecting_at + TAU_REQUEST_TTL < now)
{
on_tracker_connection_response(tracker, TAU_ACTION_ERROR, NULL);
}
{
struct tau_announce_request* req = tr_ptrArrayNth(reqs, i);
- if (cancel_all || (req->created_at + TAU_REQUEST_TTL < now))
+ if (cancel_all || req->created_at + TAU_REQUEST_TTL < now)
{
dbgmsg(tracker->key, "timeout announce req %p", (void*)req);
tau_announce_request_fail(req, false, true, NULL);
{
struct tau_scrape_request* req = tr_ptrArrayNth(reqs, i);
- if (cancel_all || (req->created_at + TAU_REQUEST_TTL < now))
+ if (cancel_all || req->created_at + TAU_REQUEST_TTL < now)
{
dbgmsg(tracker->key, "timeout scrape req %p", (void*)req);
tau_scrape_request_fail(req, false, true, NULL);
(size_t)tracker->connecting_at);
/* also need a valid connection ID... */
- if (tracker->addr && (tracker->connection_expiration_time <= now) && (!tracker->connecting_at))
+ if (tracker->addr != NULL && tracker->connection_expiration_time <= now && tracker->connecting_at == 0)
{
struct evbuffer* buf = evbuffer_new();
tracker->connecting_at = now;
tau_tracker_timeout_reqs(tracker);
- if ((tracker->addr != NULL) && (tracker->connection_expiration_time > now))
+ if (tracker->addr != NULL && tracker->connection_expiration_time > now)
{
tau_tracker_send_reqs(tracker);
}
/*fprintf(stderr, "got an incoming udp message w/len %zu\n", msglen);*/
- if (!session || !session->announcer_udp)
+ if (session == NULL || session->announcer_udp == NULL)
{
return false;
}
- if (msglen < (sizeof(uint32_t) * 2))
+ if (msglen < sizeof(uint32_t) * 2)
{
return false;
}
struct tau_tracker* tracker = tr_ptrArrayNth(&tau->trackers, i);
/* is it a connection response? */
- if (tracker->connecting_at && (transaction_id == tracker->connection_transaction_id))
+ if (tracker->connecting_at != 0 && transaction_id == tracker->connection_transaction_id)
{
dbgmsg(tracker->key, "%" PRIu32 " is my connection request!", transaction_id);
on_tracker_connection_response(tracker, action_id, buf);
{
struct tau_announce_request* req = tr_ptrArrayNth(reqs, j);
- if (req->sent_at && (transaction_id == req->transaction_id))
+ if (req->sent_at != 0 && transaction_id == req->transaction_id)
{
dbgmsg(tracker->key, "%" PRIu32 " is an announce request!", transaction_id);
tr_ptrArrayRemove(reqs, j);
{
struct tau_scrape_request* req = tr_ptrArrayNth(reqs, j);
- if (req->sent_at && (transaction_id == req->transaction_id))
+ if (req->sent_at != 0 && transaction_id == req->transaction_id)
{
dbgmsg(tracker->key, "%" PRIu32 " is a scrape request!", transaction_id);
tr_ptrArrayRemove(reqs, j);
tr_announce_request const* b = vb;
/* primary key: volume of data transferred. */
- if ((i = compareTransfer(a->up, a->down, b->up, b->down)))
+ if ((i = compareTransfer(a->up, a->down, b->up, b->down)) != 0)
{
return i;
}
int port = 0;
tr_urlParse(url, TR_BAD_SIZE, &scheme, &host, &port, NULL);
- ret = tr_strdup_printf("%s://%s:%d", (scheme ? scheme : "invalid"), (host ? host : "invalid"), port);
+ ret = tr_strdup_printf("%s://%s:%d", scheme != NULL ? scheme : "invalid", host != NULL ? host : "invalid", port);
tr_free(host);
tr_free(scheme);
{
ret = now + interval;
- while (ret % 10)
+ while (ret % 10 != 0)
{
++ret;
}
static void tier_build_log_name(tr_tier const* tier, char* buf, size_t buflen)
{
- tr_snprintf(buf, buflen, "[%s---%s]", (tier && tier->tor) ? tr_torrentName(tier->tor) : "?",
- (tier && tier->currentTracker) ? tier->currentTracker->key : "?");
+ tr_snprintf(buf, buflen, "[%s---%s]", (tier != NULL && tier->tor != NULL) ? tr_torrentName(tier->tor) : "?",
+ (tier != NULL && tier->currentTracker != NULL) ? tier->currentTracker->key : "?");
}
static void tierIncrementTracker(tr_tier* tier)
{
/* move our index to the next tracker in the tier */
- int const i = (tier->currentTracker == NULL) ? 0 : (tier->currentTrackerIndex + 1) % tier->tracker_count;
+ int const i = tier->currentTracker == NULL ? 0 : (tier->currentTrackerIndex + 1) % tier->tracker_count;
tier->currentTrackerIndex = i;
tier->currentTracker = &tier->trackers[i];
tr_session* session = announcer->session;
tr_torrent* tor = tr_torrentFindFromHash(session, info_hash);
- if (tor && tor->tiers)
+ if (tor != NULL && tor->tiers != NULL)
{
int i;
tr_torrent_tiers* tt = tor->tiers;
- for (i = 0; !tier && i < tt->tier_count; ++i)
+ for (i = 0; tier == NULL && i < tt->tier_count; ++i)
{
if (tt->tiers[i].key == tierId)
{
static void publishMessage(tr_tier* tier, char const* msg, int type)
{
- if (tier && tier->tor && tier->tor->tiers && tier->tor->tiers->callback)
+ if (tier != NULL && tier->tor != NULL && tier->tor->tiers != NULL && tier->tor->tiers->callback != NULL)
{
tr_torrent_tiers* tiers = tier->tor->tiers;
tr_tracker_event event = TRACKER_EVENT_INIT;
event.messageType = type;
event.text = msg;
- if (tier->currentTracker)
+ if (tier->currentTracker != NULL)
{
event.tracker = tier->currentTracker->announce;
}
/* special case optimization:
ocelot omits seeds from peer lists sent to seeds on private trackers.
so check for that case... */
- if ((leechers == pex_count) && tr_torrentIsPrivate(tier->tor) && tr_torrentIsSeed(tier->tor) &&
- (seeds + leechers < NUMWANT))
+ if (leechers == pex_count && tr_torrentIsPrivate(tier->tor) && tr_torrentIsSeed(tier->tor) && seeds + leechers < NUMWANT)
{
return 0;
}
- if (seeds >= 0 && leechers >= 0 && (seeds + leechers > 0))
+ if (seeds >= 0 && leechers >= 0 && seeds + leechers > 0)
{
- return (int8_t)((100.0 * seeds) / (seeds + leechers));
+ return (int8_t)(100.0 * seeds / (seeds + leechers));
}
return -1; /* unknown */
static void publishPeersPex(tr_tier* tier, int seeds, int leechers, tr_pex const* pex, int n)
{
- if (tier->tor->tiers->callback)
+ if (tier->tor->tiers->callback != NULL)
{
tr_tracker_event e = TRACKER_EVENT_INIT;
e.messageType = TR_TRACKER_PEERS;
*/
for (j = 0, jn = n; !is_duplicate && j < jn; ++j)
{
- is_duplicate = (tmp[j].port == port) && strcmp(tmp[j].scheme, scheme) == 0 && strcmp(tmp[j].host, host) == 0 &&
+ is_duplicate = tmp[j].port == port && strcmp(tmp[j].scheme, scheme) == 0 && strcmp(tmp[j].host, host) == 0 &&
strcmp(tmp[j].path, path) == 0;
}
{
for (j = i + 1, jn = n; j < jn; ++j)
{
- if ((tmp[i].info.tier != tmp[j].info.tier) && (tmp[i].port == tmp[j].port) &&
+ if (tmp[i].info.tier != tmp[j].info.tier && tmp[i].port == tmp[j].port &&
tr_strcmp0(tmp[i].host, tmp[j].host) == 0 && tr_strcmp0(tmp[i].path, tmp[j].path) == 0)
{
tmp[j].info.tier = tmp[i].info.tier;
for (i = 0; i < n; ++i)
{
- if (!i || (infos[i].tier != infos[i - 1].tier))
+ if (i == 0 || infos[i].tier != infos[i - 1].tier)
{
++tier_count;
}
for (i = 0; i < n; ++i)
{
- if (i && (infos[i].tier == infos[i - 1].tier))
+ if (i != 0 && infos[i].tier == infos[i - 1].tier)
{
++tier->tracker_count;
}
static void tier_announce_remove_trailing(tr_tier* tier, tr_announce_event e)
{
- while ((tier->announce_event_count > 0) && (tier->announce_events[tier->announce_event_count - 1] == e))
+ while (tier->announce_event_count > 0 && tier->announce_events[tier->announce_event_count - 1] == e)
{
--tier->announce_event_count;
}
time_t const now = tr_time();
tr_announce_event const event = data->event;
- if (announcer)
+ if (announcer != NULL)
{
++announcer->slotsAvailable;
}
response->downloads,
response->interval,
response->min_interval,
- response->tracker_id_str ? response->tracker_id_str : "none",
+ response->tracker_id_str != NULL ? response->tracker_id_str : "none",
response->pex_count,
response->pex6_count,
- response->errmsg ? response->errmsg : "none",
- response->warning ? response->warning : "none");
+ response->errmsg != NULL ? response->errmsg : "none",
+ response->warning != NULL ? response->warning : "none");
tier->lastAnnounceTime = now;
tier->lastAnnounceTimedOut = response->did_timeout;
{
on_announce_error(tier, _("Tracker did not respond"), event);
}
- else if (response->errmsg)
+ else if (response->errmsg != NULL)
{
/* If the torrent's only tracker returned an error, publish it.
Don't bother publishing if there are other trackers -- it's
publishErrorClear(tier);
- if ((tracker = tier->currentTracker))
+ if ((tracker = tier->currentTracker) != NULL)
{
tracker->consecutiveFailures = 0;
++scrape_fields;
}
- if ((str = response->tracker_id_str))
+ if ((str = response->tracker_id_str) != NULL)
{
tr_free(tracker->tracker_id_str);
tracker->tracker_id_str = tr_strdup(str);
}
}
- if ((str = response->warning))
+ if ((str = response->warning) != NULL)
{
tr_strlcpy(tier->lastAnnounceStr, str, sizeof(tier->lastAnnounceStr));
dbgmsg(tier, "tracker gave \"%s\"", str);
tr_strlcpy(tier->lastAnnounceStr, _("Success"), sizeof(tier->lastAnnounceStr));
}
- if ((i = response->min_interval))
+ if ((i = response->min_interval) != 0)
{
tier->announceMinIntervalSec = i;
}
- if ((i = response->interval))
+ if ((i = response->interval) != 0)
{
tier->announceIntervalSec = i;
}
tier->byteCounts[TR_ANN_CORRUPT] = 0;
}
- if (!isStopped && !tier->announce_event_count)
+ if (!isStopped && tier->announce_event_count == 0)
{
/* the queue is empty, so enqueue a perodic update */
i = tier->announceIntervalSec;
row->downloads,
row->downloaders,
response->min_request_interval,
- response->errmsg ? response->errmsg : "none");
+ response->errmsg != NULL ? response->errmsg : "none");
tier->isScraping = false;
tier->lastScrapeTime = now;
{
on_scrape_error(session, tier, _("Tracker did not respond"));
}
- else if (response->errmsg)
+ else if (response->errmsg != NULL)
{
on_scrape_error(session, tier, response->errmsg);
}
tier->scrapeAt = get_next_scrape_time(session, tier, tier->scrapeIntervalSec);
tr_logAddTorDbg(tier->tor, "Scrape successful. Rescraping in %d seconds.", tier->scrapeIntervalSec);
- if ((tracker = tier->currentTracker))
+ if ((tracker = tier->currentTracker) != NULL)
{
if (row->seeders >= 0)
{
}
/* otherwise, if there's room for another request, build a new one */
- if ((j == request_count) && (request_count < max_request_count))
+ if (j == request_count && request_count < max_request_count)
{
tr_scrape_request* req = &requests[request_count++];
req->url = url;
static bool tierNeedsToAnnounce(tr_tier const* tier, time_t const now)
{
- return !tier->isAnnouncing && !tier->isScraping && (tier->announceAt != 0) && (tier->announceAt <= now) &&
- (tier->announce_event_count > 0);
+ return !tier->isAnnouncing && !tier->isScraping && tier->announceAt != 0 && tier->announceAt <= now &&
+ tier->announce_event_count > 0;
}
static bool tierNeedsToScrape(tr_tier const* tier, time_t const now)
{
- return (!tier->isScraping) && (tier->scrapeAt != 0) && (tier->scrapeAt <= now) && (tier->currentTracker != NULL) &&
- (tier->currentTracker->scrape != NULL);
+ return !tier->isScraping && tier->scrapeAt != 0 && tier->scrapeAt <= now && tier->currentTracker != NULL &&
+ tier->currentTracker->scrape != NULL;
}
static int compareTiers(void const* va, void const* vb)
b->byteCounts[TR_ANN_DOWN]);
/* secondary key: announcements that have been waiting longer go first */
- if (!ret && (a->announceAt != b->announceAt))
+ if (ret == 0 && a->announceAt != b->announceAt)
{
ret = a->announceAt < b->announceAt ? -1 : 1;
}
/* build a list of tiers that need to be announced */
tor = NULL;
- while ((tor = tr_torrentNext(announcer->session, tor)))
+ while ((tor = tr_torrentNext(announcer->session, tor)) != NULL)
{
struct tr_torrent_tiers* tt = tor->tiers;
- for (i = 0; tt && i < tt->tier_count; ++i)
+ for (i = 0; tt != NULL && i < tt->tier_count; ++i)
{
tr_tier* tier = &tt->tiers[i];
st->isBackup = tracker != tier->currentTracker;
st->lastScrapeStartTime = tier->lastScrapeStartTime;
- if (tracker->scrape)
+ if (tracker->scrape != NULL)
{
tr_strlcpy(st->scrape, tracker->scrape, sizeof(st->scrape));
}
{
st->scrapeState = TR_TRACKER_ACTIVE;
}
- else if (!tier->scrapeAt)
+ else if (tier->scrapeAt == 0)
{
st->scrapeState = TR_TRACKER_INACTIVE;
}
{
st->announceState = TR_TRACKER_ACTIVE;
}
- else if (!torrent->isRunning || !tier->announceAt)
+ else if (!torrent->isRunning || tier->announceAt == 0)
{
st->announceState = TR_TRACKER_INACTIVE;
}
static unsigned int getSpeed_Bps(struct bratecontrol const* r, unsigned int interval_msec, uint64_t now)
{
- if (!now)
+ if (now == 0)
{
now = tr_time_msec();
}
assert(tr_isBandwidth(b));
assert(b != parent);
- if (b->parent)
+ if (b->parent != NULL)
{
assert(tr_isBandwidth(b->parent));
tr_ptrArrayRemoveSortedPointer(&b->parent->children, b, compareBandwidth);
b->parent = NULL;
}
- if (parent)
+ if (parent != NULL)
{
assert(tr_isBandwidth(parent));
assert(parent->parent != b);
* small chunk of bandwidth. Keep looping until we run out of bandwidth
* and/or peers that can use it */
n = peerCount;
- dbgmsg("%d peers to go round-robin for %s", n, (dir == TR_UP ? "upload" : "download"));
+ dbgmsg("%d peers to go round-robin for %s", n, dir == TR_UP ? "upload" : "download");
while (n > 0)
{
void tr_bandwidthSetPeer(tr_bandwidth* b, tr_peerIo* peer)
{
assert(tr_isBandwidth(b));
- assert((peer == NULL) || tr_isPeerIo(peer));
+ assert(peer == NULL || tr_isPeerIo(peer));
b->peer = peer;
}
assert(tr_isBandwidth(b));
assert(tr_isDirection(dir));
- if (b)
+ if (b != NULL)
{
if (b->band[dir].isLimited)
{
}
}
- if (b->parent && b->band[dir].honorParentLimits && (byteCount > 0))
+ if (b->parent != NULL && b->band[dir].honorParentLimits && byteCount > 0)
{
byteCount = bandwidthClamp(b->parent, now, dir, byteCount);
}
#ifdef DEBUG_DIRECTION
- if ((dir == DEBUG_DIRECTION) && (band->isLimited))
+ if (dir == DEBUG_DIRECTION && band->isLimited)
{
fprintf(stderr, "%p consumed %5zu bytes of %5s data... was %6zu, now %6zu left\n", b, byteCount,
- (isPieceData ? "piece" : "raw"), oldBytesLeft, band->bytesLeft);
+ isPieceData ? "piece" : "raw", oldBytesLeft, band->bytesLeft);
}
#endif
/** @brief test to see if the pointer refers to a live bandwidth object */
static inline bool tr_isBandwidth(tr_bandwidth const* b)
{
- return (b != NULL) && (b->magicNumber == BANDWIDTH_MAGIC_NUMBER);
+ return b != NULL && b->magicNumber == BANDWIDTH_MAGIC_NUMBER;
}
/******
/* test tr_bitfieldAdd */
for (i = 0; i < bitcount; i++)
{
- if (!(i % 7))
+ if (i % 7 == 0)
{
tr_bitfieldAdd(&field, i);
}
for (i = 0; i < bitcount; i++)
{
- check(tr_bitfieldHas(&field, i) == (!(i % 7)));
+ check(tr_bitfieldHas(&field, i) == (i % 7 == 0));
}
/* test tr_bitfieldAddRange */
/* test tr_bitfieldRem */
for (i = 0; i < bitcount; i++)
{
- if ((i % 7) != 0)
+ if (i % 7 != 0)
{
tr_bitfieldRem(&field, i);
}
for (i = 0; i < bitcount; i++)
{
- check(tr_bitfieldHas(&field, i) == (!(i % 7)));
+ check(tr_bitfieldHas(&field, i) == (i % 7 == 0));
}
/* test tr_bitfieldRemRange in the middle of a boundary */
for (i = 0; i < 64; i++)
{
- check(tr_bitfieldHas(&field, i) == ((i < 4) || (i >= 21)));
+ check(tr_bitfieldHas(&field, i) == (i < 4 || i >= 21));
}
/* test tr_bitfieldRemRange on the boundaries */
for (i = 0; i < 64; i++)
{
- check(tr_bitfieldHas(&field, i) == ((i < 8) || (i >= 24)));
+ check(tr_bitfieldHas(&field, i) == (i < 8 || i >= 24));
}
/* test tr_bitfieldRemRange when begin & end is on the same word */
for (i = 0; i < 64; i++)
{
- check(tr_bitfieldHas(&field, i) == ((i < 4) || (i >= 5)));
+ check(tr_bitfieldHas(&field, i) == (i < 4 || i >= 5));
}
/* test tr_bitfieldAddRange */
for (i = 0; i < 64; i++)
{
- check(tr_bitfieldHas(&field, i) == ((4 <= i) && (i < 21)));
+ check(tr_bitfieldHas(&field, i) == (4 <= i && i < 21));
}
/* test tr_bitfieldAddRange on the boundaries */
for (i = 0; i < 64; i++)
{
- check(tr_bitfieldHas(&field, i) == ((8 <= i) && (i < 24)));
+ check(tr_bitfieldHas(&field, i) == (8 <= i && i < 24));
}
/* test tr_bitfieldAddRange when begin & end is on the same word */
for (i = 0; i < 64; i++)
{
- check(tr_bitfieldHas(&field, i) == ((4 <= i) && (i < 5)));
+ check(tr_bitfieldHas(&field, i) == (4 <= i && i < 5));
}
tr_bitfieldDestruct(&field);
test_bitfield_has_all_none
};
- if ((ret = runTests(tests, NUM_TESTS(tests))))
+ if ((ret = runTests(tests, NUM_TESTS(tests))) != 0)
{
return ret;
}
/* bitfield count range */
for (l = 0; l < 10000; ++l)
{
- if ((ret = test_bitfield_count_range()))
+ if ((ret = test_bitfield_count_range()) != 0)
{
return ret;
}
size_t const first_byte = begin >> 3u;
size_t const last_byte = (end - 1) >> 3u;
- if (!b->bit_count)
+ if (b->bit_count == 0)
{
return 0;
}
static bool tr_bitfieldIsValid(tr_bitfield const* b)
{
assert(b != NULL);
- assert((b->alloc_count == 0) == (b->bits == 0));
- assert(!b->bits || (b->true_count == countArray(b)));
+ assert((b->alloc_count == 0) == (b->bits == NULL));
+ assert(b->bits == NULL || b->true_count == countArray(b));
return true;
}
static size_t get_bytes_needed(size_t bit_count)
{
- return (bit_count >> 3) + (bit_count & 7 ? 1 : 0);
+ return (bit_count >> 3) + ((bit_count & 7) != 0 ? 1 : 0);
}
static void set_all_true(uint8_t* array, size_t bit_count)
assert(b->bit_count > 0);
- if (b->alloc_count)
+ if (b->alloc_count != 0)
{
assert(b->alloc_count <= n);
memcpy(bits, b->bits, b->alloc_count);
end--;
- if ((end >= b->bit_count) || (begin > end))
+ if (end >= b->bit_count || begin > end)
{
return;
}
unsigned char sm, em;
size_t const diff = tr_bitfieldCountRange(b, begin, end);
- if (!diff)
+ if (diff == 0)
{
return;
}
end--;
- if ((end >= b->bit_count) || (begin > end))
+ if (end >= b->bit_count || begin > end)
{
return;
}
b->rules = tr_sys_file_map_for_reading(fd, 0, byteCount, &error);
- if (!b->rules)
+ if (b->rules == NULL)
{
tr_logAddError(err_fmt, b->filename, error->message);
tr_sys_file_close(fd, NULL);
blocklistEnsureLoaded(b);
- if (!b->rules || !b->ruleCount)
+ if (b->rules == NULL || b->ruleCount == 0)
{
return false;
}
walk = strrchr(line, ':');
- if (!walk)
+ if (walk == NULL)
{
return false;
}
size_t ranges_count = 0;
tr_error* error = NULL;
- if (!filename)
+ if (filename == NULL)
{
blocklistDelete(b);
return 0;
int i;
int err = 0;
- for (i = 0; !err && i < n; i++)
+ for (i = 0; err == 0 && i < n; i++)
{
int j;
int err = 0;
struct cache_block* cb = findBlock(cache, torrent, piece, offset);
- if (cb)
+ if (cb != NULL)
{
evbuffer_copyout(cb->evbuf, setme, len);
}
dbgmsg("flushing file %d from cache to disk: blocks [%zu...%zu]", (int)i, (size_t)first, (size_t)last);
/* flush out all the blocks in that file */
- while (!err && (pos < tr_ptrArraySize(&cache->blocks)))
+ while (err == 0 && pos < tr_ptrArraySize(&cache->blocks))
{
struct cache_block const* b = tr_ptrArrayNth(&cache->blocks, pos);
break;
}
- if ((b->block < first) || (b->block > last))
+ if (b->block < first || b->block > last)
{
break;
}
int const pos = findBlockPos(cache, torrent, 0);
/* flush out all the blocks in that torrent */
- while (!err && (pos < tr_ptrArraySize(&cache->blocks)))
+ while (err == 0 && pos < tr_ptrArraySize(&cache->blocks))
{
struct cache_block const* b = tr_ptrArrayNth(&cache->blocks, pos);
char const* str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-";
char const* pch = strchr(str, ch);
- if (!pch)
+ if (pch == NULL)
{
return false;
}
*buf = '\0';
- if (!id)
+ if (id == NULL)
{
return buf;
}
else /* current client style: -TR111Z- is 1.11+ */
{
tr_snprintf(buf, buflen, "Transmission %d.%02d%s", strint(id + 3, 1), strint(id + 4, 2),
- id[6] == 'Z' || id[6] == 'X' ? "+" : "");
+ (id[6] == 'Z' || id[6] == 'X') ? "+" : "");
}
}
else if (strncmp(chid + 1, "UT", 2) == 0)
}
/* Shad0w-style */
- if (!*buf)
+ if (*buf == '\0')
{
int a, b, c;
- if (strchr("AOQRSTU", id[0]) && getShadowInt(id[1], &a) && getShadowInt(id[2], &b) && getShadowInt(id[3], &c))
+ if (strchr("AOQRSTU", id[0]) != NULL && getShadowInt(id[1], &a) && getShadowInt(id[2], &b) && getShadowInt(id[3], &c))
{
char const* name = NULL;
break;
}
- if (name)
+ if (name != NULL)
{
tr_snprintf(buf, buflen, "%s %d.%d.%d", name, a, b, c);
return buf;
}
/* No match */
- if (!*buf)
+ if (*buf == '\0')
{
char out[32], * walk = out;
char const* in, * in_end;
n = tr_bitfieldCountRange(&cp->blockBitfield, f, l + 1);
n *= cp->tor->blockSize;
- if (l == (cp->tor->blockCount - 1) && tr_bitfieldHas(&cp->blockBitfield, l))
+ if (l == cp->tor->blockCount - 1 && tr_bitfieldHas(&cp->blockBitfield, l))
{
n -= (cp->tor->blockSize - cp->tor->lastBlockSize);
}
{
double const ratio = tr_getRatio(cp->sizeNow, tr_cpSizeWhenDone(cp));
int const iratio = (int)ratio;
- return ((iratio == TR_RATIO_NA) || (iratio == TR_RATIO_INF)) ? 0.0 : ratio;
+ return (iratio == TR_RATIO_NA || iratio == TR_RATIO_INF) ? 0.0 : ratio;
}
{
crypto->torrentHashIsSet = hash != NULL;
- if (hash)
+ if (hash != NULL)
{
memcpy(crypto->torrentHash, hash, SHA_DIGEST_LENGTH);
}
{
for (o = set->begin; o != set->end; ++o)
{
- if ((o->torrent_id == torrent_id) && cached_file_is_open(o))
+ if (o->torrent_id == torrent_id && cached_file_is_open(o))
{
cached_file_close(o);
}
{
for (o = set->begin; o != set->end; ++o)
{
- if ((torrent_id == o->torrent_id) && (i == o->file_index) && cached_file_is_open(o))
+ if (torrent_id == o->torrent_id && i == o->file_index && cached_file_is_open(o))
{
return o;
}
/* all slots are full... recycle the least recently used */
for (cull = NULL, o = set->begin; o != set->end; ++o)
{
- if (!cull || o->used_at < cull->used_at)
+ if (cull == NULL || o->used_at < cull->used_at)
{
cull = o;
}
void tr_fdClose(tr_session* session)
{
- if (session && session->fdInfo)
+ if (session != NULL && session->fdInfo != NULL)
{
struct tr_fdInfo* i = session->fdInfo;
fileset_destruct(&i->fileset);
static struct tr_fileset* get_fileset(tr_session* session)
{
- if (!session)
+ if (session == NULL)
{
return NULL;
}
{
struct tr_cached_file* o;
- if ((o = fileset_lookup(get_fileset(s), tr_torrentId(tor), i)))
+ if ((o = fileset_lookup(get_fileset(s), tr_torrentId(tor), i)) != NULL)
{
/* flush writable files so that their mtimes will be
* up-to-date when this function returns to the caller... */
{
struct tr_cached_file* o = fileset_lookup(get_fileset(s), torrent_id, i);
- if (!o || (writable && !o->is_writable))
+ if (o == NULL || (writable && !o->is_writable))
{
return TR_BAD_SYS_FILE;
}
tr_sys_path_info info;
struct tr_cached_file* o = fileset_lookup(get_fileset(s), torrent_id, i);
- if ((success = (o != NULL) && tr_sys_file_get_info(o->fd, &info, NULL)))
+ if ((success = o != NULL && tr_sys_file_get_info(o->fd, &info, NULL)))
{
*mtime = info.last_modified_at;
}
struct tr_fileset* set = get_fileset(session);
struct tr_cached_file* o = fileset_lookup(set, torrent_id, i);
- if (o && writable && !o->is_writable)
+ if (o != NULL && writable && !o->is_writable)
{
cached_file_close(o); /* close it so we can reopen in rw mode */
}
- else if (!o)
+ else if (o == NULL)
{
o = fileset_get_empty_slot(set);
}
{
int const err = cached_file_open(o, filename, writable, allocation, file_size);
- if (err)
+ if (err != 0)
{
errno = err;
return TR_BAD_SYS_FILE;
if (fd != TR_BAD_SOCKET)
{
- if ((gFd->peerCount < s->peerLimit) && tr_address_from_sockaddr_storage(addr, port, &sock))
+ if (gFd->peerCount < s->peerLimit && tr_address_from_sockaddr_storage(addr, port, &sock))
{
++gFd->peerCount;
}
tr_torrent* tor;
bool success;
- if ((torrentHash = tr_cryptoGetTorrentHash(handshake->crypto)))
+ if ((torrentHash = tr_cryptoGetTorrentHash(handshake->crypto)) != NULL)
{
- if ((tor = tr_torrentFindFromHash(handshake->session, torrentHash)))
+ if ((tor = tr_torrentFindFromHash(handshake->session, torrentHash)) != NULL)
{
peer_id = tr_torrentGetPeerId(tor);
}
/* add our public key (Ya) */
public_key = tr_cryptoGetMyPublicKey(handshake->crypto, &len);
assert(len == KEY_LEN);
- assert(public_key);
+ assert(public_key != NULL);
memcpy(walk, public_key, len);
walk += len;
handshake->crypto_select = crypto_select;
dbgmsg(handshake, "crypto select is %d", (int)crypto_select);
- if (!(crypto_select & getCryptoProvide(handshake)))
+ if ((crypto_select & getCryptoProvide(handshake)) == 0)
{
dbgmsg(handshake, "peer selected an encryption option we didn't offer");
return tr_handshakeDone(handshake, false);
/* if we've somehow connected to ourselves, don't keep the connection */
tor = tr_torrentFindFromHash(handshake->session, tr_peerIoGetTorrentHash(handshake->io));
- connected_to_self = (tor != NULL) && memcmp(peer_id, tr_torrentGetPeerId(tor), PEER_ID_LEN) == 0;
+ connected_to_self = tor != NULL && memcmp(peer_id, tr_torrentGetPeerId(tor), PEER_ID_LEN) == 0;
return tr_handshakeDone(handshake, !connected_to_self);
}
/* send crypto_select */
crypto_select = getCryptoSelect(handshake, handshake->crypto_provide);
- if (crypto_select)
+ if (crypto_select != 0)
{
dbgmsg(handshake, "selecting crypto mode '%d'", (int)crypto_select);
evbuffer_add_uint32(outbuf, crypto_select);
static bool fireDoneFunc(tr_handshake* handshake, bool isConnected)
{
- uint8_t const* peer_id = isConnected && handshake->havePeerID ? tr_peerIoGetPeersId(handshake->io) : NULL;
+ uint8_t const* peer_id = (isConnected && handshake->havePeerID) ? tr_peerIoGetPeersId(handshake->io) : NULL;
bool const success = (*handshake->doneCB)(handshake, handshake->io, handshake->haveReadAnythingFromPeer, isConnected,
peer_id, handshake->doneUserData);
static void tr_handshakeFree(tr_handshake* handshake)
{
- if (handshake->io)
+ if (handshake->io != NULL)
{
tr_peerIoUnref(handshake->io); /* balanced by the ref in tr_handshakeNew */
}
int errcode = errno;
tr_handshake* handshake = vhandshake;
- if (io->utp_socket && !io->isIncoming && handshake->state == AWAITING_YB)
+ if (io->utp_socket != NULL && !io->isIncoming && handshake->state == AWAITING_YB)
{
/* This peer probably doesn't speak uTP. */
/* if the error happened while we were sending a public key, we might
* have encountered a peer that doesn't do encryption... reconnect and
* try a plaintext handshake */
- if (((handshake->state == AWAITING_YB) || (handshake->state == AWAITING_VC)) &&
- (handshake->encryptionMode != TR_ENCRYPTION_REQUIRED) && (!tr_peerIoReconnect(handshake->io)))
+ if ((handshake->state == AWAITING_YB || handshake->state == AWAITING_VC) &&
+ handshake->encryptionMode != TR_ENCRYPTION_REQUIRED && tr_peerIoReconnect(handshake->io) == 0)
{
uint8_t msg[HANDSHAKE_SIZE];
unsigned int tr_historyGet(tr_recentHistory const* h, time_t now, unsigned int sec)
{
unsigned int n = 0;
- time_t const cutoff = (now ? now : tr_time()) - sec;
+ time_t const cutoff = (now != 0 ? now : tr_time()) - sec;
int i = h->newest;
for (;;)
tr_file const* const file = &info->files[fileIndex];
assert(fileIndex < info->fileCount);
- assert(!file->length || (fileOffset < file->length));
+ assert(file->length == 0 || fileOffset < file->length);
assert(fileOffset + buflen <= file->length);
- if (!file->length)
+ if (file->length == 0)
{
return 0;
}
tr_strdup(file->name);
}
- if (!err)
+ if (err == 0)
{
/* open (and maybe create) the file */
char* filename = tr_buildPath(base, subpath, NULL);
- int const prealloc = file->dnd || !doWrite ? TR_PREALLOCATE_NONE : tor->session->preallocationMode;
+ int const prealloc = (file->dnd || !doWrite) ? TR_PREALLOCATE_NONE : tor->session->preallocationMode;
if ((fd = tr_fdFileCheckout(session, tor->uniqueId, fileIndex, filename, doWrite, prealloc,
file->length)) == TR_BAD_SYS_FILE)
**** Use the fd
***/
- if (!err)
+ if (err == 0)
{
tr_error* error = NULL;
fileIndex++;
fileOffset = 0;
- if ((err != 0) && (ioMode == TR_IO_WRITE) && (tor->error != TR_STAT_LOCAL_ERROR))
+ if (err != 0 && ioMode == TR_IO_WRITE && tor->error != TR_STAT_LOCAL_ERROR)
{
char* path = tr_buildPath(tor->downloadDir, file->name, NULL);
tr_torrentSetLocalError(tor, "%s (%s)", tr_strerror(err), path);
while (bytesLeft)
{
size_t const len = MIN(bytesLeft, buflen);
- success = !tr_cacheReadBlock(tor->session->cache, tor, pieceIndex, offset, len, buffer);
+ success = tr_cacheReadBlock(tor->session->cache, tor, pieceIndex, offset, len, buffer) == 0;
if (!success)
{
check(tr_variantDictFindStr(&top, tr_quark_new("null", 4), &str, NULL));
check_streq("", str);
- if (!err)
+ if (err == 0)
{
tr_variantFree(&top);
}
tr_quark const key = tr_quark_new("key", 3);
err = tr_variantFromJson(&top, in, strlen(in));
- check(!err);
+ check(err == 0);
check(tr_variantIsDict(&top));
check(tr_variantDictFindStr(&top, key, &str, NULL));
check_streq("Letöltések", str);
- if (!err)
+ if (err == 0)
{
tr_variantFree(&top);
}
in = "{ \"key\": \"\\u005C\" }";
err = tr_variantFromJson(&top, in, strlen(in));
- check(!err);
+ check(err == 0);
check(tr_variantIsDict(&top));
check(tr_variantDictFindStr(&top, key, &str, NULL));
check_streq("\\", str);
- if (!err)
+ if (err == 0)
{
tr_variantFree(&top);
}
*/
in = "{ \"key\": \"Let\\u00f6lt\\u00e9sek\" }";
err = tr_variantFromJson(&top, in, strlen(in));
- check(!err);
+ check(err == 0);
check(tr_variantIsDict(&top));
check(tr_variantDictFindStr(&top, key, &str, NULL));
check_streq("Letöltések", str);
json = tr_variantToStr(&top, TR_VARIANT_FMT_JSON, NULL);
- if (!err)
+ if (err == 0)
{
tr_variantFree(&top);
}
check(strstr(json, "\\u00f6") != NULL);
check(strstr(json, "\\u00e9") != NULL);
err = tr_variantFromJson(&top, json, strlen(json));
- check(!err);
+ check(err == 0);
check(tr_variantIsDict(&top));
check(tr_variantDictFindStr(&top, key, &str, NULL));
check_streq("Letöltések", str);
- if (!err)
+ if (err == 0)
{
tr_variantFree(&top);
}
int64_t i;
int const err = tr_variantFromJson(&top, in, strlen(in));
- check(!err);
+ check(err == 0);
check(tr_variantIsDict(&top));
- check((headers = tr_variantDictFind(&top, tr_quark_new("headers", 7))));
+ check((headers = tr_variantDictFind(&top, tr_quark_new("headers", 7))) != NULL);
check(tr_variantIsDict(headers));
check(tr_variantDictFindStr(headers, tr_quark_new("type", 4), &str, NULL));
check_streq("request", str);
check(tr_variantDictFindInt(headers, TR_KEY_tag, &i));
check_int_eq(666, i);
- check((body = tr_variantDictFind(&top, tr_quark_new("body", 4))));
+ check((body = tr_variantDictFind(&top, tr_quark_new("body", 4))) != NULL);
check(tr_variantDictFindStr(body, TR_KEY_name, &str, NULL));
check_streq("torrent-info", str);
- check((args = tr_variantDictFind(body, tr_quark_new("arguments", 9))));
+ check((args = tr_variantDictFind(body, tr_quark_new("arguments", 9))) != NULL);
check(tr_variantIsDict(args));
- check((ids = tr_variantDictFind(args, TR_KEY_ids)));
+ check((ids = tr_variantDictFind(args, TR_KEY_ids)) != NULL);
check(tr_variantIsList(ids));
check_uint_eq(2, tr_variantListSize(ids));
check(tr_variantGetInt(tr_variantListChild(ids, 0), &i));
top.type = 0;
err = tr_variantFromJson(&top, in, strlen(in));
- check(err);
+ check(err != 0);
check(!tr_variantIsDict(&top));
return 0;
char const* str;
int const err = tr_variantFromJson(&top, in, strlen(in));
- check(!err);
+ check(err == 0);
check(tr_variantDictFindStr(&top, TR_KEY_errorString, &str, NULL));
check_streq("torrent not registered with this tracker 6UHsVW'*C", str);
/* run the tests in a locale with a decimal point of '.' */
setlocale(LC_NUMERIC, "C");
- if ((rv = runTests(tests, NUM_TESTS(tests))))
+ if ((rv = runTests(tests, NUM_TESTS(tests))) != 0)
{
return rv;
}
fprintf(stderr, "WARNING: unable to run locale-specific json tests. add a locale like %s or %s\n", comma_locales[0],
comma_locales[1]);
}
- else if ((rv = runTests(tests, NUM_TESTS(tests))))
+ else if ((rv = runTests(tests, NUM_TESTS(tests))) != 0)
{
return rv;
}
}
else
{
- fprintf(stderr, "FAIL %s:%d, expected \"%s\", got \"%s\"\n", file, line, expected ? expected : " (null)",
- actual ? actual : " (null)");
+ fprintf(stderr, "FAIL %s:%d, expected \"%s\", got \"%s\"\n", file, line, expected != NULL ? expected : "(null)",
+ actual != NULL ? actual : "(null)");
}
}
for (i = 0; i < numTests; i++)
{
- if ((ret = (*tests[i])()))
+ if ((ret = (*tests[i])()) != 0)
{
return ret;
}
q = TR_KEY_port_forwarding_enabled;
- if (!tr_variantDictFind(settings, q))
+ if (tr_variantDictFind(settings, q) == NULL)
{
tr_variantDictAddBool(settings, q, false);
}
q = TR_KEY_dht_enabled;
- if (!tr_variantDictFind(settings, q))
+ if (tr_variantDictFind(settings, q) == NULL)
{
tr_variantDictAddBool(settings, q, false);
}
q = TR_KEY_message_level;
- if (!tr_variantDictFind(settings, q))
+ if (tr_variantDictFind(settings, q) == NULL)
{
tr_variantDictAddInt(settings, q, verbose ? TR_LOG_DEBUG : TR_LOG_ERROR);
}
/* create the torrent */
err = 0;
tor = tr_torrentNew(ctor, &err, NULL);
- assert(!err);
+ assert(err == 0);
/* cleanup */
tr_free(metainfo);
char* dirname;
tr_file const* file = &tor->info.files[i];
- if (!complete && (i == 0))
+ if (!complete && i == 0)
{
path = tr_strdup_printf("%s%c%s.part", tor->currentDir, TR_PATH_DELIMITER, file->name);
}
{
static tr_lock* l = NULL;
- if (!l)
+ if (l == NULL)
{
l = tr_lockNew();
}
void tr_list_free(tr_list** list, TrListForeachFunc data_free_func)
{
- while (*list)
+ while (*list != NULL)
{
tr_list* node = *list;
*list = (*list)->next;
- if (data_free_func)
+ if (data_free_func != NULL)
{
data_free_func(node->data);
}
node->data = data;
node->next = *list;
- if (*list)
+ if (*list != NULL)
{
(*list)->prev = node;
}
node->data = data;
- if (!*list)
+ if (*list == NULL)
{
*list = node;
}
{
tr_list* l = *list;
- while (l->next)
+ while (l->next != NULL)
{
l = l->next;
}
static tr_list* tr_list_find_data(tr_list* list, void const* data)
{
- for (; list; list = list->next)
+ for (; list != NULL; list = list->next)
{
if (list->data == data)
{
static void* tr_list_remove_node(tr_list** list, tr_list* node)
{
void* data;
- tr_list* prev = node ? node->prev : NULL;
- tr_list* next = node ? node->next : NULL;
+ tr_list* prev = node != NULL ? node->prev : NULL;
+ tr_list* next = node != NULL ? node->next : NULL;
- if (prev)
+ if (prev != NULL)
{
prev->next = next;
}
- if (next)
+ if (next != NULL)
{
next->prev = prev;
}
{
void* ret = NULL;
- if (*list)
+ if (*list != NULL)
{
ret = (*list)->data;
tr_list_remove_node(list, *list);
tr_list* tr_list_find(tr_list* list, void const* b, TrListCompareFunc func)
{
- for (; list; list = list->next)
+ for (; list != NULL; list = list->next)
{
- if (!func(list->data, b))
+ if (func(list->data, b) == 0)
{
return list;
}
{
int size = 0;
- while (list)
+ while (list != NULL)
{
++size;
list = list->next;
{
static tr_lock* l = NULL;
- if (!l)
+ if (l == NULL)
{
l = tr_lockNew();
}
{
tr_log_message* next;
- while (NULL != list)
+ while (list != NULL)
{
next = list->next;
tr_free(list->message);
evbuffer_add_printf(buf, "[%s] ", tr_logGetTimeStr(timestr, sizeof(timestr)));
- if (name)
+ if (name != NULL)
{
evbuffer_add_printf(buf, "%s ", name);
}
#endif
- if (*buf)
+ if (*buf != '\0')
{
if (tr_logGetQueueEnabled())
{
tr_logGetTimeStr(timestr, sizeof(timestr));
- if (name)
+ if (name != NULL)
{
tr_sys_file_write_fmt(fp, "[%s] %s: %s" TR_NATIVE_EOL_STR, NULL, timestr, name, buf);
}
{
char const* walk;
- for (walk = uri + 8; walk && *walk;)
+ for (walk = uri + 8; walk != NULL && *walk != '\0';)
{
char const* key = walk;
char const* delim = strchr(key, '=');
displayName = tr_http_unescape(val, vallen);
}
- if ((vallen > 0) && (trCount < MAX_TRACKERS))
+ if (vallen > 0 && trCount < MAX_TRACKERS)
{
int i;
{
tr[trCount++] = tr_http_unescape(val, vallen);
}
- else if ((sscanf(key, "tr.%d=", &i) == 1) && (i >= 0)) /* ticket #3341 and #5134 */
+ else if (sscanf(key, "tr.%d=", &i) == 1 && i >= 0) /* ticket #3341 and #5134 */
{
tr[trCount++] = tr_http_unescape(val, vallen);
}
uint32_t const MiB = 1048576;
uint32_t const GiB = 1073741824;
- if (totalSize >= (2 * GiB))
+ if (totalSize >= 2 * GiB)
{
return 2 * MiB;
}
- if (totalSize >= (1 * GiB))
+ if (totalSize >= 1 * GiB)
{
return 1 * MiB;
}
- if (totalSize >= (512 * MiB))
+ if (totalSize >= 512 * MiB)
{
return 512 * KiB;
}
- if (totalSize >= (350 * MiB))
+ if (totalSize >= 350 * MiB)
{
return 256 * KiB;
}
- if (totalSize >= (150 * MiB))
+ if (totalSize >= 150 * MiB)
{
return 128 * KiB;
}
- if (totalSize >= (50 * MiB))
+ if (totalSize >= 50 * MiB)
{
return 64 * KiB;
}
static bool isValidPieceSize(uint32_t n)
{
- bool const isPowerOfTwo = !(n == 0) && !(n & (n - 1));
+ bool const isPowerOfTwo = n != 0 && (n & (n - 1)) == 0;
return isPowerOfTwo;
}
b->pieceSize = bytes;
b->pieceCount = (int)(b->totalSize / b->pieceSize);
- if (b->totalSize % b->pieceSize)
+ if (b->totalSize % b->pieceSize != 0)
{
++b->pieceCount;
}
void tr_metaInfoBuilderFree(tr_metainfo_builder* builder)
{
- if (builder)
+ if (builder != NULL)
{
int i;
tr_file_index_t t;
tr_sys_file_t fd;
tr_error* error = NULL;
- if (!b->totalSize)
+ if (b->totalSize == 0)
{
return ret;
}
assert(b->pieceIndex < b->pieceCount);
- while (leftInPiece)
+ while (leftInPiece != 0)
{
uint64_t const n_this_pass = MIN(b->files[fileIndex].size - off, leftInPiece);
uint64_t n_read = 0;
++b->pieceIndex;
}
- assert(b->abortFlag || (walk - ret == (int)(SHA_DIGEST_LENGTH * b->pieceCount)));
+ assert(b->abortFlag || walk - ret == (int)(SHA_DIGEST_LENGTH * b->pieceCount));
assert(b->abortFlag || !totalRemain);
if (fd != TR_BAD_SYS_FILE)
char* walk = filename;
char const* token;
- while ((token = tr_strsep(&walk, TR_PATH_DELIMITER_STR)))
+ while ((token = tr_strsep(&walk, TR_PATH_DELIMITER_STR)) != NULL)
{
- if (*token)
+ if (*token != '\0')
{
tr_variantListAddStr(uninitialized_path, token);
}
tr_variantDictAddInt(dict, TR_KEY_piece_length, builder->pieceSize);
- if ((pch = getHashInfo(builder)))
+ if ((pch = getHashInfo(builder)) != NULL)
{
tr_variantDictAddRaw(dict, TR_KEY_pieces, pch, SHA_DIGEST_LENGTH * builder->pieceCount);
tr_free(pch);
tr_variantInitDict(&top, 6);
- if (!builder->fileCount || !builder->totalSize || !builder->pieceSize || !builder->pieceCount)
+ if (builder->fileCount == 0 || builder->totalSize == 0 || builder->pieceSize == 0 || builder->pieceCount == 0)
{
builder->errfile[0] = '\0';
builder->my_errno = ENOENT;
builder->isDone = true;
}
- if (!builder->result && builder->trackerCount)
+ if (builder->result == TR_MAKEMETA_OK && builder->trackerCount != 0)
{
int prevTier = -1;
tr_variant* tier = NULL;
tr_variantDictAddStr(&top, TR_KEY_announce, builder->trackers[0].announce);
}
- if (!builder->result && !builder->abortFlag)
+ if (builder->result == TR_MAKEMETA_OK && !builder->abortFlag)
{
- if (builder->comment && *builder->comment)
+ if (builder->comment != NULL && *builder->comment != '\0')
{
tr_variantDictAddStr(&top, TR_KEY_comment, builder->comment);
}
}
/* save the file */
- if (!builder->result && !builder->abortFlag)
+ if (builder->result == TR_MAKEMETA_OK && !builder->abortFlag)
{
- if (tr_variantToFile(&top, TR_VARIANT_FMT_BENC, builder->outputFile))
+ if (tr_variantToFile(&top, TR_VARIANT_FMT_BENC, builder->outputFile) != 0)
{
builder->my_errno = errno;
tr_strlcpy(builder->errfile, builder->outputFile, sizeof(builder->errfile));
{
static tr_lock* lock = NULL;
- if (!lock)
+ if (lock == NULL)
{
lock = tr_lockNew();
}
tr_lock* lock = getQueueLock();
tr_lockLock(lock);
- if (queue)
+ if (queue != NULL)
{
builder = queue;
queue = queue->nextBuilder;
builder->comment = tr_strdup(comment);
builder->isPrivate = isPrivate;
- if (outputFile && *outputFile)
+ if (outputFile != NULL && *outputFile != '\0')
{
builder->outputFile = tr_strdup(outputFile);
}
builder->nextBuilder = queue;
queue = builder;
- if (!workerThread)
+ if (workerThread == NULL)
{
workerThread = tr_threadNew(makeMetaWorkerFunc, NULL);
}
int const err = tr_ctorSetMetainfo(ctor, metainfo[i].benc, strlen(metainfo[i].benc));
check_int_eq(metainfo[i].expected_benc_err, err);
- if (!err)
+ if (err == 0)
{
tr_parse_result const parse_result = tr_torrentParse(ctor, NULL);
check_int_eq(metainfo[i].expected_parse_result, parse_result);
static bool path_component_is_suspicious(char const* component)
{
- return (component == NULL) || (strpbrk(component, PATH_DELIMITER_CHARS) != NULL) || (strcmp(component, ".") == 0) ||
- (strcmp(component, "..") == 0);
+ return component == NULL || strpbrk(component, PATH_DELIMITER_CHARS) != NULL || strcmp(component, ".") == 0 ||
+ strcmp(component, "..") == 0;
}
static bool getfile(char** setme, char const* root, tr_variant* path, struct evbuffer* buf)
break;
}
- if (!*str)
+ if (*str == '\0')
{
continue;
}
}
}
- if (success && (evbuffer_get_length(buf) <= root_len))
+ if (success && evbuffer_get_length(buf) <= root_len)
{
success = false;
}
* it will be taken as a sign that that tracker doesn't support
* the scrape convention. If it does, substitute 'scrape' for
* 'announce' to find the scrape page. */
- if (((s = strrchr(announce, '/')) != NULL) && strncmp(++s, "announce", 8) == 0)
+ if ((s = strrchr(announce, '/')) != NULL && strncmp(++s, "announce", 8) == 0)
{
char const* prefix = announce;
size_t const prefix_len = s - announce;
}
/* did we use any of the tiers? */
- if (!trackerCount)
+ if (trackerCount == 0)
{
tr_free(trackers);
trackers = NULL;
}
/* Regular announce value */
- if (!trackerCount && tr_variantDictFindStr(meta, TR_KEY_announce, &str, &len))
+ if (trackerCount == 0 && tr_variantDictFindStr(meta, TR_KEY_announce, &str, &len))
{
char* url = tr_strstrip(tr_strndup(str, len));
if (tr_urlIsValid(url, len))
{
- if ((inf->fileCount > 1) && (len > 0) && (url[len - 1] != '/'))
+ if (inf->fileCount > 1 && len > 0 && url[len - 1] != '/')
{
ret = tr_strdup_printf("%*.*s/", (int)len, (int)len, url);
}
inf->originalName = tr_strndup(str, len);
}
- if (!inf->name)
+ if (inf->name == NULL)
{
inf->name = tr_strdup(inf->hashString);
}
- if (!inf->originalName)
+ if (inf->originalName == NULL)
{
inf->originalName = tr_strdup(inf->hashString);
}
}
}
- if (!str || !*str)
+ if (str == NULL || *str == '\0')
{
return "name";
}
/* files */
if (!isMagnet)
{
- if ((str = parseFiles(inf, tr_variantDictFind(infoDict, TR_KEY_files), tr_variantDictFind(infoDict, TR_KEY_length))))
+ if ((str = parseFiles(inf, tr_variantDictFind(infoDict, TR_KEY_files), tr_variantDictFind(infoDict, TR_KEY_length))) != NULL)
{
return str;
}
- if (!inf->fileCount || !inf->totalSize)
+ if (inf->fileCount == 0 || inf->totalSize == 0)
{
return "files";
}
}
/* get announce or announce-list */
- if ((str = getannounce(inf, meta)))
+ if ((str = getannounce(inf, meta)) != NULL)
{
return str;
}
/* filename of Transmission's copy */
tr_free(inf->torrent);
- inf->torrent = session ? getTorrentFilename(session, inf) : NULL;
+ inf->torrent = session != NULL ? getTorrentFilename(session, inf) : NULL;
return NULL;
}
char const* badTag = tr_metainfoParseImpl(session, inf, hasInfoDict, infoDictLength, meta_in);
bool const success = badTag == NULL;
- if (badTag)
+ if (badTag != NULL)
{
tr_logAddNamedError(inf->name, _("Invalid metadata entry \"%s\""), badTag);
tr_metainfoFree(inf);
libttest_blockingTorrentVerify(tor);
check_uint_eq(0, tr_torrentStat(tor)->leftUntilDone);
- while ((completeness == completeness_unset) && (time(NULL) <= deadline))
+ while (completeness == completeness_unset && time(NULL) <= deadline)
{
tr_wait_msec(50);
}
int rv;
/* test what happens when incompleteDir is a subdir of downloadDir*/
- if ((rv = test_incomplete_dir_impl("Downloads/Incomplete", "Downloads")))
+ if ((rv = test_incomplete_dir_impl("Downloads/Incomplete", "Downloads")) != 0)
{
return rv;
}
/* test what happens when downloadDir is a subdir of incompleteDir */
- if ((rv = test_incomplete_dir_impl("Downloads", "Downloads/Complete")))
+ if ((rv = test_incomplete_dir_impl("Downloads", "Downloads/Complete")) != 0)
{
return rv;
}
/* test what happens when downloadDir and incompleteDir are siblings */
- if ((rv = test_incomplete_dir_impl("Incomplete", "Downloads")))
+ if ((rv = test_incomplete_dir_impl("Incomplete", "Downloads")) != 0)
{
return rv;
}
void tr_natpmpClose(tr_natpmp* nat)
{
- if (nat)
+ if (nat != NULL)
{
closenatpmp(&nat->natpmp);
tr_free(nat);
{
int ret;
- if (is_enabled && (nat->state == TR_NATPMP_DISCOVER))
+ if (is_enabled && nat->state == TR_NATPMP_DISCOVER)
{
int val = initnatpmp(&nat->natpmp, 0, 0);
logVal("initnatpmp", val);
setCommandTime(nat);
}
- if ((nat->state == TR_NATPMP_RECV_PUB) && canSendCommand(nat))
+ if (nat->state == TR_NATPMP_RECV_PUB && canSendCommand(nat))
{
natpmpresp_t response;
int const val = readnatpmpresponseorretry(&nat->natpmp, &response);
}
}
- if ((nat->state == TR_NATPMP_IDLE) || (nat->state == TR_NATPMP_ERR))
+ if (nat->state == TR_NATPMP_IDLE || nat->state == TR_NATPMP_ERR)
{
- if (nat->is_mapped && (!is_enabled || (nat->private_port != private_port)))
+ if (nat->is_mapped && (!is_enabled || nat->private_port != private_port))
{
nat->state = TR_NATPMP_SEND_UNMAP;
}
}
- if ((nat->state == TR_NATPMP_SEND_UNMAP) && canSendCommand(nat))
+ if (nat->state == TR_NATPMP_SEND_UNMAP && canSendCommand(nat))
{
int const val = sendnewportmappingrequest(&nat->natpmp, NATPMP_PROTOCOL_TCP, nat->private_port, nat->public_port, 0);
logVal("sendnewportmappingrequest", val);
}
}
- if ((nat->state == TR_NATPMP_SEND_MAP) && canSendCommand(nat))
+ if (nat->state == TR_NATPMP_SEND_MAP && canSendCommand(nat))
{
int const val = sendnewportmappingrequest(&nat->natpmp, NATPMP_PROTOCOL_TCP, private_port, private_port, LIFETIME_SECS);
logVal("sendnewportmappingrequest", val);
{
int n = 8192;
- if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void const*)&n, sizeof(n)))
+ if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void const*)&n, sizeof(n)) != 0)
{
tr_logAddInfo("Unable to set SO_RCVBUF on socket %" PRIdMAX ": %s", (intmax_t)s,
tr_net_strerror(err_buf, sizeof(err_buf), sockerrno));
assert(source_addr);
sourcelen = setup_sockaddr(source_addr, 0, &source_sock);
- if (bind(s, (struct sockaddr*)&source_sock, sourcelen))
+ if (bind(s, (struct sockaddr*)&source_sock, sourcelen) != 0)
{
tr_logAddError(_("Couldn't set source address %s on %" PRIdMAX ": %s"), tr_address_to_string(source_addr), (intmax_t)s,
tr_net_strerror(err_buf, sizeof(err_buf), sockerrno));
return TR_BAD_SOCKET; /* -errno */
}
- if ((connect(s, (struct sockaddr*)&sock, addrlen) < 0) &&
+ if (connect(s, (struct sockaddr*)&sock, addrlen) < 0 &&
#ifdef _WIN32
- (sockerrno != WSAEWOULDBLOCK) &&
+ sockerrno != WSAEWOULDBLOCK &&
#endif
- (sockerrno != EINPROGRESS))
+ sockerrno != EINPROGRESS)
{
int tmperrno;
tmperrno = sockerrno;
addrlen = setup_sockaddr(addr, htons(port), &sock);
- if (bind(fd, (struct sockaddr*)&sock, addrlen))
+ if (bind(fd, (struct sockaddr*)&sock, addrlen) != 0)
{
int const err = sockerrno;
{
unsigned char const* a = (unsigned char*)&((struct sockaddr_in6*)sa)->sin6_addr;
/* 2000::/3 */
- return (a[0] & 0xE0) == 0x20;
+ return (a[0] & 0xE0) == 0x20 ? 1 : 0;
}
else
{
return -1;
}
- if (!global_unicast_address((struct sockaddr*)&ss))
+ if (global_unicast_address((struct sockaddr*)&ss) == 0)
{
return -1;
}
{
int addrlen = 16;
int const rc = tr_globalAddress(AF_INET6, ipv6, &addrlen);
- have_ipv6 = (rc >= 0) && (addrlen == 16);
+ have_ipv6 = rc >= 0 && addrlen == 16;
last_time = now;
}
static bool isIPv4MappedAddress(tr_address const* addr)
{
- return (addr->type == TR_AF_INET6) && IN6_IS_ADDR_V4MAPPED(&addr->addr.addr6);
+ return addr->type == TR_AF_INET6 && IN6_IS_ADDR_V4MAPPED(&addr->addr.addr6);
}
static bool isIPv6LinkLocalAddress(tr_address const* addr)
{
- return (addr->type == TR_AF_INET6) && IN6_IS_ADDR_LINKLOCAL(&addr->addr.addr6);
+ return addr->type == TR_AF_INET6 && IN6_IS_ADDR_LINKLOCAL(&addr->addr.addr6);
}
/* isMartianAddr was written by Juliusz Chroboczek,
case TR_AF_INET:
{
unsigned char const* address = (unsigned char const*)&a->addr.addr4;
- return (address[0] == 0) || (address[0] == 127) || ((address[0] & 0xE0) == 0xE0);
+ return address[0] == 0 || address[0] == 127 || (address[0] & 0xE0) == 0xE0;
}
case TR_AF_INET6:
{
unsigned char const* address = (unsigned char const*)&a->addr.addr6;
- return (address[0] == 0xFF) || (memcmp(address, zeroes, 15) == 0 && (address[15] == 0 || address[15] == 1));
+ return address[0] == 0xFF || (memcmp(address, zeroes, 15) == 0 && (address[15] == 0 || address[15] == 1));
}
default:
bool tr_address_is_valid_for_peers(tr_address const* addr, tr_port port)
{
- return (port != 0) && (tr_address_is_valid(addr)) && (!isIPv6LinkLocalAddress(addr)) && (!isIPv4MappedAddress(addr)) &&
- (!isMartianAddr(addr));
+ return port != 0 && tr_address_is_valid(addr) && !isIPv6LinkLocalAddress(addr) && !isIPv4MappedAddress(addr) &&
+ !isMartianAddr(addr);
}
{
struct tr_datatype* tmp;
- if ((tmp = io->outbuf_datatypes))
+ if ((tmp = io->outbuf_datatypes) != NULL)
{
io->outbuf_datatypes = tmp->next;
datatype_free(tmp);
{
struct tr_datatype* tmp;
- if ((tmp = io->outbuf_datatypes))
+ if ((tmp = io->outbuf_datatypes) != NULL)
{
while (tmp->next != NULL)
{
static void didWriteWrapper(tr_peerIo* io, unsigned int bytes_transferred)
{
- while (bytes_transferred && tr_isPeerIo(io))
+ while (bytes_transferred != 0 && tr_isPeerIo(io))
{
struct tr_datatype* next = io->outbuf_datatypes;
tr_bandwidthUsed(&io->bandwidth, TR_UP, overhead, false, now);
}
- if (io->didWrite)
+ if (io->didWrite != NULL)
{
io->didWrite(io, payload, next->isPieceData, io->userData);
}
bytes_transferred -= payload;
next->length -= payload;
- if (!next->length)
+ if (next->length == 0)
{
peer_io_pull_datatype(io);
}
session = io->session;
/* try to consume the input buffer */
- if (io->canRead)
+ if (io->canRead != NULL)
{
uint64_t const now = tr_time_msec();
size_t const used = oldLen - evbuffer_get_length(io->inbuf);
unsigned int const overhead = guessPacketOverhead(used);
- if (piece || (piece != used))
+ if (piece != 0 || piece != used)
{
- if (piece)
+ if (piece != 0)
{
tr_bandwidthUsed(&io->bandwidth, TR_DOWN, piece, true, now);
}
switch (ret)
{
case READ_NOW:
- if (evbuffer_get_length(io->inbuf))
+ if (evbuffer_get_length(io->inbuf) != 0)
{
continue;
}
if (res == -1)
{
- if (!e || e == EAGAIN || e == EINTR || e == EINPROGRESS)
+ if (e == 0 || e == EAGAIN || e == EINTR || e == EINPROGRESS)
{
goto reschedule;
}
goto error;
}
- if (evbuffer_get_length(io->outbuf))
+ if (evbuffer_get_length(io->outbuf) != 0)
{
tr_peerIoSetEnabled(io, dir, true);
}
return;
reschedule:
-
- if (evbuffer_get_length(io->outbuf))
+ if (evbuffer_get_length(io->outbuf) != 0)
{
tr_peerIoSetEnabled(io, dir, true);
}
static void maybeSetCongestionAlgorithm(tr_socket_t socket, char const* algorithm)
{
- if (algorithm && *algorithm)
+ if (algorithm != NULL && *algorithm != '\0')
{
tr_netSetCongestionControl(socket, algorithm);
}
{
dbgmsg(io, "utp_on_state_change -- changed to writable");
- if (io->pendingEvents & EV_WRITE)
+ if ((io->pendingEvents & EV_WRITE) != 0)
{
utp_on_writable(io);
}
}
else if (state == UTP_STATE_EOF)
{
- if (io->gotError)
+ if (io->gotError != NULL)
{
io->gotError(io, BEV_EVENT_EOF, io->userData);
}
dbgmsg(io, "utp_on_error -- errcode is %d", errcode);
- if (io->gotError)
+ if (io->gotError != NULL)
{
errno = errcode;
io->gotError(io, BEV_EVENT_ERROR, io->userData);
}
}
-static void utp_on_overhead(void* closure, uint8_t send, size_t count, int type UNUSED)
+static void utp_on_overhead(void* closure, uint8_t /* bool */ send, size_t count, int type UNUSED)
{
tr_peerIo* io = closure;
assert(tr_isPeerIo(io));
static void dummy_on_state_change(void* closure UNUSED, int state UNUSED)
{
- return;
}
static void dummy_on_error(void* closure UNUSED, int errcode UNUSED)
{
- return;
}
-static void dummy_on_overhead(void* closure UNUSED, uint8_t send UNUSED, size_t count UNUSED, int type UNUSED)
+static void dummy_on_overhead(void* closure UNUSED, uint8_t /* bool */ send UNUSED, size_t count UNUSED, int type UNUSED)
{
- return;
}
static struct UTPFunctionTable dummy_utp_function_table =
tr_peerIo* tr_peerIoNewIncoming(tr_session* session, tr_bandwidth* parent, tr_address const* addr, tr_port port, tr_socket_t fd,
struct UTPSocket* utp_socket)
{
- assert(session);
+ assert(session != NULL);
assert(tr_address_is_valid(addr));
return tr_peerIoNew(session, parent, addr, port, NULL, true, false, fd, utp_socket);
tr_socket_t fd = TR_BAD_SOCKET;
struct UTPSocket* utp_socket = NULL;
- assert(session);
+ assert(session != NULL);
assert(tr_address_is_valid(addr));
- assert(torrentHash);
+ assert(torrentHash != NULL);
if (utp)
{
utp_socket = tr_netOpenPeerUTPSocket(session, addr, port, isSeed);
}
- if (!utp_socket)
+ if (utp_socket == NULL)
{
fd = tr_netOpenPeerSocket(session, addr, port, isSeed);
dbgmsg(NULL, "tr_netOpenPeerSocket returned fd %" PRIdMAX, (intmax_t)fd);
assert(event_initialized(io->event_write));
}
- if ((event & EV_READ) && !(io->pendingEvents & EV_READ))
+ if ((event & EV_READ) != 0 && (io->pendingEvents & EV_READ) == 0)
{
dbgmsg(io, "enabling ready-to-read polling");
io->pendingEvents |= EV_READ;
}
- if ((event & EV_WRITE) && !(io->pendingEvents & EV_WRITE))
+ if ((event & EV_WRITE) != 0 && (io->pendingEvents & EV_WRITE) == 0)
{
dbgmsg(io, "enabling ready-to-write polling");
assert(event_initialized(io->event_write));
}
- if ((event & EV_READ) && (io->pendingEvents & EV_READ))
+ if ((event & EV_READ) != 0 && (io->pendingEvents & EV_READ) != 0)
{
dbgmsg(io, "disabling ready-to-read polling");
io->pendingEvents &= ~EV_READ;
}
- if ((event & EV_WRITE) && (io->pendingEvents & EV_WRITE))
+ if ((event & EV_WRITE) != 0 && (io->pendingEvents & EV_WRITE) != 0)
{
dbgmsg(io, "disabling ready-to-write polling");
#ifdef WITH_UTP
- if (io->utp_socket)
+ if (io->utp_socket != NULL)
{
UTP_SetCallbacks(io->utp_socket, &dummy_utp_function_table, NULL);
UTP_Close(io->utp_socket);
static void tr_peerIoFree(tr_peerIo* io)
{
- if (io)
+ if (io != NULL)
{
dbgmsg(io, "in tr_peerIoFree");
io->canRead = NULL;
dbgmsg(io, "%s:%d is decrementing the IO's refcount from %d to %d", file, line, io->refCount, io->refCount - 1);
- if (!--io->refCount)
+ if (--io->refCount == 0)
{
tr_peerIoFree(io);
}
{
assert(tr_isPeerIo(io));
- if (port)
+ if (port != NULL)
{
*port = io->port;
}
{
int res = 0;
- if ((howmuch = tr_bandwidthClamp(&io->bandwidth, TR_DOWN, howmuch)))
+ if ((howmuch = tr_bandwidthClamp(&io->bandwidth, TR_DOWN, howmuch)) != 0)
{
if (io->utp_socket != NULL) /* utp peer connection */
{
res = evbuffer_read(io->inbuf, io->socket, (int)howmuch);
e = EVUTIL_SOCKET_ERROR();
- dbgmsg(io, "read %d from peer (%s)", res, (res == -1 ? tr_net_strerror(err_buf, sizeof(err_buf), e) : ""));
+ dbgmsg(io, "read %d from peer (%s)", res, res == -1 ? tr_net_strerror(err_buf, sizeof(err_buf), e) : "");
if (evbuffer_get_length(io->inbuf))
{
canReadWrapper(io);
}
- if ((res <= 0) && (io->gotError) && (e != EAGAIN) && (e != EINTR) && (e != EINPROGRESS))
+ if (res <= 0 && io->gotError != NULL && e != EAGAIN && e != EINTR && e != EINPROGRESS)
{
short what = BEV_EVENT_READING | BEV_EVENT_ERROR;
dbgmsg(io, "tr_peerIoTryRead got an error. res is %d, what is %hd, errno is %d (%s)", res, what, e,
tr_net_strerror(err_buf, sizeof(err_buf), e));
+
io->gotError(io, what, io->userData);
}
}
howmuch = old_len;
}
- if ((howmuch = tr_bandwidthClamp(&io->bandwidth, TR_UP, howmuch)))
+ if ((howmuch = tr_bandwidthClamp(&io->bandwidth, TR_UP, howmuch)) != 0)
{
if (io->utp_socket != NULL) /* utp peer connection */
{
didWriteWrapper(io, n);
}
- if ((n < 0) && (io->gotError) && e && (e != EPIPE) && (e != EAGAIN) && (e != EINTR) && (e != EINPROGRESS))
+ if (n < 0 && io->gotError != NULL && e != 0 && e != EPIPE && e != EAGAIN && e != EINTR && e != EINPROGRESS)
{
char errstr[512];
short const what = BEV_EVENT_WRITING | BEV_EVENT_ERROR;
dbgmsg(io, "tr_peerIoTryWrite got an error. res is %d, what is %hd, errno is %d (%s)", n, what, e,
tr_net_strerror(errstr, sizeof(errstr), e));
- if (io->gotError != NULL)
- {
- io->gotError(io, what, io->userData);
- }
+ io->gotError(io, what, io->userData);
}
}
}
static inline bool tr_isPeerIo(tr_peerIo const* io)
{
- return (io != NULL) && (io->magicNumber == PEER_IO_MAGIC_NUMBER) && (io->refCount >= 0) &&
- (tr_isBandwidth(&io->bandwidth)) && (tr_address_is_valid(&io->addr));
+ return io != NULL && io->magicNumber == PEER_IO_MAGIC_NUMBER && io->refCount >= 0 && tr_isBandwidth(&io->bandwidth) &&
+ tr_address_is_valid(&io->addr);
}
/**
static inline tr_session* tr_peerIoGetSession(tr_peerIo* io)
{
assert(tr_isPeerIo(io));
- assert(io->session);
+ assert(io->session != NULL);
return io->session;
}
static inline bool tr_peerIoIsEncrypted(tr_peerIo const* io)
{
- return (io != NULL) && (io->encryption_type == PEER_ENCRYPTION_RC4);
+ return io != NULL && io->encryption_type == PEER_ENCRYPTION_RC4;
}
void evbuffer_add_uint8(struct evbuffer* outbuf, uint8_t byte);
static bool tr_isAtom(struct peer_atom const* atom)
{
- return (atom != NULL) && (atom->fromFirst < TR_PEER_FROM__MAX) && (atom->fromBest < TR_PEER_FROM__MAX) &&
- (tr_address_is_valid(&atom->addr));
+ return atom != NULL && atom->fromFirst < TR_PEER_FROM__MAX && atom->fromBest < TR_PEER_FROM__MAX &&
+ tr_address_is_valid(&atom->addr);
}
#endif
static char const* tr_atomAddrStr(struct peer_atom const* atom)
{
- return atom ? tr_peerIoAddrStr(&atom->addr, atom->port) : "[no atom]";
+ return atom != NULL ? tr_peerIoAddrStr(&atom->addr, atom->port) : "[no atom]";
}
struct block_request
tr_bitfieldDestruct(&peer->have);
tr_bitfieldDestruct(&peer->blame);
- if (peer->atom)
+ if (peer->atom != NULL)
{
peer->atom->peer = NULL;
}
assert(swarmIsLocked(s));
- return (atom->peer != NULL) || getExistingHandshake(&s->outgoingHandshakes, &atom->addr) ||
+ return atom->peer != NULL || getExistingHandshake(&s->outgoingHandshakes, &atom->addr) ||
getExistingHandshake(&s->manager->incomingHandshakes, &atom->addr);
}
/* we cache whether or not a peer is blocklisted...
since the blocklist has changed, erase that cached value */
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
int i;
tr_swarm* s = tor->swarm;
tr_swarm const* s = tor->swarm;
struct peer_atom const* atom = getExistingAtom(s, addr);
- if (atom)
+ if (atom != NULL)
{
isSeed = atomIsSeed(atom);
}
{
struct peer_atom* atom = getExistingAtom(tor->swarm, addr);
- if (atom)
+ if (atom != NULL)
{
atom->flags |= ADDED_F_UTP_FLAGS;
}
{
struct peer_atom* atom = getExistingAtom(tor->swarm, addr);
- if (atom)
+ if (atom != NULL)
{
atom->utp_failed = failed;
}
{
/* we consider ourselves to be in endgame if the number of bytes
we've got requested is >= the number of bytes left to download */
- return ((uint64_t)s->requestCount * s->tor->blockSize) >= tr_torrentGetLeftUntilDone(s->tor);
+ return (uint64_t)s->requestCount * s->tor->blockSize >= tr_torrentGetLeftUntilDone(s->tor);
}
static void updateEndgame(tr_swarm* s)
/* not in endgame */
s->endgame = 0;
}
- else if (!s->endgame) /* only recalculate when endgame first begins */
+ else if (s->endgame == 0) /* only recalculate when endgame first begins */
{
int i;
int numDownloading = 0;
/* primary key: weight */
missing = tr_torrentMissingBlocksInPiece(tor, a->index);
pending = a->requestCount;
- ia = missing > pending ? missing - pending : (tor->blockCountInPiece + pending);
+ ia = missing > pending ? missing - pending : tor->blockCountInPiece + pending;
missing = tr_torrentMissingBlocksInPiece(tor, b->index);
pending = b->requestCount;
- ib = missing > pending ? missing - pending : (tor->blockCountInPiece + pending);
+ ib = missing > pending ? missing - pending : tor->blockCountInPiece + pending;
if (ia < ib)
{
static void assertWeightedPiecesAreSorted(Torrent* t)
{
- if (!t->endgame)
+ if (t->endgame == 0)
{
int i;
setComparePieceByWeightTorrent(t);
{
struct weighted_piece* p;
- if ((p = pieceListLookup(s, piece)))
+ if ((p = pieceListLookup(s, piece)) != NULL)
{
int const pos = p - s->pieces;
pos = p - s->pieces;
setComparePieceByWeightTorrent(s);
- if (isSorted && (pos > 0) && (comparePieceByWeight(p - 1, p) > 0))
+ if (isSorted && pos > 0 && comparePieceByWeight(p - 1, p) > 0)
{
isSorted = false;
}
- if (isSorted && (pos < s->pieceCount - 1) && (comparePieceByWeight(p, p + 1) > 0))
+ if (isSorted && pos < s->pieceCount - 1 && comparePieceByWeight(p, p + 1) > 0)
{
isSorted = false;
}
struct weighted_piece* p;
tr_piece_index_t const index = tr_torBlockPiece(s->tor, block);
- if (((p = pieceListLookup(s, index))) && (p->requestCount > 0))
+ if ((p = pieceListLookup(s, index)) != NULL && p->requestCount > 0)
{
--p->requestCount;
pieceListResortPiece(s, p);
if (peerCount != 0)
{
/* don't make a second block request until the endgame */
- if (!s->endgame)
+ if (s->endgame == 0)
{
continue;
}
}
/* if intervals are requested two array entries are necessarry:
one for the interval's starting block and one for its end block */
- else if (got && setme[2 * got - 1] == b - 1 && b != first)
+ else if (got != 0 && setme[2 * got - 1] == b - 1 && b != first)
{
/* expand the last interval */
++setme[2 * got - 1];
/* alloc the temporary "cancel" buffer */
tor = NULL;
- while ((tor = tr_torrentNext(mgr->session, tor)))
+ while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
{
cancel_buflen = MAX(cancel_buflen, tor->swarm->requestCount);
}
/* prune requests that are too old */
tor = NULL;
- while ((tor = tr_torrentNext(mgr->session, tor)))
+ while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
{
tr_swarm* s = tor->swarm;
int const n = s->requestCount;
{
tr_peerMsgs* msgs = PEER_MSGS(it->peer);
- if ((msgs != NULL) && (it->sentAt <= too_old) && !tr_peerMsgsIsReadingBlock(msgs, it->block))
+ if (msgs != NULL && it->sentAt <= too_old && !tr_peerMsgsIsReadingBlock(msgs, it->block))
{
cancel[cancelCount++] = *it;
}
{
tr_peer* p = peers[i];
- if ((p != no_notify) && tr_isPeerMsgs(p))
+ if (p != no_notify && tr_isPeerMsgs(p))
{
tr_historyAdd(&p->cancelsSentToPeer, tr_time(), 1);
tr_peerMsgsCancel(PEER_MSGS(p), block);
break;
case TR_PEER_CLIENT_GOT_PORT:
- if (peer->atom)
+ if (peer->atom != NULL)
{
peer->atom->port = e->port;
}
}
case TR_PEER_ERROR:
- if ((e->err == ERANGE) || (e->err == EMSGSIZE) || (e->err == ENOTCONN))
+ if (e->err == ERANGE || e->err == EMSGSIZE || e->err == ENOTCONN)
{
/* some protocol error from the peer */
peer->doPurge = true;
tr_peerMgr* manager = vmanager;
tr_swarm* s;
- assert(io);
+ assert(io != NULL);
assert(tr_isBool(ok));
s = tr_peerIoHasTorrentHash(io) ? getExistingSwarm(manager, tr_peerIoGetTorrentHash(io)) : NULL;
{
tr_ptrArrayRemoveSortedPointer(&manager->incomingHandshakes, handshake, handshakeCompare);
}
- else if (s)
+ else if (s != NULL)
{
tr_ptrArrayRemoveSortedPointer(&s->outgoingHandshakes, handshake, handshakeCompare);
}
- if (s)
+ if (s != NULL)
{
swarmLock(s);
}
addr = tr_peerIoGetAddress(io, &port);
- if (!ok || !s || !s->isRunning)
+ if (!ok || s == NULL || !s->isRunning)
{
- if (s)
+ if (s != NULL)
{
struct peer_atom* atom = getExistingAtom(s, addr);
- if (atom)
+ if (atom != NULL)
{
++atom->numFails;
/* In principle, this flag specifies whether the peer groks uTP,
not whether it's currently connected over uTP. */
- if (io->utp_socket)
+ if (io->utp_socket != NULL)
{
atom->flags |= ADDED_F_UTP_FLAGS;
}
- if (atom->flags2 & MYFLAG_BANNED)
+ if ((atom->flags2 & MYFLAG_BANNED) != 0)
{
tordbg(s, "banned peer %s tried to reconnect", tr_atomAddrStr(atom));
}
- else if (tr_peerIoIsIncoming(io) && (getPeerCount(s) >= getMaxPeerCount(s->tor)))
+ else if (tr_peerIoIsIncoming(io) && getPeerCount(s) >= getMaxPeerCount(s->tor))
{
}
else
{
tr_peer* peer = atom->peer;
- if (peer)
+ if (peer != NULL)
{
/* we already have this peer */
}
UTP_Close(utp_socket);
}
}
- else if (getExistingHandshake(&manager->incomingHandshakes, addr))
+ else if (getExistingHandshake(&manager->incomingHandshakes, addr) != NULL)
{
if (socket != TR_BAD_SOCKET)
{
memcpy(&pex[i].port, walk, 2);
walk += 2;
- if (added_f && (n == added_f_len))
+ if (added_f != NULL && n == added_f_len)
{
pex[i].flags = added_f[i];
}
memcpy(&pex[i].port, walk, 2);
walk += 2;
- if (added_f && (n == added_f_len))
+ if (added_f != NULL && n == added_f_len)
{
pex[i].flags = added_f[i];
}
assert(tr_isPex(a));
assert(tr_isPex(b));
- if ((i = tr_address_compare(&a->addr, &b->addr)))
+ if ((i = tr_address_compare(&a->addr, &b->addr)) != 0)
{
return i;
}
return false;
}
- if (atom->flags2 & MYFLAG_BANNED)
+ if ((atom->flags2 & MYFLAG_BANNED) != 0)
{
return false;
}
peer->progress = 1.0;
}
- if (peer->atom && (peer->progress >= 1.0))
+ if (peer->atom != NULL && peer->progress >= 1.0)
{
atomSetSeed(tor->swarm, peer->atom);
}
{
tab[i] = -1;
}
- else if (peerCount)
+ else if (peerCount != 0)
{
int j;
return true;
}
- if (peer->atom && atomIsSeed(peer->atom))
+ if (peer->atom != NULL && atomIsSeed(peer->atom))
{
return true;
}
}
}
- if (!s->pieceReplication || !s->pieceReplicationSize)
+ if (s->pieceReplication == NULL || s->pieceReplicationSize == 0)
{
return 0;
}
for (i = 0, n = MIN(tor->info.pieceCount, s->pieceReplicationSize); i < n; ++i)
{
- if (!tor->info.pieces[i].dnd && (s->pieceReplication[i] > 0))
+ if (!tor->info.pieces[i].dnd && s->pieceReplication[i] > 0)
{
desiredAvailable += tr_torrentMissingBytesInPiece(tor, i);
}
timeSinceCancel = now - s->lastCancel;
- if (timeSinceCancel)
+ if (timeSinceCancel != 0)
{
int const maxIncrease = 15;
time_t const maxHistory = 2 * CANCEL_HISTORY_SEC;
int const blocks = tr_historyGet(&peer->blocksSentToClient, now, CANCEL_HISTORY_SEC);
int const cancels = tr_historyGet(&peer->cancelsSentToPeer, now, CANCEL_HISTORY_SEC);
- if (!blocks && !cancels)
+ if (blocks == 0 && cancels == 0)
{
rechoke_state = RECHOKE_STATE_UNTESTED;
}
- else if (!cancels)
+ else if (cancels == 0)
{
rechoke_state = RECHOKE_STATE_GOOD;
}
- else if (!blocks)
+ else if (blocks == 0)
{
rechoke_state = RECHOKE_STATE_BAD;
}
- else if ((cancels * 10) < blocks)
+ else if (cancels * 10 < blocks)
{
rechoke_state = RECHOKE_STATE_GOOD;
}
/* is this a new connection? */
static bool isNew(tr_peerMsgs const* msgs)
{
- return (msgs != NULL) && (tr_peerMsgsGetConnectionAge(msgs) < 45);
+ return msgs != NULL && tr_peerMsgsGetConnectionAge(msgs) < 45;
}
/* get a rate for deciding which peers to choke and unchoke. */
}
/* optimistic unchoke */
- if (!s->optimistic && !isMaxedOut && (i < size))
+ if (s->optimistic == NULL && !isMaxedOut && i < size)
{
int n;
struct ChokeData* c;
}
}
- if ((n = tr_ptrArraySize(&randPool)))
+ if ((n = tr_ptrArraySize(&randPool)) != 0)
{
c = tr_ptrArrayNth(&randPool, tr_rand_int_weak(n));
c->isChoked = false;
managerLock(mgr);
- while ((tor = tr_torrentNext(mgr->session, tor)))
+ while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
{
if (tor->isRunning)
{
/* disconnect if we're both seeds and enough time has passed for PEX */
if (tr_torrentIsSeed(tor) && tr_peerIsSeed(peer))
{
- return !tr_torrentAllowsPex(tor) || (now - atom->time >= 30);
+ return !tr_torrentAllowsPex(tor) || now - atom->time >= 30;
}
/* disconnect if it's been too long since piece data has been transferred.
/* if we were recently connected to this peer and transferring piece
* data, try to reconnect to them sooner rather that later -- we don't
* want network troubles to get in the way of a good peer. */
- if (!unreachable && ((now - atom->piece_data_time) <= (MINIMUM_RECONNECT_INTERVAL_SECS * 2)))
+ if (!unreachable && now - atom->piece_data_time <= MINIMUM_RECONNECT_INTERVAL_SECS * 2)
{
sec = MINIMUM_RECONNECT_INTERVAL_SECS;
}
struct peer_atom* atom = peer->atom;
assert(swarmIsLocked(s));
- assert(atom);
+ assert(atom != NULL);
atom->time = tr_time();
l->time = p->atom->time;
l->speed = tr_peerGetPieceSpeed_Bps(p, now, TR_UP) + tr_peerGetPieceSpeed_Bps(p, now, TR_DOWN);
- if (clientData)
+ if (clientData != NULL)
{
l->clientData = clientData[i];
}
}
/* sort 'em */
- assert(n == (l - lives));
+ assert(n == l - lives);
qsort(lives, n, sizeof(struct peer_liveliness), compare);
/* build the peer array */
{
peers[i] = l->peer;
- if (clientData)
+ if (clientData != NULL)
{
clientData[i] = l->clientData;
}
}
- assert(n == (l - lives));
+ assert(n == l - lives);
/* cleanup */
tr_free(lives);
int const max = tr_sessionGetPeerLimit(session);
/* count the total number of peers */
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
n += tr_ptrArraySize(&tor->swarm->peers);
}
n = 0;
tor = NULL;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
int i;
tr_swarm* s = tor->swarm;
/* if we're over the per-torrent peer limits, cull some peers */
tor = NULL;
- while ((tor = tr_torrentNext(mgr->session, tor)))
+ while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
{
if (tor->isRunning)
{
/* remove crappy peers */
tor = NULL;
- while ((tor = tr_torrentNext(mgr->session, tor)))
+ while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
{
if (!tor->swarm->isRunning)
{
{
tr_torrent* tor = NULL;
- while ((tor = tr_torrentNext(mgr->session, tor)))
+ while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
{
int j;
tr_swarm* s = tor->swarm;
/* torrent upkeep */
tor = NULL;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
/* possibly stop torrents that have seeded enough */
tr_torrentCheckSeedLimit(tor);
tr_peerMgr* mgr = vmgr;
managerLock(mgr);
- while ((tor = tr_torrentNext(mgr->session, tor)))
+ while ((tor = tr_torrentNext(mgr->session, tor)) != NULL)
{
int atomCount;
tr_swarm* s = tor->swarm;
}
/* not if we just tried them already */
- if ((now - atom->time) < getReconnectIntervalSecs(atom, now))
+ if (now - atom->time < getReconnectIntervalSecs(atom, now))
{
return false;
}
}
/* not if they're banned... */
- if (atom->flags2 & MYFLAG_BANNED)
+ if ((atom->flags2 & MYFLAG_BANNED) != 0)
{
return false;
}
score = addValToKey(score, 1, i);
/* prefer peers that are known to be connectible */
- i = (atom->flags & ADDED_F_CONNECTABLE) ? 0 : 1;
+ i = (atom->flags & ADDED_F_CONNECTABLE) != 0 ? 0 : 1;
score = addValToKey(score, 1, i);
/* prefer peers that we might have a chance of uploading to...
atomCount = 0;
peerCount = 0;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
atomCount += tr_ptrArraySize(&tor->swarm->pool);
peerCount += tr_ptrArraySize(&tor->swarm->peers);
/* populate the candidate array */
tor = NULL;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
int i, nAtoms;
struct peer_atom** atoms;
/* PEX has explicit signalling for uTP support. If an atom
originally came from PEX and doesn't have the uTP flag, skip the
uTP connection attempt. Are we being optimistic here? */
- utp = utp && (atom->flags & ADDED_F_UTP_FLAGS);
+ utp = utp && (atom->flags & ADDED_F_UTP_FLAGS) != 0;
}
tordbg(s, "Starting an OUTGOING%s connection with %s", utp ? " µTP" : "", tr_atomAddrStr(atom));
{
size_t setSize = 0;
- assert(setmePieces);
+ assert(setmePieces != NULL);
assert(desiredSetSize <= pieceCount);
- assert(desiredSetSize);
- assert(pieceCount);
- assert(infohash);
- assert(addr);
+ assert(desiredSetSize != 0);
+ assert(pieceCount != 0);
+ assert(infohash != NULL);
+ assert(addr != NULL);
if (addr->type == TR_AF_INET)
{
static void updateFastSet(tr_peerMsgs* msgs UNUSED)
{
bool const fext = tr_peerIoSupportsFEXT(msgs->io);
- int const peerIsNeedy = msgs->peer->progress < 0.10;
+ bool const peerIsNeedy = msgs->peer->progress < 0.10;
if (fext && peerIsNeedy && !msgs->haveFastSet)
{
{
struct evbuffer* out = msgs->outMessages;
- assert(msgs);
+ assert(msgs != NULL);
assert(tr_isBool(b));
msgs->client_is_interested = b;
static void cancelAllRequestsToClient(tr_peerMsgs* msgs)
{
struct peer_request req;
- int const mustSendCancel = tr_peerIoSupportsFEXT(msgs->io);
+ bool const mustSendCancel = tr_peerIoSupportsFEXT(msgs->io);
while (popNextRequest(msgs, &req))
{
return;
}
- if (!version_quark)
+ if (version_quark == 0)
{
version_quark = tr_quark_new(TR_NAME " " USERAGENT_PREFIX, TR_BAD_SIZE);
}
tr_variantDictAddRaw(&val, TR_KEY_ipv6, ipv6, 16);
}
- if (allow_metadata_xfer && tr_torrentHasMetadata(msgs->torrent) && (msgs->torrent->infoDictLength > 0))
+ if (allow_metadata_xfer && tr_torrentHasMetadata(msgs->torrent) && msgs->torrent->infoDictLength > 0)
{
tr_variantDictAddInt(&val, TR_KEY_metadata_size, msgs->torrent->infoDictLength);
}
tr_peerIoReadBytes(msgs->io, inbuf, tmp, len);
msgs->peerSentLtepHandshake = true;
- if (tr_variantFromBenc(&val, tmp, len) || !tr_variantIsDict(&val))
+ if (tr_variantFromBenc(&val, tmp, len) != 0 || !tr_variantIsDict(&val))
{
dbgmsg(msgs, "GET extended-handshake, couldn't get dictionary");
tr_free(tmp);
/* does the peer prefer encrypted connections? */
if (tr_variantDictFindInt(&val, TR_KEY_e, &i))
{
- msgs->encryption_preference = i ? ENCRYPTION_PREFERENCE_YES : ENCRYPTION_PREFERENCE_NO;
+ msgs->encryption_preference = i != 0 ? ENCRYPTION_PREFERENCE_YES : ENCRYPTION_PREFERENCE_NO;
- if (i)
+ if (i != 0)
{
pex.flags |= ADDED_F_ENCRYPTION_FLAG;
}
dbgmsg(msgs, "peer's port is now %d", (int)i);
}
- if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv4, &addr, &addr_len) && (addr_len == 4))
+ if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv4, &addr, &addr_len) && addr_len == 4)
{
pex.addr.type = TR_AF_INET;
memcpy(&pex.addr.addr.addr4, addr, 4);
tr_peerMgrAddPex(msgs->torrent, TR_PEER_FROM_LTEP, &pex, seedProbability);
}
- if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv6, &addr, &addr_len) && (addr_len == 16))
+ if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv6, &addr, &addr_len) && addr_len == 16)
{
pex.addr.type = TR_AF_INET6;
memcpy(&pex.addr.addr.addr6, addr, 16);
tr_peerIoReadBytes(msgs->io, inbuf, tmp, msglen);
msg_end = (char*)tmp + msglen;
- if (!tr_variantFromBencFull(&dict, tmp, msglen, NULL, &benc_end))
+ if (tr_variantFromBencFull(&dict, tmp, msglen, NULL, &benc_end) == 0)
{
tr_variantDictFindInt(&dict, TR_KEY_msg_type, &msg_type);
tr_variantDictFindInt(&dict, TR_KEY_piece, &piece);
/* NOOP */
}
- if ((msg_type == METADATA_MSG_TYPE_DATA) && (!tr_torrentHasMetadata(msgs->torrent)) &&
- (msg_end - benc_end <= METADATA_PIECE_SIZE) && (piece * METADATA_PIECE_SIZE + (msg_end - benc_end) <= total_size))
+ if (msg_type == METADATA_MSG_TYPE_DATA && !tr_torrentHasMetadata(msgs->torrent) &&
+ msg_end - benc_end <= METADATA_PIECE_SIZE && piece * METADATA_PIECE_SIZE + (msg_end - benc_end) <= total_size)
{
int const pieceLen = msg_end - benc_end;
tr_torrentSetMetadataPiece(msgs->torrent, piece, benc_end, pieceLen);
if (msg_type == METADATA_MSG_TYPE_REQUEST)
{
- if ((piece >= 0) && tr_torrentHasMetadata(msgs->torrent) && !tr_torrentIsPrivate(msgs->torrent) &&
- (msgs->peerAskedForMetadataCount < METADATA_REQQ))
+ if (piece >= 0 && tr_torrentHasMetadata(msgs->torrent) && !tr_torrentIsPrivate(msgs->torrent) &&
+ msgs->peerAskedForMetadataCount < METADATA_REQQ)
{
msgs->peerAskedForMetadata[msgs->peerAskedForMetadataCount++] = piece;
}
static void parseUtPex(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbuf)
{
- int loaded = 0;
+ bool loaded = false;
uint8_t* tmp = tr_new(uint8_t, msglen);
tr_variant val;
tr_torrent* tor = msgs->torrent;
tr_peerIoReadBytes(msgs->io, inbuf, tmp, msglen);
- if (tr_torrentAllowsPex(tor) && ((loaded = !tr_variantFromBenc(&val, tmp, msglen))))
+ if (tr_torrentAllowsPex(tor) && (loaded = tr_variantFromBenc(&val, tmp, msglen) == 0))
{
if (tr_variantDictFindRaw(&val, TR_KEY_added, &added, &added_len))
{
if (i < added_f_len)
{
- seedProbability = (added_f[i] & ADDED_F_SEED_FLAG) ? 100 : 0;
+ seedProbability = (added_f[i] & ADDED_F_SEED_FLAG) != 0 ? 100 : 0;
}
tr_peerMgrAddPex(tor, TR_PEER_FROM_PEX, pex + i, seedProbability);
if (i < added_f_len)
{
- seedProbability = (added_f[i] & ADDED_F_SEED_FLAG) ? 100 : 0;
+ seedProbability = (added_f[i] & ADDED_F_SEED_FLAG) != 0 ? 100 : 0;
}
tr_peerMgrAddPex(tor, TR_PEER_FROM_PEX, pex + i, seedProbability);
static void peerMadeRequest(tr_peerMsgs* msgs, struct peer_request const* req)
{
bool const fext = tr_peerIoSupportsFEXT(msgs->io);
- int const reqIsValid = requestIsValid(msgs, req);
- int const clientHasPiece = reqIsValid && tr_torrentPieceIsComplete(msgs->torrent, req->index);
- int const peerIsChoked = msgs->peer_is_choked;
+ bool const reqIsValid = requestIsValid(msgs, req);
+ bool const clientHasPiece = reqIsValid && tr_torrentPieceIsComplete(msgs->torrent, req->index);
+ bool const peerIsChoked = msgs->peer_is_choked;
bool allow = false;
case BT_BITFIELD:
if (tr_torrentHasMetadata(msg->torrent))
{
- return len == (msg->torrent->info.pieceCount >> 3) + (msg->torrent->info.pieceCount & 7 ? 1 : 0) + 1u;
+ return len == (msg->torrent->info.pieceCount >> 3) + ((msg->torrent->info.pieceCount & 7) != 0 ? 1 : 0) + 1u;
}
/* we don't know the piece count yet,
assert(evbuffer_get_length(inbuf) >= inlen);
dbgmsg(msgs, "In readBtPiece");
- if (!req->length)
+ if (req->length == 0)
{
if (inlen < 8)
{
/* cleanup */
req->length = 0;
msgs->state = AWAITING_BT_LENGTH;
- return err ? READ_ERR : READ_NOW;
+ return err != 0 ? READ_ERR : READ_NOW;
}
}
tr_peerIoReadUint32(msgs->io, inbuf, &ui32);
dbgmsg(msgs, "got Have: %u", ui32);
- if (tr_torrentHasMetadata(msgs->torrent) && (ui32 >= msgs->torrent->info.pieceCount))
+ if (tr_torrentHasMetadata(msgs->torrent) && ui32 >= msgs->torrent->info.pieceCount)
{
fireError(msgs, ERANGE);
return READ_ERR;
{
struct peer_request const* req = msgs->peerAskedFor + i;
- if ((req->index == r.index) && (req->offset == r.offset) && (req->length == r.length))
+ if (req->index == r.index && req->offset == r.offset && req->length == r.length)
{
break;
}
*** Save the block
**/
- if ((err = tr_cacheWriteBlock(getSession(msgs)->cache, tor, req->index, req->offset, req->length, data)))
+ if ((err = tr_cacheWriteBlock(getSession(msgs)->cache, tor, req->index, req->offset, req->length, data)) != 0)
{
return err;
}
firePeerGotPieceData(msgs, bytesWritten);
}
- if (tr_isPeerIo(io) && io->userData)
+ if (tr_isPeerIo(io) && io->userData != NULL)
{
peerPulse(msgs);
}
dbgmsg(msgs, "canRead: inlen is %zu, msgs->state is %d", inlen, msgs->state);
- if (!inlen)
+ if (inlen == 0)
{
ret = READ_LATER;
}
static void updateBlockRequests(tr_peerMsgs* msgs)
{
- if (tr_torrentIsPieceTransferAllowed(msgs->torrent, TR_PEER_TO_CLIENT) && (msgs->desiredRequestCount > 0) &&
- (msgs->peer.pendingReqsToPeer <= (msgs->desiredRequestCount * 0.66)))
+ if (tr_torrentIsPieceTransferAllowed(msgs->torrent, TR_PEER_TO_CLIENT) && msgs->desiredRequestCount > 0 &&
+ msgs->peer.pendingReqsToPeer <= msgs->desiredRequestCount * 0.66)
{
int i;
int n;
*** Protocol messages
**/
- if (haveMessages && !msgs->outMessagesBatchedAt) /* fresh batch */
+ if (haveMessages && msgs->outMessagesBatchedAt == 0) /* fresh batch */
{
dbgmsg(msgs, "started an outMessages batch (length is %zu)", evbuffer_get_length(msgs->outMessages));
msgs->outMessagesBatchedAt = now;
}
- else if (haveMessages && ((now - msgs->outMessagesBatchedAt) >= msgs->outMessagesBatchPeriod))
+ else if (haveMessages && now - msgs->outMessagesBatchedAt >= msgs->outMessagesBatchPeriod)
{
size_t const len = evbuffer_get_length(msgs->outMessages);
/* flush the protocol messages */
*** Metadata Pieces
**/
- if ((tr_peerIoGetWriteBufferSpace(msgs->io, now) >= METADATA_PIECE_SIZE) && popNextMetadataRequest(msgs, &piece))
+ if (tr_peerIoGetWriteBufferSpace(msgs->io, now) >= METADATA_PIECE_SIZE && popNextMetadataRequest(msgs, &piece))
{
char* data;
size_t dataLen;
*** Data Blocks
**/
- if ((tr_peerIoGetWriteBufferSpace(msgs->io, now) >= msgs->torrent->blockSize) && popNextRequest(msgs, &req))
+ if (tr_peerIoGetWriteBufferSpace(msgs->io, now) >= msgs->torrent->blockSize && popNextRequest(msgs, &req))
{
--msgs->prefetchCount;
evbuffer_commit_space(out, iovec, 1);
/* check the piece if it needs checking... */
- if (!err && tr_torrentPieceNeedsCheck(msgs->torrent, req.index))
+ if (err == 0 && tr_torrentPieceNeedsCheck(msgs->torrent, req.index))
{
- if ((err = !tr_torrentCheckPiece(msgs->torrent, req.index)))
+ if ((err = !tr_torrentCheckPiece(msgs->torrent, req.index)) != 0)
{
tr_torrentSetLocalError(msgs->torrent, _("Please Verify Local Data! Piece #%zu is corrupt."),
(size_t)req.index);
}
}
- if (err)
+ if (err != 0)
{
if (fext)
{
evbuffer_free(out);
- if (err)
+ if (err != 0)
{
bytesWritten = 0;
msgs = NULL;
*** Keepalive
**/
- if ((msgs != NULL) && (msgs->clientSentAnythingAt != 0) && ((now - msgs->clientSentAnythingAt) > KEEPALIVE_INTERVAL_SECS))
+ if (msgs != NULL && msgs->clientSentAnythingAt != 0 && now - msgs->clientSentAnythingAt > KEEPALIVE_INTERVAL_SECS)
{
dbgmsg(msgs, "sending a keepalive message");
evbuffer_add_uint32(msgs->outMessages, 0);
static void gotError(tr_peerIo* io UNUSED, short what, void* vmsgs)
{
- if (what & BEV_EVENT_TIMEOUT)
+ if ((what & BEV_EVENT_TIMEOUT) != 0)
{
dbgmsg(vmsgs, "libevent got a timeout, what=%hd", what);
}
- if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
+ if ((what & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) != 0)
{
dbgmsg(vmsgs, "libevent got an error! what=%hd, errno=%d (%s)", what, errno, tr_strerror(errno));
}
{
int const val = (*compare)(a, b);
- if (!val)
+ if (val == 0)
{
(*in_both_cb)((void*)a, userData);
a += elementSize;
dbgmsg(msgs, "pex: old peer count %d+%d, new peer count %d+%d, added %d+%d, removed %d+%d", msgs->pexCount,
msgs->pexCount6, newCount, newCount6, diffs.addedCount, diffs6.addedCount, diffs.droppedCount, diffs6.droppedCount);
- if (!diffs.addedCount && !diffs.droppedCount && !diffs6.addedCount && !diffs6.droppedCount)
+ if (diffs.addedCount == 0 && diffs.droppedCount == 0 && diffs6.addedCount == 0 && diffs6.droppedCount == 0)
{
tr_free(diffs.elements);
tr_free(diffs6.elements);
walk += 2;
}
- assert((walk - tmp) == diffs.addedCount * 6);
+ assert(walk - tmp == diffs.addedCount * 6);
tr_variantDictAddRaw(&val, TR_KEY_added, tmp, walk - tmp);
tr_free(tmp);
*walk++ = diffs.added[i].flags & ~ADDED_F_HOLEPUNCH;
}
- assert((walk - tmp) == diffs.addedCount);
+ assert(walk - tmp == diffs.addedCount);
tr_variantDictAddRaw(&val, TR_KEY_added_f, tmp, walk - tmp);
tr_free(tmp);
}
walk += 2;
}
- assert((walk - tmp) == diffs.droppedCount * 6);
+ assert(walk - tmp == diffs.droppedCount * 6);
tr_variantDictAddRaw(&val, TR_KEY_dropped, tmp, walk - tmp);
tr_free(tmp);
}
walk += 2;
}
- assert((walk - tmp) == diffs6.addedCount * 18);
+ assert(walk - tmp == diffs6.addedCount * 18);
tr_variantDictAddRaw(&val, TR_KEY_added6, tmp, walk - tmp);
tr_free(tmp);
*walk++ = diffs6.added[i].flags & ~ADDED_F_HOLEPUNCH;
}
- assert((walk - tmp) == diffs6.addedCount);
+ assert(walk - tmp == diffs6.addedCount);
tr_variantDictAddRaw(&val, TR_KEY_added6_f, tmp, walk - tmp);
tr_free(tmp);
}
walk += 2;
}
- assert((walk - tmp) == diffs6.droppedCount * 18);
+ assert(walk - tmp == diffs6.droppedCount * 18);
tr_variantDictAddRaw(&val, TR_KEY_dropped6, tmp, walk - tmp);
tr_free(tmp);
}
evbuffer_free(msgs->incoming.block);
}
- if (msgs->io)
+ if (msgs->io != NULL)
{
tr_peerIoClear(msgs->io);
tr_peerIoUnref(msgs->io); /* balanced by the ref in handshakeDoneCB() */
bool tr_isPeerMsgs(void const* msgs)
{
/* FIXME: this is pretty crude */
- return (msgs != NULL) && (((struct tr_peerMsgs*)msgs)->magic_number == MAGIC_NUMBER);
+ return msgs != NULL && ((struct tr_peerMsgs*)msgs)->magic_number == MAGIC_NUMBER;
}
tr_peerMsgs* tr_peerMsgsCast(void* vm)
}
endmntent(fp);
- return mnt ? mnt->mnt_fsname : NULL;
+ return mnt != NULL ? mnt->mnt_fsname : NULL;
#endif
n = getmntinfo(&mnt, MNT_WAIT);
- if (!n)
+ if (n == 0)
{
return NULL;
}
}
}
- return (i < n) ? mnt[i].f_mntfromname : NULL;
+ return i < n ? mnt[i].f_mntfromname : NULL;
#endif
}
}
endmntent(fp);
- return mnt ? mnt->mnt_type : NULL;
+ return mnt != NULL ? mnt->mnt_type : NULL;
#endif
n = getmntinfo(&mnt, MNT_WAIT);
- if (!n)
+ if (n == 0)
{
return NULL;
}
}
}
- return (i < n) ? mnt[i].f_fstypename : NULL;
+ return i < n ? mnt[i].f_fstypename : NULL;
#endif
}
return device;
}
-#if defined(__NetBSD__) && (__NetBSD_Version__ >= 600000000)
+#if defined(__NetBSD__) && __NetBSD_Version__ >= 600000000
#include <quota.h>
quota_close(qh);
freespace = limit - spaceused;
- return (freespace < 0) ? 0 : freespace;
+ return freespace < 0 ? 0 : freespace;
}
#else
freespace = limit - spaceused;
#ifdef __APPLE__
- return (freespace < 0) ? 0 : freespace;
+ return freespace < 0 ? 0 : freespace;
#else
- return (freespace < 0) ? 0 : freespace * 1024;
+ return freespace < 0 ? 0 : freespace * 1024;
#endif
}
}
freespace = limit - (dq.d_bcount >> 1);
- return (freespace < 0) ? 0 : freespace * 1024;
+ return freespace < 0 ? 0 : freespace * 1024;
}
/* something went wrong */
#ifndef _WIN32
- if (info->fstype && !evutil_ascii_strcasecmp(info->fstype, "xfs"))
+ if (info->fstype != NULL && evutil_ascii_strcasecmp(info->fstype, "xfs") == 0)
{
#ifdef HAVE_XQM
ret = getxfsquota(info->device);
{
int64_t free_space;
- if ((info == NULL) || (info->path == NULL))
+ if (info == NULL || info->path == NULL)
{
errno = EINVAL;
free_space = -1;
#endif
assert(l->depth >= 0);
- assert(!l->depth || tr_areThreadsEqual(l->lockThread, tr_getCurrentThread()));
+ assert(l->depth == 0 || tr_areThreadsEqual(l->lockThread, tr_getCurrentThread()));
l->lockThread = tr_getCurrentThread();
++l->depth;
}
bool tr_lockHave(tr_lock const* l)
{
- return (l->depth > 0) && (tr_areThreadsEqual(l->lockThread, tr_getCurrentThread()));
+ return l->depth > 0 && tr_areThreadsEqual(l->lockThread, tr_getCurrentThread());
}
void tr_lockUnlock(tr_lock* l)
{
static char* home = NULL;
- if (!home)
+ if (home == NULL)
{
home = tr_env_get_string("HOME", NULL);
- if (!home)
+ if (home == NULL)
{
#ifdef _WIN32
struct passwd* pw = getpwuid(getuid());
- if (pw)
+ if (pw != NULL)
{
home = tr_strdup(pw->pw_dir);
}
#endif
}
- if (!home)
+ if (home == NULL)
{
home = tr_strdup("");
}
{
static char* s = NULL;
- if (!appname || !*appname)
+ if (appname == NULL || *appname == '\0')
{
appname = "Transmission";
}
- if (!s)
+ if (s == NULL)
{
s = tr_env_get_string("TRANSMISSION_HOME", NULL);
/* figure out where to look for user-dirs.dirs */
config_home = tr_env_get_string("XDG_CONFIG_HOME", NULL);
- if (config_home && *config_home)
+ if (config_home != NULL && *config_home != '\0')
{
config_file = tr_buildPath(config_home, "user-dirs.dirs", NULL);
}
/* read in user-dirs.dirs and look for the download dir entry */
content = (char*)tr_loadFile(config_file, &content_len, NULL);
- if (content && content_len > 0)
+ if (content != NULL && content_len > 0)
{
char const* key = "XDG_DOWNLOAD_DIR=\"";
char* line = strstr(content, key);
char* value = line + strlen(key);
char* end = strchr(value, '"');
- if (end)
+ if (end != NULL)
{
*end = '\0';
{
static char* s = NULL;
- if (!s)
+ if (s == NULL)
{
s = tr_env_get_string("CLUTCH_HOME", NULL);
/* XDG_DATA_HOME should be the first in the list of candidates */
tmp = tr_env_get_string("XDG_DATA_HOME", NULL);
- if (tmp && *tmp)
+ if (tmp != NULL && *tmp != '\0')
{
tr_list_append(&candidates, tmp);
}
tr_free(xdg);
tmp = buf;
- while (tmp && *tmp)
+ while (tmp != NULL && *tmp != '\0')
{
char const* end = strchr(tmp, ':');
- if (end)
+ if (end != NULL)
{
- if ((end - tmp) > 1)
+ if (end - tmp > 1)
{
tr_list_append(&candidates, tr_strndup(tmp, (size_t)(end - tmp)));
}
tmp = (char*)end + 1;
}
- else if (tmp && *tmp)
+ else if (tmp != NULL && *tmp != '\0')
{
tr_list_append(&candidates, tr_strdup(tmp));
break;
}
/* walk through the candidates & look for a match */
- for (l = candidates; l; l = l->next)
+ for (l = candidates; l != NULL; l = l->next)
{
char* path = tr_buildPath(l->data, "transmission", "web", NULL);
- int const found = isWebClientDir(path);
+ bool const found = isWebClientDir(path);
if (found)
{
int newStatus;
tr_port public_peer_port;
tr_port const private_peer_port = s->session->private_peer_port;
- int const is_enabled = s->isEnabled && !s->isShuttingDown;
+ bool const is_enabled = s->isEnabled && !s->isShuttingDown;
if (s->natpmp == NULL)
{
{
tr_shared* s = vshared;
- assert(s);
- assert(s->timer);
+ assert(s != NULL);
+ assert(s->timer != NULL);
/* do something */
natPulse(s, s->doPortCheck);
void tr_ptrArrayDestruct(tr_ptrArray* p, PtrArrayForeachFunc func)
{
assert(p != NULL);
- assert(p->items || !p->n_items);
+ assert(p->items != NULL || p->n_items == 0);
- if (func)
+ if (func != NULL)
{
tr_ptrArrayForeach(p, func);
}
{
int i;
- assert(t);
- assert(t->items || !t->n_items);
- assert(func);
+ assert(t != NULL);
+ assert(t->items != NULL || t->n_items == 0);
+ assert(func != NULL);
for (i = 0; i < t->n_items; ++i)
{
{
void* ret = NULL;
- if (t->n_items)
+ if (t->n_items != 0)
{
ret = t->items[--t->n_items];
}
assert(compare(t->items[pos - 1], t->items[pos]) < 0);
}
- if ((pos + 1) < t->n_items)
+ if (pos + 1 < t->n_items)
{
assert(compare(t->items[pos], t->items[pos + 1]) < 0);
}
@return the nth item in a tr_ptrArray */
static inline void* tr_ptrArrayNth(tr_ptrArray* array, int i)
{
- assert(array);
+ assert(array != NULL);
assert(i >= 0);
assert(i < array->n_items);
/* create the torrent */
err = 0;
tor = tr_torrentNew(ctor, &err, NULL);
- assert(!err);
+ assert(err == 0);
/* cleanup */
tr_free(metainfo);
check_streq(expected_files[3], files[3].name);
check(testFileExistsAndConsistsOfThisString(tor, 1, expected_contents[1]));
check(testFileExistsAndConsistsOfThisString(tor, 2, expected_contents[2]));
- check(files[0].is_renamed == false);
- check(files[1].is_renamed == true);
- check(files[2].is_renamed == true);
- check(files[3].is_renamed == false);
+ check(!files[0].is_renamed);
+ check(files[1].is_renamed);
+ check(files[2].is_renamed);
+ check(!files[3].is_renamed);
/* (while the branch is renamed: confirm that the .resume file remembers the changes) */
tr_torrentSaveResume(tor);
check(testFileExistsAndConsistsOfThisString(tor, i, expected_contents[i]));
}
- check(files[0].is_renamed == false);
- check(files[1].is_renamed == true);
- check(files[2].is_renamed == true);
- check(files[3].is_renamed == false);
+ check(!files[0].is_renamed);
+ check(files[1].is_renamed);
+ check(files[2].is_renamed);
+ check(!files[3].is_renamed);
/***
**** Test it an incomplete torrent...
/* rename prefix of top */
check_int_eq(EINVAL, torrentRenameAndWait(tor, "Feli", "FelidaeX"));
check_streq(tor->info.name, "Felidae");
- check(files[0].is_renamed == false);
- check(files[1].is_renamed == false);
- check(files[2].is_renamed == false);
- check(files[3].is_renamed == false);
+ check(!files[0].is_renamed);
+ check(!files[1].is_renamed);
+ check(!files[2].is_renamed);
+ check(!files[3].is_renamed);
/* rename false path */
check_int_eq(EINVAL, torrentRenameAndWait(tor, "Felidae/FelinaeX", "Genus Felinae"));
check_streq(tor->info.name, "Felidae");
- check(files[0].is_renamed == false);
- check(files[1].is_renamed == false);
- check(files[2].is_renamed == false);
- check(files[3].is_renamed == false);
+ check(!files[0].is_renamed);
+ check(!files[1].is_renamed);
+ check(!files[2].is_renamed);
+ check(!files[3].is_renamed);
/***
****
tr_variant* list = NULL;
tr_file_index_t const n = tor->info.fileCount;
- if (tr_variantDictFindList(dict, TR_KEY_dnd, &list) && (tr_variantListSize(list) == n))
+ if (tr_variantDictFindList(dict, TR_KEY_dnd, &list) && tr_variantListSize(list) == n)
{
int64_t tmp;
tr_file_index_t* dl = tr_new(tr_file_index_t, n);
for (i = 0; i < n; ++i)
{
- if (tr_variantGetInt(tr_variantListChild(list, i), &tmp) && tmp)
+ if (tr_variantGetInt(tr_variantListChild(list, i), &tmp) && tmp != 0)
{
dnd[dndCount++] = i;
}
}
}
- if (dndCount)
+ if (dndCount != 0)
{
tr_torrentInitFileDLs(tor, dnd, dndCount, false);
tr_logAddTorDbg(tor, "Resume file found %d files listed as dnd", dndCount);
}
- if (dlCount)
+ if (dlCount != 0)
{
tr_torrentInitFileDLs(tor, dl, dlCount, true);
tr_logAddTorDbg(tor, "Resume file found %d files marked for download", dlCount);
uint64_t ret = 0;
tr_file_index_t const n = tor->info.fileCount;
- if (tr_variantDictFindList(dict, TR_KEY_priority, &list) && (tr_variantListSize(list) == n))
+ if (tr_variantDictFindList(dict, TR_KEY_priority, &list) && tr_variantListSize(list) == n)
{
int64_t priority;
tr_file_index_t i;
char const* str;
size_t str_len;
- if (tr_variantGetStr(tr_variantListChild(list, i), &str, &str_len) && str && str_len)
+ if (tr_variantGetStr(tr_variantListChild(list, i), &str, &str_len) && str != NULL && str_len != 0)
{
tr_free(files[i].name);
files[i].name = tr_strndup(str, str_len);
/* get the oldest and newest nonzero timestamps for pieces in this file */
for (p = &inf->pieces[f->firstPiece], pend = &inf->pieces[f->lastPiece]; p != pend; ++p)
{
- if (!p->timeChecked)
+ if (p->timeChecked == 0)
{
has_zero = true;
}
only a single timestamp is saved for the file if *all* or *none*
of the pieces were tested more recently than the file's mtime. */
- if (!has_zero && (mtime <= oldest_nonzero)) /* all checked */
+ if (!has_zero && mtime <= oldest_nonzero) /* all checked */
{
tr_variantListAddInt(l, oldest_nonzero);
}
for (p = &inf->pieces[f->firstPiece], pend = &inf->pieces[f->lastPiece] + 1; p != pend; ++p)
{
- tr_variantListAddInt(ll, p->timeChecked ? p->timeChecked - offset : 0);
+ tr_variantListAddInt(ll, p->timeChecked != 0 ? p->timeChecked - offset : 0);
}
}
}
{
int64_t t = 0;
tr_variantGetInt(tr_variantListChild(b, i + 1), &t);
- inf->pieces[f->firstPiece + i].timeChecked = (time_t)(t ? t + offset : 0);
+ inf->pieces[f->firstPiece + i].timeChecked = (time_t)(t != 0 ? t + offset : 0);
}
}
}
err = NULL;
tr_bitfieldConstruct(&blocks, tor->blockCount);
- if ((b = tr_variantDictFind(prog, TR_KEY_blocks)))
+ if ((b = tr_variantDictFind(prog, TR_KEY_blocks)) != NULL)
{
size_t buflen;
uint8_t const* buf;
filename = getResumeFilename(tor);
- if ((err = tr_variantToFile(&top, TR_VARIANT_FMT_BENC, filename)))
+ if ((err = tr_variantToFile(&top, TR_VARIANT_FMT_BENC, filename)) != 0)
{
tr_torrentSetLocalError(tor, "Unable to save resume file: %s", tr_strerror(err));
}
tr_logAddTorDbg(tor, "Read resume file \"%s\"", filename);
- if ((fieldsToLoad & TR_FR_CORRUPT) && tr_variantDictFindInt(&top, TR_KEY_corrupt, &i))
+ if ((fieldsToLoad & TR_FR_CORRUPT) != 0 && tr_variantDictFindInt(&top, TR_KEY_corrupt, &i))
{
tor->corruptPrev = i;
fieldsLoaded |= TR_FR_CORRUPT;
}
- if ((fieldsToLoad & (TR_FR_PROGRESS | TR_FR_DOWNLOAD_DIR)) &&
- (tr_variantDictFindStr(&top, TR_KEY_destination, &str, &len)) && (str && *str))
+ if ((fieldsToLoad & (TR_FR_PROGRESS | TR_FR_DOWNLOAD_DIR)) != 0 &&
+ tr_variantDictFindStr(&top, TR_KEY_destination, &str, &len) && str != NULL && *str != '\0')
{
bool const is_current_dir = tor->currentDir == tor->downloadDir;
tr_free(tor->downloadDir);
fieldsLoaded |= TR_FR_DOWNLOAD_DIR;
}
- if ((fieldsToLoad & (TR_FR_PROGRESS | TR_FR_INCOMPLETE_DIR)) &&
- (tr_variantDictFindStr(&top, TR_KEY_incomplete_dir, &str, &len)) && (str && *str))
+ if ((fieldsToLoad & (TR_FR_PROGRESS | TR_FR_INCOMPLETE_DIR)) != 0 &&
+ tr_variantDictFindStr(&top, TR_KEY_incomplete_dir, &str, &len) && str != NULL && *str != '\0')
{
bool const is_current_dir = tor->currentDir == tor->incompleteDir;
tr_free(tor->incompleteDir);
fieldsLoaded |= TR_FR_INCOMPLETE_DIR;
}
- if ((fieldsToLoad & TR_FR_DOWNLOADED) && tr_variantDictFindInt(&top, TR_KEY_downloaded, &i))
+ if ((fieldsToLoad & TR_FR_DOWNLOADED) != 0 && tr_variantDictFindInt(&top, TR_KEY_downloaded, &i))
{
tor->downloadedPrev = i;
fieldsLoaded |= TR_FR_DOWNLOADED;
}
- if ((fieldsToLoad & TR_FR_UPLOADED) && tr_variantDictFindInt(&top, TR_KEY_uploaded, &i))
+ if ((fieldsToLoad & TR_FR_UPLOADED) != 0 && tr_variantDictFindInt(&top, TR_KEY_uploaded, &i))
{
tor->uploadedPrev = i;
fieldsLoaded |= TR_FR_UPLOADED;
}
- if ((fieldsToLoad & TR_FR_MAX_PEERS) && tr_variantDictFindInt(&top, TR_KEY_max_peers, &i))
+ if ((fieldsToLoad & TR_FR_MAX_PEERS) != 0 && tr_variantDictFindInt(&top, TR_KEY_max_peers, &i))
{
tor->maxConnectedPeers = i;
fieldsLoaded |= TR_FR_MAX_PEERS;
}
- if ((fieldsToLoad & TR_FR_RUN) && tr_variantDictFindBool(&top, TR_KEY_paused, &boolVal))
+ if ((fieldsToLoad & TR_FR_RUN) != 0 && tr_variantDictFindBool(&top, TR_KEY_paused, &boolVal))
{
tor->isRunning = !boolVal;
fieldsLoaded |= TR_FR_RUN;
}
- if ((fieldsToLoad & TR_FR_ADDED_DATE) && tr_variantDictFindInt(&top, TR_KEY_added_date, &i))
+ if ((fieldsToLoad & TR_FR_ADDED_DATE) != 0 && tr_variantDictFindInt(&top, TR_KEY_added_date, &i))
{
tor->addedDate = i;
fieldsLoaded |= TR_FR_ADDED_DATE;
}
- if ((fieldsToLoad & TR_FR_DONE_DATE) && tr_variantDictFindInt(&top, TR_KEY_done_date, &i))
+ if ((fieldsToLoad & TR_FR_DONE_DATE) != 0 && tr_variantDictFindInt(&top, TR_KEY_done_date, &i))
{
tor->doneDate = i;
fieldsLoaded |= TR_FR_DONE_DATE;
}
- if ((fieldsToLoad & TR_FR_ACTIVITY_DATE) && tr_variantDictFindInt(&top, TR_KEY_activity_date, &i))
+ if ((fieldsToLoad & TR_FR_ACTIVITY_DATE) != 0 && tr_variantDictFindInt(&top, TR_KEY_activity_date, &i))
{
tr_torrentSetActivityDate(tor, i);
fieldsLoaded |= TR_FR_ACTIVITY_DATE;
}
- if ((fieldsToLoad & TR_FR_TIME_SEEDING) && tr_variantDictFindInt(&top, TR_KEY_seeding_time_seconds, &i))
+ if ((fieldsToLoad & TR_FR_TIME_SEEDING) != 0 && tr_variantDictFindInt(&top, TR_KEY_seeding_time_seconds, &i))
{
tor->secondsSeeding = i;
fieldsLoaded |= TR_FR_TIME_SEEDING;
}
- if ((fieldsToLoad & TR_FR_TIME_DOWNLOADING) && tr_variantDictFindInt(&top, TR_KEY_downloading_time_seconds, &i))
+ if ((fieldsToLoad & TR_FR_TIME_DOWNLOADING) != 0 && tr_variantDictFindInt(&top, TR_KEY_downloading_time_seconds, &i))
{
tor->secondsDownloading = i;
fieldsLoaded |= TR_FR_TIME_DOWNLOADING;
}
- if ((fieldsToLoad & TR_FR_BANDWIDTH_PRIORITY) &&
+ if ((fieldsToLoad & TR_FR_BANDWIDTH_PRIORITY) != 0 &&
tr_variantDictFindInt(&top, TR_KEY_bandwidth_priority, &i) && tr_isPriority(i))
{
tr_torrentSetPriority(tor, i);
fieldsLoaded |= TR_FR_BANDWIDTH_PRIORITY;
}
- if (fieldsToLoad & TR_FR_PEERS)
+ if ((fieldsToLoad & TR_FR_PEERS) != 0)
{
fieldsLoaded |= loadPeers(&top, tor);
}
- if (fieldsToLoad & TR_FR_FILE_PRIORITIES)
+ if ((fieldsToLoad & TR_FR_FILE_PRIORITIES) != 0)
{
fieldsLoaded |= loadFilePriorities(&top, tor);
}
- if (fieldsToLoad & TR_FR_PROGRESS)
+ if ((fieldsToLoad & TR_FR_PROGRESS) != 0)
{
fieldsLoaded |= loadProgress(&top, tor);
}
- if (fieldsToLoad & TR_FR_DND)
+ if ((fieldsToLoad & TR_FR_DND) != 0)
{
fieldsLoaded |= loadDND(&top, tor);
}
- if (fieldsToLoad & TR_FR_SPEEDLIMIT)
+ if ((fieldsToLoad & TR_FR_SPEEDLIMIT) != 0)
{
fieldsLoaded |= loadSpeedLimits(&top, tor);
}
- if (fieldsToLoad & TR_FR_RATIOLIMIT)
+ if ((fieldsToLoad & TR_FR_RATIOLIMIT) != 0)
{
fieldsLoaded |= loadRatioLimits(&top, tor);
}
- if (fieldsToLoad & TR_FR_IDLELIMIT)
+ if ((fieldsToLoad & TR_FR_IDLELIMIT) != 0)
{
fieldsLoaded |= loadIdleLimits(&top, tor);
}
- if (fieldsToLoad & TR_FR_FILENAMES)
+ if ((fieldsToLoad & TR_FR_FILENAMES) != 0)
{
fieldsLoaded |= loadFilenames(&top, tor);
}
- if (fieldsToLoad & TR_FR_NAME)
+ if ((fieldsToLoad & TR_FR_NAME) != 0)
{
fieldsLoaded |= loadName(&top, tor);
}
{
uint64_t ret = 0;
- if (fields & TR_FR_RUN)
+ if ((fields & TR_FR_RUN) != 0)
{
bool isPaused;
}
}
- if (fields & TR_FR_MAX_PEERS)
+ if ((fields & TR_FR_MAX_PEERS) != 0)
{
if (tr_ctorGetPeerLimit(ctor, mode, &tor->maxConnectedPeers))
{
}
}
- if (fields & TR_FR_DOWNLOAD_DIR)
+ if ((fields & TR_FR_DOWNLOAD_DIR) != 0)
{
char const* path;
- if (tr_ctorGetDownloadDir(ctor, mode, &path) && path && *path)
+ if (tr_ctorGetDownloadDir(ctor, mode, &path) && path != NULL && *path != '\0')
{
ret |= TR_FR_DOWNLOAD_DIR;
tr_free(tor->downloadDir);
evbuffer_add_printf(body, "<h1>%d: %s</h1>", code, code_text);
- if (text)
+ if (text != NULL)
{
evbuffer_add_printf(body, "%s", text);
}
size_t inlen = evbuffer_get_length(body);
char const* boundary_key = "boundary=";
- char const* boundary_key_begin = content_type ? strstr(content_type, boundary_key) : NULL;
- char const* boundary_val = boundary_key_begin ? boundary_key_begin + strlen(boundary_key) : "arglebargle";
+ char const* boundary_key_begin = content_type != NULL ? strstr(content_type, boundary_key) : NULL;
+ char const* boundary_val = boundary_key_begin != NULL ? boundary_key_begin + strlen(boundary_key) : "arglebargle";
char* boundary = tr_strdup_printf("--%s", boundary_val);
size_t const boundary_len = strlen(boundary);
char const* delim = tr_memmem(in, inlen, boundary, boundary_len);
- while (delim)
+ while (delim != NULL)
{
size_t part_len;
char const* part = delim + boundary_len;
in = part;
delim = tr_memmem(in, inlen, boundary, boundary_len);
- part_len = delim ? (size_t)(delim - part) : inlen;
+ part_len = delim != NULL ? (size_t)(delim - part) : inlen;
- if (part_len)
+ if (part_len != 0)
{
char const* rnrn = tr_memmem(part, part_len, "\r\n\r\n", 4);
- if (rnrn)
+ if (rnrn != NULL)
{
struct tr_mimepart* p = tr_new(struct tr_mimepart, 1);
p->headers_len = (size_t)(rnrn - part);
tr_ptrArray parts = TR_PTR_ARRAY_INIT;
char const* query = strchr(req->uri, '?');
- bool const paused = query && strstr(query + 1, "paused=true");
+ bool const paused = query != NULL && strstr(query + 1, "paused=true") != NULL;
extract_parts_from_multipart(req->input_headers, req->input_buffer, &parts);
n = tr_ptrArraySize(&parts);
{
struct tr_mimepart* p = tr_ptrArrayNth(&parts, i);
- if (tr_memmem(p->headers, p->headers_len, TR_RPC_SESSION_ID_HEADER, strlen(TR_RPC_SESSION_ID_HEADER)))
+ if (tr_memmem(p->headers, p->headers_len, TR_RPC_SESSION_ID_HEADER, strlen(TR_RPC_SESSION_ID_HEADER)) != NULL)
{
break;
}
tr_variantDictAddRaw(args, TR_KEY_filename, body, body_len);
have_source = true;
}
- else if (!tr_variantFromBenc(&test, body, body_len))
+ else if (tr_variantFromBenc(&test, body, body_len) == 0)
{
char* b64 = tr_base64_encode(body, body_len, NULL);
tr_variantDictAddStr(args, TR_KEY_metainfo, b64);
};
char const* dot = strrchr(path, '.');
- for (i = 0; dot && i < TR_N_ELEMENTS(types); ++i)
+ for (i = 0; dot != NULL && i < TR_N_ELEMENTS(types); ++i)
{
if (strcmp(dot + 1, types[i].suffix) == 0)
{
{
char const* key = "Accept-Encoding";
char const* encoding = evhttp_find_header(req->input_headers, key);
- int const do_compress = encoding && strstr(encoding, "gzip");
+ bool const do_compress = encoding != NULL && strstr(encoding, "gzip") != NULL;
if (!do_compress)
{
{
char const* webClientDir = tr_getWebClientDir(server->session);
- if (!webClientDir || !*webClientDir)
+ if (webClientDir == NULL || *webClientDir == '\0')
{
send_simple_response(req, HTTP_NOTFOUND,
"<p>Couldn't find Transmission's web interface files!</p>"
subpath = tr_strdup(req->uri + strlen(server->url) + 4);
- if ((pch = strchr(subpath, '?')))
+ if ((pch = strchr(subpath, '?')) != NULL)
{
*pch = '\0';
}
- if (strstr(subpath, ".."))
+ if (strstr(subpath, "..") != NULL)
{
send_simple_response(req, HTTP_NOTFOUND, "<p>Tsk, tsk.</p>");
}
handle_rpc_from_json(req, server, (char const*)evbuffer_pullup(req->input_buffer, -1),
evbuffer_get_length(req->input_buffer));
}
- else if ((req->type == EVHTTP_REQ_GET) && ((q = strchr(req->uri, '?'))))
+ else if (req->type == EVHTTP_REQ_GET && (q = strchr(req->uri, '?')) != NULL)
{
struct rpc_response_data* data = tr_new0(struct rpc_response_data, 1);
data->req = req;
{
struct tr_rpc_server* server = arg;
- if (req && req->evcon)
+ if (req != NULL && req->evcon != NULL)
{
char const* auth;
char* user = NULL;
auth = evhttp_find_header(req->input_headers, "Authorization");
- if (auth && !evutil_ascii_strncasecmp(auth, "basic ", 6))
+ if (auth != NULL && evutil_ascii_strncasecmp(auth, "basic ", 6) == 0)
{
size_t plen;
char* p = tr_base64_decode_str(auth + 6, &plen);
char const* tr_rpcGetUrl(tr_rpc_server const* server)
{
- return server->url ? server->url : "";
+ return server->url != NULL ? server->url : "";
}
void tr_rpcSetWhitelist(tr_rpc_server* server, char const* whitelistStr)
tr_free(tmp);
/* clear out the old whitelist entries */
- while ((tmp = tr_list_pop_front(&server->whitelist)))
+ while ((tmp = tr_list_pop_front(&server->whitelist)) != NULL)
{
tr_free(tmp);
}
/* build the new whitelist entries */
- for (walk = whitelistStr; walk && *walk;)
+ for (walk = whitelistStr; walk != NULL && *walk != '\0';)
{
char const* delimiters = " ,;";
size_t const len = strcspn(walk, delimiters);
char const* tr_rpcGetWhitelist(tr_rpc_server const* server)
{
- return server->whitelistStr ? server->whitelistStr : "";
+ return server->whitelistStr != NULL ? server->whitelistStr : "";
}
void tr_rpcSetWhitelistEnabled(tr_rpc_server* server, bool isEnabled)
char const* tr_rpcGetUsername(tr_rpc_server const* server)
{
- return server->username ? server->username : "";
+ return server->username != NULL ? server->username : "";
}
void tr_rpcSetPassword(tr_rpc_server* server, char const* password)
char const* tr_rpcGetPassword(tr_rpc_server const* server)
{
- return server->password ? server->password : "";
+ return server->password != NULL ? server->password : "";
}
void tr_rpcSetPasswordEnabled(tr_rpc_server* server, bool isEnabled)
stopServer(s);
- while ((tmp = tr_list_pop_front(&s->whitelist)))
+ while ((tmp = tr_list_pop_front(&s->whitelist)) != NULL)
{
tr_free(tmp);
}
key = TR_KEY_rpc_whitelist;
- if (!tr_variantDictFindStr(settings, key, &str, NULL) && str)
+ if (!tr_variantDictFindStr(settings, key, &str, NULL) && str != NULL)
{
missing_settings_key(key);
}
{
tr_rpc_callback_status status = 0;
- if (session->rpc_func)
+ if (session->rpc_func != NULL)
{
status = session->rpc_func(session, type, tor, session->rpc_func_user_data);
}
tr_torrent* tor;
torrents = tr_new0(tr_torrent*, 1);
- if ((tor = tr_torrentFindFromId(session, id)))
+ if ((tor = tr_torrentFindFromId(session, id)) != NULL)
{
torrents[torrentCount++] = tor;
}
int const n = tr_sessionCountTorrents(session);
torrents = tr_new0(tr_torrent*, n);
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
if (tor->anyDate >= now - window)
{
tr_torrent* tor;
torrents = tr_new0(tr_torrent*, 1);
- if ((tor = tr_torrentFindFromHashString(session, str)))
+ if ((tor = tr_torrentFindFromHashString(session, str)) != NULL)
{
torrents[torrentCount++] = tor;
}
tr_torrent* tor = torrents[i];
tr_rpc_callback_status const status = notify(session, type, tor);
- if (!(status & TR_RPC_NOREMOVE))
+ if ((status & TR_RPC_NOREMOVE) == 0)
{
tr_torrentRemove(tor, deleteFlag, NULL);
}
int const interval = RECENTLY_ACTIVE_SECONDS;
tr_variant* removed_out = tr_variantDictAddList(args_out, TR_KEY_removed, 0);
- while ((d = tr_variantListChild(&session->removedTorrents, n++)))
+ while ((d = tr_variantListChild(&session->removedTorrents, n++)) != NULL)
{
int64_t intVal;
- if (tr_variantDictFindInt(d, TR_KEY_date, &intVal) && (intVal >= now - interval))
+ if (tr_variantDictFindInt(d, TR_KEY_date, &intVal) && intVal >= now - interval)
{
tr_variantDictFindInt(d, TR_KEY_id, &intVal);
tr_variantListAddInt(removed_out, intVal);
char const* errmsg = NULL;
tr_file_index_t* files = tr_new0(tr_file_index_t, tor->info.fileCount);
- if (n)
+ if (n != 0)
{
for (i = 0; i < n; ++i)
{
}
}
- if (fileCount)
+ if (fileCount != 0)
{
tr_torrentSetFilePriorities(tor, files, fileCount, priority);
}
char const* errmsg = NULL;
tr_file_index_t* files = tr_new0(tr_file_index_t, tor->info.fileCount);
- if (n) /* if argument list, process them */
+ if (n != 0) /* if argument list, process them */
{
for (i = 0; i < n; ++i)
{
/* and add the new ones */
i = 0;
- while ((val = tr_variantListChild(urls, i++)))
+ while ((val = tr_variantListChild(urls, i++)) != NULL)
{
char const* announce = NULL;
/* make the substitutions... */
i = 0;
- while (((pair[0] = tr_variantListChild(urls, i))) && ((pair[1] = tr_variantListChild(urls, i + 1))))
+ while ((pair[0] = tr_variantListChild(urls, i)) != NULL && (pair[1] = tr_variantListChild(urls, i + 1)) != NULL)
{
size_t len;
int64_t pos;
/* remove the ones specified in the urls list */
i = 0;
- while ((val = tr_variantListChild(ids, i++)))
+ while ((val = tr_variantListChild(ids, i++)) != NULL)
{
int64_t pos;
- if (tr_variantGetInt(val, &pos) && (0 <= pos) && (pos < n))
+ if (tr_variantGetInt(val, &pos) && 0 <= pos && pos < n)
{
tids[t++] = pos;
}
/* sort trackerIds and remove from largest to smallest so there is no need to recacluate array indicies */
qsort(tids, t, sizeof(int), compareInt);
- while (t--)
+ while (t-- != 0)
{
/* check for duplicates */
if (tids[t] == dup)
}
}
- if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_files_unwanted, &files))
+ if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_files_unwanted, &files))
{
errmsg = setFileDLs(tor, false, files);
}
- if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_files_wanted, &files))
+ if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_files_wanted, &files))
{
errmsg = setFileDLs(tor, true, files);
}
tr_torrentSetPeerLimit(tor, tmp);
}
- if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_priority_high, &files))
+ if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_priority_high, &files))
{
errmsg = setFilePriorities(tor, TR_PRI_HIGH, files);
}
- if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_priority_low, &files))
+ if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_priority_low, &files))
{
errmsg = setFilePriorities(tor, TR_PRI_LOW, files);
}
- if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_priority_normal, &files))
+ if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_priority_normal, &files))
{
errmsg = setFilePriorities(tor, TR_PRI_NORMAL, files);
}
tr_torrentSetQueuePosition(tor, tmp);
}
- if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_trackerAdd, &trackers))
+ if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_trackerAdd, &trackers))
{
errmsg = addTrackerUrls(tor, trackers);
}
- if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_trackerRemove, &trackers))
+ if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_trackerRemove, &trackers))
{
errmsg = removeTrackers(tor, trackers);
}
- if (!errmsg && tr_variantDictFindList(args_in, TR_KEY_trackerReplace, &trackers))
+ if (errmsg == NULL && tr_variantDictFindList(args_in, TR_KEY_trackerReplace, &trackers))
{
errmsg = replaceTrackers(tor, trackers);
}
}
else /* success */
{
- bool const isOpen = response_byte_count && *(char*)response == '1';
+ bool const isOpen = response_byte_count != 0 && *(char*)response == '1';
tr_variantDictAddBool(data->args_out, TR_KEY_port_is_open, isOpen);
tr_snprintf(result, sizeof(result), "success");
}
if (err != Z_OK)
{
- if ((err != Z_STREAM_END) && (err != Z_DATA_ERROR))
+ if (err != Z_STREAM_END && err != Z_DATA_ERROR)
{
tr_snprintf(result, sizeof(result), _("Error uncompressing blocklist: %s (%d)"), zError(err), err);
}
tr_sys_file_close(fd, NULL);
- if (*result)
+ if (*result != '\0')
{
tr_logAddError("%s", result);
}
tor = tr_torrentNew(ctor, &err, &duplicate_id);
tr_ctorFree(ctor);
- if (!err)
+ if (err == 0)
{
key = TR_KEY_torrent_added;
result = NULL;
result = "invalid or corrupt torrent file";
}
- if (tor && key)
+ if (tor != NULL && key != 0)
{
tr_variant fields;
tr_variantInitList(&fields, 3);
tr_variantDictFindStr(args_in, TR_KEY_filename, &filename, NULL);
tr_variantDictFindStr(args_in, TR_KEY_metainfo, &metainfo_base64, NULL);
- if (!filename && !metainfo_base64)
+ if (filename == NULL && metainfo_base64 == NULL)
{
return "no filename or metainfo specified";
}
assert(idle_data == NULL);
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
++total;
pch = strchr(request, '?');
- if (!pch)
+ if (pch == NULL)
{
pch = request;
}
- while (pch)
+ while (pch != NULL)
{
char const* delim = strchr(pch, '=');
char const* next = strchr(pch, '&');
- if (delim)
+ if (delim != NULL)
{
char* key = tr_strndup(pch, (size_t)(delim - pch));
bool isArg = strcmp(key, "method") != 0 && strcmp(key, "tag") != 0;
tr_variant* parent = isArg ? args : ⊤
tr_rpc_parse_list_str(tr_variantDictAdd(parent, tr_quark_new(key, (size_t)(delim - pch))), delim + 1,
- next ? (size_t)(next - (delim + 1)) : strlen(delim + 1));
+ next != NULL ? (size_t)(next - (delim + 1)) : strlen(delim + 1));
tr_free(key);
}
- pch = next ? next + 1 : NULL;
+ pch = next != NULL ? next + 1 : NULL;
}
tr_rpc_request_exec_json(session, &top, callback, callback_user_data);
val += strtoul(tmp, NULL, 36);
}
- check((val % 36) == 0);
+ check(val % 36 == 0);
}
return 0;
buf[i] = pool[val];
}
- val = total % base ? base - (total % base) : 0;
+ val = total % base != 0 ? base - (total % base) : 0;
buf[19] = pool[val];
buf[20] = '\0';
}
tr_encryption_mode tr_sessionGetEncryption(tr_session* session)
{
- assert(session);
+ assert(session != NULL);
return session->encryptionMode;
}
void tr_sessionSetEncryption(tr_session* session, tr_encryption_mode mode)
{
- assert(session);
+ assert(session != NULL);
assert(mode == TR_ENCRYPTION_PREFERRED || mode == TR_ENCRYPTION_REQUIRED || mode == TR_CLEAR_PREFERRED);
session->encryptionMode = mode;
static void close_bindinfo(struct tr_bindinfo* b)
{
- if ((b != NULL) && (b->socket != TR_BAD_SOCKET))
+ if (b != NULL && b->socket != TR_BAD_SOCKET)
{
event_free(b->ev);
b->ev = NULL;
break;
}
- if (is_default_value && bindinfo)
+ if (is_default_value != NULL && bindinfo != NULL)
{
*is_default_value = tr_strcmp0(default_value, tr_address_to_string(&bindinfo->addr)) == 0;
}
- return bindinfo ? &bindinfo->addr : NULL;
+ return bindinfo != NULL ? &bindinfo->addr : NULL;
}
/***
char* p;
int value;
- if (!evutil_ascii_strcasecmp(str, ""))
+ if (evutil_ascii_strcasecmp(str, "") == 0)
{
return 0;
}
- if (!evutil_ascii_strcasecmp(str, "default"))
+ if (evutil_ascii_strcasecmp(str, "default") == 0)
{
return 0;
}
- if (!evutil_ascii_strcasecmp(str, "lowcost"))
+ if (evutil_ascii_strcasecmp(str, "lowcost") == 0)
{
return 0x10;
}
- if (!evutil_ascii_strcasecmp(str, "mincost"))
+ if (evutil_ascii_strcasecmp(str, "mincost") == 0)
{
return 0x10;
}
- if (!evutil_ascii_strcasecmp(str, "throughput"))
+ if (evutil_ascii_strcasecmp(str, "throughput") == 0)
{
return 0x08;
}
- if (!evutil_ascii_strcasecmp(str, "reliability"))
+ if (evutil_ascii_strcasecmp(str, "reliability") == 0)
{
return 0x04;
}
- if (!evutil_ascii_strcasecmp(str, "lowdelay"))
+ if (evutil_ascii_strcasecmp(str, "lowdelay") == 0)
{
return 0x02;
}
value = strtol(str, &p, 0);
- if (!p || (p == str))
+ if (p == NULL || p == str)
{
return 0;
}
tr_variantFree(&oldDict);
/* if caller didn't specify a config dir, use the default */
- if (!configDir || !*configDir)
+ if (configDir == NULL || *configDir == '\0')
{
configDir = tr_getDefaultConfigDir(appName);
}
tr_torrent* tor = NULL;
tr_session* session = vsession;
- if (tr_cacheFlushDone(session->cache))
+ if (tr_cacheFlushDone(session->cache) != 0)
{
tr_logAddError("Error while flushing completed pieces from cache");
}
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
tr_torrentSave(tor);
}
turtleCheckClock(session, &session->turtle);
}
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
if (tor->isRunning)
{
tr_variantDictFindStr(settings, TR_KEY_bind_address_ipv4, &str, NULL);
- if (!tr_address_from_string(&b.addr, str) || (b.addr.type != TR_AF_INET))
+ if (!tr_address_from_string(&b.addr, str) || b.addr.type != TR_AF_INET)
{
b.addr = tr_inaddr_any;
}
tr_variantDictFindStr(settings, TR_KEY_bind_address_ipv6, &str, NULL);
- if (!tr_address_from_string(&b.addr, str) || (b.addr.type != TR_AF_INET6))
+ if (!tr_address_from_string(&b.addr, str) || b.addr.type != TR_AF_INET6)
{
b.addr = tr_in6addr_any;
}
assert(tr_isSession(session));
- if ((session != NULL) && (session->downloadDir != NULL))
+ if (session != NULL && session->downloadDir != NULL)
{
dir = session->downloadDir->path;
}
open_incoming_peer_port(session);
tr_sharedPortChanged(session);
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
tr_torrentChangeMyPort(tor);
}
void tr_sessionSetPeerPort(tr_session* session, tr_port port)
{
- if (tr_isSession(session) && (session->private_peer_port != port))
+ if (tr_isSession(session) && session->private_peer_port != port)
{
setPeerPort(session, port);
}
{
unsigned int limit_Bps = 0;
bool const isLimited = tr_sessionGetActiveSpeedLimit_Bps(session, dir, &limit_Bps);
- bool const zeroCase = isLimited && !limit_Bps;
+ bool const zeroCase = isLimited && limit_Bps == 0;
tr_bandwidthSetLimited(&session->bandwidth, dir, isLimited && !zeroCase);
for (day = 0; day < 7; ++day)
{
- if (t->days & (1 << day))
+ if ((t->days & (1 << day)) != 0)
{
int i;
time_t const begin = t->beginMinute;
enabled = getInTurtleTime(t);
newAutoTurtleState = autoSwitchState(enabled);
- alreadySwitched = (t->autoTurtleState == newAutoTurtleState);
+ alreadySwitched = t->autoTurtleState == newAutoTurtleState;
if (!alreadySwitched)
{
- tr_logAddInfo("Time to turn %s turtle mode!", (enabled ? "on" : "off"));
+ tr_logAddInfo("Time to turn %s turtle mode!", enabled ? "on" : "off");
t->autoTurtleState = newAutoTurtleState;
useAltSpeed(s, t, enabled, false);
}
void tr_sessionSetAltSpeedBegin(tr_session* s, int minute)
{
assert(tr_isSession(s));
- assert(0 <= minute && minute < (60 * 24));
+ assert(0 <= minute && minute < 60 * 24);
if (s->turtle.beginMinute != minute)
{
void tr_sessionSetAltSpeedEnd(tr_session* s, int minute)
{
assert(tr_isSession(s));
- assert(0 <= minute && minute < (60 * 24));
+ assert(0 <= minute && minute < 60 * 24);
if (s->turtle.endMinute != minute)
{
* so we need to keep the transmission thread alive
* for a bit while they tell the router & tracker
* that we're closing now */
- while ((session->shared || session->web || session->announcer || session->announcer_udp) && !deadlineReached(deadline))
+ while ((session->shared != NULL || session->web != NULL || session->announcer != NULL || session->announcer_udp != NULL) &&
+ !deadlineReached(deadline))
{
dbgmsg("waiting on port unmap (%p) or announcer (%p)... now %zu deadline %zu", (void*)session->shared,
(void*)session->announcer, (size_t)time(NULL), (size_t)deadline);
tr_session_id_free(session->session_id);
tr_lockFree(session->lock);
- if (session->metainfoLookup)
+ if (session->metainfoLookup != NULL)
{
tr_variantFree(session->metainfoLookup);
tr_free(session->metainfoLookup);
char* path = tr_buildPath(dirname, name, NULL);
tr_ctorSetMetainfoFromFile(data->ctor, path);
- if ((tor = tr_torrentNew(data->ctor, NULL, NULL)))
+ if ((tor = tr_torrentNew(data->ctor, NULL, NULL)) != NULL)
{
tr_list_prepend(&list, tor);
++n;
tr_list_free(&list, NULL);
- if (n)
+ if (n != 0)
{
tr_logAddInfo(_("Loaded %d torrents"), n);
}
- if (data->setmeCount)
+ if (data->setmeCount != NULL)
{
*data->setmeCount = n;
}
assert(tr_isSession(session));
- for (l = session->blocklists; l; l = l->next)
+ for (l = session->blocklists; l != NULL; l = l->next)
{
n += tr_blocklistFileGetRuleCount(l->data);
}
char const* defaultName = DEFAULT_BLOCKLIST_FILENAME;
tr_sessionLock(session);
- for (b = NULL, l = session->blocklists; !b && l; l = l->next)
+ for (b = NULL, l = session->blocklists; b == NULL && l != NULL; l = l->next)
{
if (tr_stringEndsWith(tr_blocklistFileGetFilename(l->data), defaultName))
{
}
}
- if (!b)
+ if (b == NULL)
{
char* path = tr_buildPath(session->configDir, "blocklists", defaultName, NULL);
b = tr_blocklistFileNew(path, session->isBlocklistEnabled);
assert(tr_isSession(session));
- for (l = session->blocklists; l; l = l->next)
+ for (l = session->blocklists; l != NULL; l = l->next)
{
if (tr_blocklistFileHasAddress(l->data, addr))
{
char* path = tr_buildPath(dirname, name, NULL);
tr_ctorSetMetainfoFromFile(ctor, path);
- if (!tr_torrentParse(ctor, &inf))
+ if (tr_torrentParse(ctor, &inf) == TR_PARSE_OK)
{
++n;
tr_variantDictAddStr(lookup, tr_quark_new(inf.hashString, TR_BAD_SIZE), path);
{
char const* filename = NULL;
- if (!session->metainfoLookup)
+ if (session->metainfoLookup == NULL)
{
metainfoLookupInit((tr_session*)session);
}
* and tr_sessionSetTorrentFile() is just to tell us there's a new file
* in that same directory, we don't need to do anything here if the
* lookup table hasn't been built yet */
- if (session->metainfoLookup)
+ if (session->metainfoLookup != NULL)
{
tr_variantDictAddStr(session->metainfoLookup, tr_quark_new(hashString, TR_BAD_SIZE), filename);
}
i = 0;
tor = NULL;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
if (!tr_torrentIsQueued(tor))
{
tor = NULL;
active_count = 0;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
if (!tr_torrentIsStalled(tor))
{
static inline bool tr_isSession(tr_session const* session)
{
- return (session != NULL) && (session->magicNumber == SESSION_MAGIC_NUMBER);
+ return session != NULL && session->magicNumber == SESSION_MAGIC_NUMBER;
}
static inline bool tr_isPreallocationMode(tr_preallocation_mode m)
{
- return (m == TR_PREALLOCATE_NONE) || (m == TR_PREALLOCATE_SPARSE) || (m == TR_PREALLOCATE_FULL);
+ return m == TR_PREALLOCATE_NONE || m == TR_PREALLOCATE_SPARSE || m == TR_PREALLOCATE_FULL;
}
static inline bool tr_isEncryptionMode(tr_encryption_mode m)
{
- return (m == TR_CLEAR_PREFERRED) || (m == TR_ENCRYPTION_PREFERRED) || (m == TR_ENCRYPTION_REQUIRED);
+ return m == TR_CLEAR_PREFERRED || m == TR_ENCRYPTION_PREFERRED || m == TR_ENCRYPTION_REQUIRED;
}
static inline bool tr_isPriority(tr_priority_t p)
{
- return (p == TR_PRI_LOW) || (p == TR_PRI_NORMAL) || (p == TR_PRI_HIGH);
+ return p == TR_PRI_LOW || p == TR_PRI_NORMAL || p == TR_PRI_HIGH;
}
/***
{
struct tr_stats_handle* h = getStats(session);
- if ((h != NULL) && h->isDirty)
+ if (h != NULL && h->isDirty)
{
tr_session_stats cumulative = STATS_INIT;
tr_sessionGetCumulativeStats(session, &cumulative);
{
struct tr_stats_handle const* stats = getStats(session);
- if (stats)
+ if (stats != NULL)
{
*setme = stats->single;
setme->secondsActive = tr_time() - stats->startTime;
struct tr_stats_handle const* stats = getStats(session);
tr_session_stats current = STATS_INIT;
- if (stats)
+ if (stats != NULL)
{
tr_sessionGetStats(session, ¤t);
addStats(setme, &stats->old, ¤t);
{
struct tr_stats_handle* s;
- if ((s = getStats(session)))
+ if ((s = getStats(session)) != NULL)
{
s->single.uploadedBytes += bytes;
s->isDirty = true;
{
struct tr_stats_handle* s;
- if ((s = getStats(session)))
+ if ((s = getStats(session)) != NULL)
{
s->single.downloadedBytes += bytes;
s->isDirty = true;
{
struct tr_stats_handle* s;
- if ((s = getStats(session)))
+ if ((s = getStats(session)) != NULL)
{
s->single.filesAdded++;
}
metainfo = tr_loadFile(filename, &len, NULL);
- if (metainfo && len)
+ if (metainfo != NULL && len != 0)
{
err = tr_ctorSetMetainfo(ctor, metainfo, len);
}
}
}
- if (!name || !*name)
+ if (name == NULL || *name == '\0')
{
char* base = tr_sys_path_basename(filename, NULL);
filename = tr_sessionFindTorrentFile(ctor->session, hashString);
- if (!filename)
+ if (filename == NULL)
{
err = EINVAL;
}
void tr_ctorInitTorrentWanted(tr_ctor const* ctor, tr_torrent* tor)
{
- if (ctor->notWantSize)
+ if (ctor->notWantSize != 0)
{
tr_torrentInitFileDLs(tor, ctor->notWant, ctor->notWantSize, false);
}
- if (ctor->wantSize)
+ if (ctor->wantSize != 0)
{
tr_torrentInitFileDLs(tor, ctor->want, ctor->wantSize, true);
}
{
ret = false;
}
- else if (setme)
+ else if (setme != NULL)
{
*setme = ctor->doDelete;
}
struct optional_args* args;
assert(ctor != NULL);
- assert((mode == TR_FALLBACK) || (mode == TR_FORCE));
+ assert(mode == TR_FALLBACK || mode == TR_FORCE);
assert(tr_isBool(isPaused));
args = &ctor->optionalArgs[mode];
struct optional_args* args;
assert(ctor != NULL);
- assert((mode == TR_FALLBACK) || (mode == TR_FORCE));
+ assert(mode == TR_FALLBACK || mode == TR_FORCE);
args = &ctor->optionalArgs[mode];
args->isSet_connected = true;
struct optional_args* args;
assert(ctor != NULL);
- assert((mode == TR_FALLBACK) || (mode == TR_FORCE));
+ assert(mode == TR_FALLBACK || mode == TR_FORCE);
args = &ctor->optionalArgs[mode];
tr_free(args->downloadDir);
args->downloadDir = NULL;
args->isSet_downloadDir = false;
- if (directory && *directory)
+ if (directory != NULL && *directory != '\0')
{
args->isSet_downloadDir = true;
args->downloadDir = tr_strdup(directory);
{
ret = false;
}
- else if (setmeCount)
+ else if (setmeCount != NULL)
{
*setmeCount = args->peerLimit;
}
{
ret = false;
}
- else if (setmeIsPaused)
+ else if (setmeIsPaused != NULL)
{
*setmeIsPaused = args->isPaused;
}
{
ret = false;
}
- else if (setmeDownloadDir)
+ else if (setmeDownloadDir != NULL)
{
*setmeDownloadDir = args->downloadDir;
}
{
ret = false;
}
- else if (setme)
+ else if (setme != NULL)
{
*setme = &ctor->metainfo;
}
static bool isPriority(int i)
{
- return (i == TR_PRI_LOW) || (i == TR_PRI_NORMAL) || (i == TR_PRI_HIGH);
+ return i == TR_PRI_LOW || i == TR_PRI_NORMAL || i == TR_PRI_HIGH;
}
void tr_ctorSetBandwidthPriority(tr_ctor* ctor, tr_priority_t priority)
size_t offset = 0;
/* load the file, and find the info dict's offset inside the file */
- if ((fileContents = tr_loadFile(tor->info.torrent, &fileLen, NULL)))
+ if ((fileContents = tr_loadFile(tor->info.torrent, &fileLen, NULL)) != NULL)
{
tr_variant top;
- if (!tr_variantFromBenc(&top, fileContents, fileLen))
+ if (tr_variantFromBenc(&top, fileContents, fileLen) == 0)
{
tr_variant* infoDict;
int const err = tr_variantFromBenc(&infoDict, m->metadata, m->metadata_size);
dbgmsg(tor, "err is %d", err);
- if ((metainfoParsed = !err))
+ if ((metainfoParsed = err == 0))
{
/* yay we have bencoded metainfo... merge it into our .torrent file */
tr_variant newMetainfo;
m = tor->incompleteMetadata;
- if ((m != NULL) && (m->piecesNeededCount > 0) && (m->piecesNeeded[0].requestedAt + MIN_REPEAT_INTERVAL_SECS < now))
+ if (m != NULL && m->piecesNeededCount > 0 && m->piecesNeeded[0].requestedAt + MIN_REPEAT_INTERVAL_SECS < now)
{
int i;
int const piece = m->piecesNeeded[0].piece;
{
struct tr_incomplete_metadata const* m = tor->incompleteMetadata;
- if (!m || !m->pieceCount)
+ if (m == NULL || m->pieceCount == 0)
{
ret = 0.0;
}
name = inf->name;
- if (name && *name)
+ if (name != NULL && *name != '\0')
{
evbuffer_add_printf(s, "%s", "&dn=");
tr_http_escape(s, name, TR_BAD_SIZE, true);
char const* tr_torrentName(tr_torrent const* tor)
{
- return tor ? tor->info.name : "";
+ return tor != NULL ? tor->info.name : "";
}
int tr_torrentId(tr_torrent const* tor)
{
- return tor ? tor->uniqueId : -1;
+ return tor != NULL ? tor->uniqueId : -1;
}
tr_torrent* tr_torrentFindFromId(tr_session* session, int id)
{
tr_torrent* tor = NULL;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
if (tor->uniqueId == id)
{
{
tr_torrent* tor = NULL;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
if (!evutil_ascii_strcasecmp(str, tor->info.hashString))
{
{
tr_torrent* tor = NULL;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
if (*tor->info.hash == *torrentHash)
{
tr_magnet_info* info;
tr_torrent* tor = NULL;
- if ((info = tr_magnetParse(magnet)))
+ if ((info = tr_magnetParse(magnet)) != NULL)
{
tor = tr_torrentFindFromHash(session, info->hash);
tr_magnetFree(info);
{
tr_torrent* tor = NULL;
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
if (memcmp(tor->obfuscatedHash, obfuscatedTorrentHash, SHA_DIGEST_LENGTH) == 0)
{
{
int ttl;
- if (!tor->peer_id_creation_time)
+ if (tor->peer_id_creation_time == 0)
{
ttl = 0;
}
{
bool needs_new_peer_id = false;
- if (!*tor->peer_id)
+ if (*tor->peer_id == '\0')
{
needs_new_peer_id = true;
}
case TR_RATIOLIMIT_SINGLE:
isLimited = true;
- if (ratio)
+ if (ratio != NULL)
{
*ratio = tr_torrentGetRatioLimit(tor);
}
case TR_RATIOLIMIT_GLOBAL:
isLimited = tr_sessionIsRatioLimited(tor->session);
- if (isLimited && ratio)
+ if (isLimited && ratio != NULL)
{
*ratio = tr_sessionGetRatioLimit(tor->session);
}
uint64_t const baseline = d ? d : tr_cpSizeWhenDone(&tor->completion);
uint64_t const goal = baseline * seedRatio;
- if (setmeLeft)
+ if (setmeLeft != NULL)
{
*setmeLeft = goal > u ? goal - u : 0;
}
- if (setmeGoal)
+ if (setmeGoal != NULL)
{
*setmeGoal = goal;
}
case TR_IDLELIMIT_GLOBAL:
isLimited = tr_sessionIsIdleLimited(tor->session);
- if (isLimited && idleMinutes)
+ if (isLimited && idleMinutes != NULL)
{
*idleMinutes = tr_sessionGetIdleLimit(tor->session);
}
{
tr_piece_index_t piece;
- assert(info);
+ assert(info != NULL);
assert(info->pieceSize != 0);
piece = byteOffset / info->pieceSize;
static bool pieceHasFile(tr_piece_index_t piece, tr_file const* file)
{
- return (file->firstPiece <= piece) && (piece <= file->lastPiece);
+ return file->firstPiece <= piece && piece <= file->lastPiece;
}
static tr_priority_t calculatePiecePriority(tr_torrent const* tor, tr_piece_index_t piece, int fileHint)
b /= 2u;
}
- if (!b || (pieceSize % b)) /* not cleanly divisible */
+ if (b == 0 || pieceSize % b != 0) /* not cleanly divisible */
{
return 0;
}
tor->blockSize = tr_getBlockSize(info->pieceSize);
- if (info->pieceSize)
+ if (info->pieceSize != 0)
{
tor->lastPieceSize = (uint32_t)(info->totalSize % info->pieceSize);
}
- if (!tor->lastPieceSize)
+ if (tor->lastPieceSize == 0)
{
tor->lastPieceSize = info->pieceSize;
}
- if (tor->blockSize)
+ if (tor->blockSize != 0)
{
tor->lastBlockSize = info->totalSize % tor->blockSize;
}
- if (!tor->lastBlockSize)
+ if (tor->lastBlockSize == 0)
{
tor->lastBlockSize = tor->blockSize;
}
- tor->blockCount = tor->blockSize ? (info->totalSize + tor->blockSize - 1) / tor->blockSize : 0;
- tor->blockCountInPiece = tor->blockSize ? info->pieceSize / tor->blockSize : 0;
- tor->blockCountInLastPiece = tor->blockSize ? (tor->lastPieceSize + tor->blockSize - 1) / tor->blockSize : 0;
+ tor->blockCount = tor->blockSize != 0 ? (info->totalSize + tor->blockSize - 1) / tor->blockSize : 0;
+ tor->blockCountInPiece = tor->blockSize != 0 ? info->pieceSize / tor->blockSize : 0;
+ tor->blockCountInLastPiece = tor->blockSize != 0 ? (tor->lastPieceSize + tor->blockSize - 1) / tor->blockSize : 0;
/* check our work */
if (tor->blockSize != 0)
{
- assert((info->pieceSize % tor->blockSize) == 0);
+ assert(info->pieceSize % tor->blockSize == 0);
}
t = info->pieceCount - 1;
static bool setLocalErrorIfFilesDisappeared(tr_torrent* tor)
{
- bool const disappeared = (tr_torrentHaveTotal(tor) > 0) && !hasAnyLocalData(tor);
+ bool const disappeared = tr_torrentHaveTotal(tor) > 0 && !hasAnyLocalData(tor);
if (disappeared)
{
tr_peerMgrAddTorrent(session->peerMgr, tor);
- assert(!tor->downloadedCur);
- assert(!tor->uploadedCur);
+ assert(tor->downloadedCur == 0);
+ assert(tor->uploadedCur == 0);
tr_torrentSetAddedDate(tor, tr_time()); /* this is a default value to be overwritten by the resume file */
doStart = tor->isRunning;
tor->isRunning = false;
- if (!(loaded & TR_FR_SPEEDLIMIT))
+ if ((loaded & TR_FR_SPEEDLIMIT) == 0)
{
tr_torrentUseSpeedLimit(tor, TR_UP, false);
tr_torrentSetSpeedLimit_Bps(tor, TR_UP, tr_sessionGetSpeedLimit_Bps(tor->session, TR_UP));
tr_torrentUseSessionLimits(tor, true);
}
- if (!(loaded & TR_FR_RATIOLIMIT))
+ if ((loaded & TR_FR_RATIOLIMIT) == 0)
{
tr_torrentSetRatioMode(tor, TR_RATIOLIMIT_GLOBAL);
tr_torrentSetRatioLimit(tor, tr_sessionGetRatioLimit(tor->session));
}
- if (!(loaded & TR_FR_IDLELIMIT))
+ if ((loaded & TR_FR_IDLELIMIT) == 0)
{
tr_torrentSetIdleMode(tor, TR_IDLELIMIT_GLOBAL);
tr_torrentSetIdleLimit(tor, tr_sessionGetIdleLimit(tor->session));
char const* path = tor->info.torrent;
int const err = tr_variantToFile(val, TR_VARIANT_FMT_BENC, path);
- if (err)
+ if (err != 0)
{
tr_torrentSetLocalError(tor, "Unable to save torrent file: %s", tr_strerror(err));
}
result = TR_PARSE_ERR;
}
- if (didParse && session && (result == TR_PARSE_OK))
+ if (didParse && session != NULL && result == TR_PARSE_OK)
{
tr_torrent const* const tor = tr_torrentFindFromHash(session, setmeInfo->hash);
bool tr_torrentCanManualUpdate(tr_torrent const* tor)
{
- return (tr_isTorrent(tor)) && (tor->isRunning) && (tr_announcerCanManualAnnounce(tor));
+ return tr_isTorrent(tor) && tor->isRunning && tr_announcerCanManualAnnounce(tor);
}
tr_info const* tr_torrentInfo(tr_torrent const* tor)
{
time_t const now = tr_time();
- return tr_isTorrent(tor) && (now == tor->lastStatTime) ? &tor->stats : tr_torrentStat(tor);
+ return (tr_isTorrent(tor) && now == tor->lastStatTime) ? &tor->stats : tr_torrentStat(tor);
}
void tr_torrentSetVerifyState(tr_torrent* tor, tr_verify_state state)
bool tr_torrentIsStalled(tr_torrent const* tor)
{
return tr_sessionGetQueueStalledEnabled(tor->session) &&
- (torrentGetIdleSecs(tor) > (tr_sessionGetQueueStalledMinutes(tor->session) * 60));
+ torrentGetIdleSecs(tor) > tr_sessionGetQueueStalledMinutes(tor->session) * 60;
}
static double getVerifyProgress(tr_torrent const* tor)
for (i = 0, n = tor->info.pieceCount; i != n; ++i)
{
- if (tor->info.pieces[i].timeChecked)
+ if (tor->info.pieces[i].timeChecked != 0)
{
++checked;
}
* so, etaXLSpeed is a smoothed-out version of the piece speed
* to dampen the effect of fluctuations */
case TR_STATUS_DOWNLOAD:
- if ((tor->etaDLSpeedCalculatedAt + 800) < now)
+ if (tor->etaDLSpeedCalculatedAt + 800 < now)
{
tor->etaDLSpeedCalculatedAt = now;
- tor->etaDLSpeed_Bps = ((tor->etaDLSpeedCalculatedAt + 4000) < now) ?
+ tor->etaDLSpeed_Bps = tor->etaDLSpeedCalculatedAt + 4000 < now ?
pieceDownloadSpeed_Bps : /* if no recent previous speed, no need to smooth */
- ((tor->etaDLSpeed_Bps * 4.0) + pieceDownloadSpeed_Bps) / 5.0; /* smooth across 5 readings */
+ (tor->etaDLSpeed_Bps * 4.0 + pieceDownloadSpeed_Bps) / 5.0; /* smooth across 5 readings */
}
- if ((s->leftUntilDone > s->desiredAvailable) && (tor->info.webseedCount < 1))
+ if (s->leftUntilDone > s->desiredAvailable && tor->info.webseedCount < 1)
{
s->eta = TR_ETA_NOT_AVAIL;
}
}
else
{
- if ((tor->etaULSpeedCalculatedAt + 800) < now)
+ if (tor->etaULSpeedCalculatedAt + 800 < now)
{
tor->etaULSpeedCalculatedAt = now;
- tor->etaULSpeed_Bps = ((tor->etaULSpeedCalculatedAt + 4000) < now) ?
+ tor->etaULSpeed_Bps = tor->etaULSpeedCalculatedAt + 4000 < now ?
pieceUploadSpeed_Bps : /* if no recent previous speed, no need to smooth */
- ((tor->etaULSpeed_Bps * 4.0) + pieceUploadSpeed_Bps) / 5.0; /* smooth across 5 readings */
+ (tor->etaULSpeed_Bps * 4.0 + pieceUploadSpeed_Bps) / 5.0; /* smooth across 5 readings */
}
if (tor->etaULSpeed_Bps == 0)
/* s->haveValid is here to make sure a torrent isn't marked 'finished'
* when the user hits "uncheck all" prior to starting the torrent... */
- s->finished = tor->finishedSeedingByIdle || (seedRatioApplies && !seedRatioBytesLeft && s->haveValid);
+ s->finished = tor->finishedSeedingByIdle || (seedRatioApplies && seedRatioBytesLeft == 0 && s->haveValid != 0);
if (!seedRatioApplies || s->finished)
{
s->seedRatioPercentDone = 1;
}
- else if (!seedRatioBytesGoal) /* impossible? safeguard for div by zero */
+ else if (seedRatioBytesGoal == 0) /* impossible? safeguard for div by zero */
{
s->seedRatioPercentDone = 0;
}
uint64_t total = 0;
tr_file const* f = &tor->info.files[index];
- if (f->length)
+ if (f->length != 0)
{
tr_block_index_t first;
tr_block_index_t last;
{
uint64_t const b = isSeed ? tor->info.files[i].length : countFileBytesCompleted(tor, i);
walk->bytesCompleted = b;
- walk->progress = tor->info.files[i].length > 0 ? ((float)b / tor->info.files[i].length) : 1.0f;
+ walk->progress = tor->info.files[i].length > 0 ? (float)b / tor->info.files[i].length : 1.0f;
}
if (fileCount != NULL)
/* resequence the queue positions */
t = NULL;
- while ((t = tr_torrentNext(session, t)))
+ while ((t = tr_torrentNext(session, t)) != NULL)
{
if (t->queuePosition > tor->queuePosition)
{
static void fireCompletenessChange(tr_torrent* tor, tr_completeness status, bool wasRunning)
{
- assert((status == TR_LEECH) || (status == TR_SEED) || (status == TR_PARTIAL_SEED));
+ assert(status == TR_LEECH || status == TR_SEED || status == TR_PARTIAL_SEED);
- if (tor->completeness_func)
+ if (tor->completeness_func != NULL)
{
tor->completeness_func(tor, status, wasRunning, tor->completeness_func_user_data);
}
*newlinePos = '\0';
}
- if (script && *script)
+ if (script != NULL && *script != '\0')
{
size_t i;
char* cmd[] =
signal(SIGCHLD, onSigCHLD);
- if (!fork())
+ if (fork() == 0)
{
for (i = 0; env[i] != NULL; ++i)
{
firstPieceDND = tor->info.files[i].dnd;
- if (!i)
+ if (i == 0)
{
break;
}
{
err = 2;
}
- else if ((offset + length) > tr_torPieceCountBytes(tor, index))
+ else if (offset + length > tr_torPieceCountBytes(tor, index))
{
err = 3;
}
err = 5;
}
- if (err)
+ if (err != 0)
{
tr_logAddTorDbg(tor, "index %lu offset %lu length %lu err %d\n", (unsigned long)index, (unsigned long)offset,
(unsigned long)length, err);
*first = offset / tor->blockSize;
- if (!f->length)
+ if (f->length == 0)
{
*last = *first;
}
tr_info const* inf = tr_torrentInfo(tor);
/* if we've never checked this piece, then it needs to be checked */
- if (!inf->pieces[p].timeChecked)
+ if (inf->pieces[p].timeChecked == 0)
{
return true;
}
/* if we had a tracker-related error on this torrent,
* and that tracker's been removed,
* then clear the error */
- if ((tor->error == TR_STAT_TRACKER_WARNING) || (tor->error == TR_STAT_TRACKER_ERROR))
+ if (tor->error == TR_STAT_TRACKER_WARNING || tor->error == TR_STAT_TRACKER_ERROR)
{
bool clear = true;
{
tr_file const* file = &tor->info.files[i];
- if ((file->firstPiece <= pieceIndex) && (pieceIndex <= file->lastPiece))
+ if (file->firstPiece <= pieceIndex && pieceIndex <= file->lastPiece)
{
if (tr_cpFileIsComplete(&tor->completion, i))
{
}
/* look in the incomplete dir... */
- if ((b == NULL) && (tor->incompleteDir != NULL))
+ if (b == NULL && tor->incompleteDir != NULL)
{
char* filename = tr_buildPath(tor->incompleteDir, file->name, NULL);
}
/* look for a .part file in the incomplete dir... */
- if ((b == NULL) && (tor->incompleteDir != NULL))
+ if (b == NULL && tor->incompleteDir != NULL)
{
char* filename = tr_buildPath(tor->incompleteDir, part, NULL);
}
assert(dir != NULL);
- assert((dir == tor->downloadDir) || (dir == tor->incompleteDir));
+ assert(dir == tor->downloadDir || dir == tor->incompleteDir);
tor->currentDir = dir;
}
walk = NULL;
- while ((walk = tr_torrentNext(tor->session, walk)))
+ while ((walk = tr_torrentNext(tor->session, walk)) != NULL)
{
if (old_pos < pos)
{
- if ((old_pos <= walk->queuePosition) && (walk->queuePosition <= pos))
+ if (old_pos <= walk->queuePosition && walk->queuePosition <= pos)
{
walk->queuePosition--;
walk->anyDate = now;
if (old_pos > pos)
{
- if ((pos <= walk->queuePosition) && (walk->queuePosition < old_pos))
+ if (pos <= walk->queuePosition && walk->queuePosition < old_pos)
{
walk->queuePosition++;
walk->anyDate = now;
static bool renameArgsAreValid(char const* oldpath, char const* newname)
{
- return (oldpath && *oldpath) && (newname && *newname) && (strcmp(newname, ".") != 0) && (strcmp(newname, "..") != 0) &&
- (strchr(newname, TR_PATH_DELIMITER) == NULL);
+ return oldpath != NULL && *oldpath != '\0' && newname != NULL && *newname != '\0' && strcmp(newname, ".") != 0 &&
+ strcmp(newname, "..") != 0 && strchr(newname, TR_PATH_DELIMITER) == NULL;
}
static tr_file_index_t* renameFindAffectedFiles(tr_torrent* tor, char const* oldpath, size_t* setme_n)
char const* base;
int err = 0;
- if (!tr_torrentIsSeed(tor) && (tor->incompleteDir != NULL))
+ if (!tr_torrentIsSeed(tor) && tor->incompleteDir != NULL)
{
base = tor->incompleteDir;
}
error = renamePath(tor, oldpath, newname);
- if (!error)
+ if (error == 0)
{
/* update tr_info.files */
for (i = 0; i < n; ++i)
}
/* update tr_info.name if user changed the toplevel */
- if ((n == tor->info.fileCount) && (strchr(oldpath, '/') == NULL))
+ if (n == tor->info.fileCount && strchr(oldpath, '/') == NULL)
{
tr_free(tor->info.name);
tor->info.name = tr_strdup(newname);
static inline tr_torrent* tr_torrentNext(tr_session* session, tr_torrent* current)
{
- return current ? current->next : session->torrentList;
+ return current != NULL ? current->next : session->torrentList;
}
/* what piece index is this block in? */
static inline bool tr_torrentIsPrivate(tr_torrent const* tor)
{
- return (tor != NULL) && tor->info.isPrivate;
+ return tor != NULL && tor->info.isPrivate;
}
static inline bool tr_torrentAllowsPex(tr_torrent const* tor)
{
- return (tor != NULL) && (tor->session->isPexEnabled) && (!tr_torrentIsPrivate(tor));
+ return tor != NULL && tor->session->isPexEnabled && !tr_torrentIsPrivate(tor);
}
static inline bool tr_torrentAllowsDHT(tr_torrent const* tor)
{
- return (tor != NULL) && (tr_sessionAllowsDHT(tor->session)) && (!tr_torrentIsPrivate(tor));
+ return tor != NULL && tr_sessionAllowsDHT(tor->session) && !tr_torrentIsPrivate(tor);
}
static inline bool tr_torrentAllowsLPD(tr_torrent const* tor)
{
- return (tor != NULL) && (tr_sessionAllowsLPD(tor->session)) && (!tr_torrentIsPrivate(tor));
+ return tor != NULL && tr_sessionAllowsLPD(tor->session) && !tr_torrentIsPrivate(tor);
}
/***
static inline bool tr_isTorrent(tr_torrent const* tor)
{
- return (tor != NULL) && (tor->magicNumber == TORRENT_MAGIC_NUMBER) && (tr_isSession(tor->session));
+ return tor != NULL && tor->magicNumber == TORRENT_MAGIC_NUMBER && tr_isSession(tor->session);
}
/* set a flag indicating that the torrent's .resume file
infop = info;
- while (infop)
+ while (infop != NULL)
{
dht_ping_node(infop->ai_addr, infop->ai_addrlen);
bootstrap_file = tr_buildPath(cl->session->configDir, "dht.bootstrap", NULL);
- if (bootstrap_file)
+ if (bootstrap_file != NULL)
{
f = tr_sys_file_open(bootstrap_file, TR_SYS_FILE_READ, 0, NULL);
}
}
}
- if (cl->nodes)
+ if (cl->nodes != NULL)
{
tr_free(cl->nodes);
}
- if (cl->nodes6)
+ if (cl->nodes6 != NULL)
{
tr_free(cl->nodes6);
}
size_t len, len6;
struct bootstrap_closure* cl;
- if (session) /* already initialized */
+ if (session != NULL) /* already initialized */
{
return -1;
}
memcpy(myid, raw, len);
}
- if (ss->udp_socket != TR_BAD_SOCKET &&
- tr_variantDictFindRaw(&benc, TR_KEY_nodes, &raw, &len) && !(len % 6))
+ if (ss->udp_socket != TR_BAD_SOCKET && tr_variantDictFindRaw(&benc, TR_KEY_nodes, &raw, &len) && len % 6 == 0)
{
nodes = tr_memdup(raw, len);
}
- if (ss->udp6_socket != TR_BAD_SOCKET &&
- tr_variantDictFindRaw(&benc, TR_KEY_nodes6, &raw, &len6) && !(len6 % 18))
+ if (ss->udp6_socket != TR_BAD_SOCKET && tr_variantDictFindRaw(&benc, TR_KEY_nodes6, &raw, &len6) && len6 % 18 == 0)
{
nodes6 = tr_memdup(raw, len6);
}
/* Since we only save known good nodes, avoid erasing older data if we
don't know enough nodes. */
- if ((tr_dhtStatus(ss, AF_INET, NULL) < TR_DHT_FIREWALLED) && (tr_dhtStatus(ss, AF_INET6, NULL) < TR_DHT_FIREWALLED))
+ if (tr_dhtStatus(ss, AF_INET, NULL) < TR_DHT_FIREWALLED && tr_dhtStatus(ss, AF_INET6, NULL) < TR_DHT_FIREWALLED)
{
tr_logAddNamedInfo("DHT", "Not saving nodes, DHT not ready");
}
bool tr_dhtEnabled(tr_session const* ss)
{
- return ss && (ss == session);
+ return ss != NULL && ss == session;
}
struct getstatus_closure
if (!tr_dhtEnabled(session) || (af == AF_INET && session->udp_socket == TR_BAD_SOCKET) ||
(af == AF_INET6 && session->udp6_socket == TR_BAD_SOCKET))
{
- if (nodes_return)
+ if (nodes_return != NULL)
{
*nodes_return = 0;
}
tr_wait_msec(50 /*msec*/);
}
- if (nodes_return)
+ if (nodes_return != NULL)
{
*nodes_return = closure.count;
}
tr_sessionLock(session);
tor = tr_torrentFindFromHash(session, info_hash);
- if (tor && tr_torrentAllowsDHT(tor))
+ if (tor != NULL && tr_torrentAllowsDHT(tor))
{
size_t i, n;
tr_pex* pex;
{
tr_torrent* tor = tr_torrentFindFromHash(session, info_hash);
- if (tor)
+ if (tor != NULL)
{
if (event == DHT_EVENT_SEARCH_DONE)
{
tr_torrent* tor = NULL;
time_t const now = tr_time();
- while ((tor = tr_torrentNext(session, tor)))
+ while ((tor = tr_torrentNext(session, tor)) != NULL)
{
if (!tor->isRunning || !tr_torrentAllowsDHT(tor))
{
n = 0;
tr_optind = 1;
- while ((c = tr_getopt("summary", argc, argv, options, &optarg)))
+ while ((c = tr_getopt("summary", argc, argv, options, &optarg)) != TR_OPT_DONE)
{
check(n < expected_n);
check_int_eq(expected_c[n], c);
{
arg = "";
}
- else if (opt->argName)
+ else if (opt->argName != NULL)
{
arg = opt->argName;
}
end = maxlen < len ? maxlen : len;
- while ((end > 0) && !isspace(description[end]))
+ while (end > 0 && !isspace(description[end]))
{
--end;
}
- return end ? end : len;
+ return end != 0 ? end : len;
}
static void getopts_usage_line(tr_option const* opt, int longWidth, int shortWidth, int argWidth)
{
int len;
- char const* longName = opt->longName ? opt->longName : "";
- char const* shortName = opt->shortName ? opt->shortName : "";
+ char const* longName = opt->longName != NULL ? opt->longName : "";
+ char const* shortName = opt->shortName != NULL ? opt->shortName : "";
char const* arg = getArgName(opt);
int const d_indent = shortWidth + longWidth + argWidth + 7;
int const d_width = 80 - d_indent;
char const* d = opt->description;
- printf(" %s%-*s %s%-*s %-*s ", (shortName && *shortName ? "-" : " "), shortWidth, shortName,
- (longName && *longName ? "--" : " "), longWidth, longName, argWidth, arg);
+ printf(" %s%-*s %s%-*s %-*s ", (shortName != NULL && *shortName != '\0') ? "-" : " ", shortWidth, shortName,
+ (longName != NULL && *longName != '\0') ? "--" : " ", longWidth, longName, argWidth, arg);
len = get_next_line_len(d, d_width);
printf("%*.*s\n", len, len, d);
++d;
}
- while ((len = get_next_line_len(d, d_width)))
+ while ((len = get_next_line_len(d, d_width)) != 0)
{
printf("%*.*s%*.*s\n", d_indent, d_indent, "", len, len, d);
d += len;
{
char const* arg;
- if (o->longName)
+ if (o->longName != NULL)
{
*longWidth = MAX(*longWidth, (int)strlen(o->longName));
}
- if (o->shortName)
+ if (o->shortName != NULL)
{
*shortWidth = MAX(*shortWidth, (int)strlen(o->shortName));
}
- if ((arg = getArgName(o)))
+ if ((arg = getArgName(o)) != NULL)
{
*argWidth = MAX(*argWidth, (int)strlen(arg));
}
struct tr_option help;
struct tr_option const* o;
- for (o = opts; o->val; ++o)
+ for (o = opts; o->val != 0; ++o)
{
maxWidth(o, &longWidth, &shortWidth, &argWidth);
}
printf("\n\nOptions:\n");
getopts_usage_line(&help, longWidth, shortWidth, argWidth);
- for (o = opts; o->val; ++o)
+ for (o = opts; o->val != 0; ++o)
{
getopts_usage_line(o, longWidth, shortWidth, argWidth);
}
tr_option const* match = NULL;
/* find the longest matching option */
- for (o = opts; o->val; ++o)
+ for (o = opts; o->val != 0; ++o)
{
- size_t len = o->longName ? strlen(o->longName) : 0;
+ size_t len = o->longName != NULL ? strlen(o->longName) : 0;
- if ((matchlen < len) && (str[0] == '-') && (str[1] == '-') && strncmp(str + 2, o->longName, len) == 0 &&
+ if (matchlen < len && str[0] == '-' && str[1] == '-' && strncmp(str + 2, o->longName, len) == 0 &&
(str[len + 2] == '\0' || (o->has_arg && str[len + 2] == '=')))
{
matchlen = len;
arg = str[len + 2] == '=' ? str + len + 3 : NULL;
}
- len = o->shortName ? strlen(o->shortName) : 0;
+ len = o->shortName != NULL ? strlen(o->shortName) : 0;
- if ((matchlen < len) && (str[0] == '-') && strncmp(str + 1, o->shortName, len) == 0 &&
- (str[len + 1] == '\0' || o->has_arg))
+ if (matchlen < len && str[0] == '-' && strncmp(str + 1, o->shortName, len) == 0 && (str[len + 1] == '\0' || o->has_arg))
{
matchlen = len;
match = o;
}
}
- if (setme_arg)
+ if (setme_arg != NULL)
{
*setme_arg = arg;
}
o = findOption(opts, argv[tr_optind], &arg);
- if (!o)
+ if (o == NULL)
{
/* let the user know we got an unknown option... */
*setme_optarg = argv[tr_optind++];
if (!o->has_arg)
{
/* no argument needed for this option, so we're done */
- if (arg)
+ if (arg != NULL)
{
return TR_OPT_ERR;
}
}
/* option needed an argument, and it was embedded in this string */
- if (arg)
+ if (arg != NULL)
{
*setme_optarg = arg;
++tr_optind;
return TR_OPT_ERR;
}
- if (findOption(opts, argv[tr_optind], NULL))
+ if (findOption(opts, argv[tr_optind], NULL) != NULL)
{
return TR_OPT_ERR;
}
struct ip_mreq mcastReq;
int const opt_on = 1, opt_off = 0;
- if (session) /* already initialized */
+ if (session != NULL) /* already initialized */
{
return -1;
}
bool tr_lpdEnabled(tr_session const* ss)
{
- return ss && (ss == session);
+ return ss != NULL && ss == session;
}
/**
}
/* make sure the hash string is normalized, just in case */
- for (i = 0; i < sizeof hashString; i++)
+ for (i = 0; i < sizeof(hashString); i++)
{
hashString[i] = toupper(t->info.hashString[i]);
}
return -1;
}
- while ((tor = tr_torrentNext(session, tor)) && tr_sessionAllowsLPD(session))
+ while ((tor = tr_torrentNext(session, tor)) != NULL && tr_sessionAllowsLPD(session))
{
if (tr_isTorrent(tor))
{
#define SEND_BUFFER_SIZE (1 * 1024 * 1024)
#define SMALL_BUFFER_SIZE (32 * 1024)
-static void set_socket_buffers(tr_socket_t fd, int large)
+static void set_socket_buffers(tr_socket_t fd, bool large)
{
int size, rbuf, sbuf, rc;
socklen_t rbuf_len = sizeof(rbuf), sbuf_len = sizeof(sbuf);
No way to fix that without some surgery to the DHT code itself. */
if (ipv6 == NULL || (!force && ss->udp6_socket == TR_BAD_SOCKET))
{
- if (ss->udp6_bound)
+ if (ss->udp6_bound != NULL)
{
free(ss->udp6_bound);
ss->udp6_bound = NULL;
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
- if (ipv6)
+ if (ipv6 != NULL)
{
memcpy(&sin6.sin6_addr, ipv6, 16);
}
sin6.sin6_port = htons(ss->udp_port);
public_addr = tr_sessionGetPublicAddress(ss, TR_AF_INET6, &is_default);
- if (public_addr && !is_default)
+ if (public_addr != NULL && !is_default)
{
sin6.sin6_addr = public_addr->addr.addr6;
}
ss->udp6_bound = malloc(16);
}
- if (ss->udp6_bound)
+ if (ss->udp6_bound != NULL)
{
memcpy(ss->udp6_bound, ipv6, 16);
}
tr_netCloseSocket(s);
}
- if (ss->udp6_bound)
+ if (ss->udp6_bound != NULL)
{
free(ss->udp6_bound);
ss->udp6_bound = NULL;
{
rc = tau_handle_message(ss, buf, rc);
- if (!rc)
+ if (rc == 0)
{
tr_logAddNamedDbg("UDP", "Couldn't parse UDP tracker packet.");
}
{
rc = tr_utpPacket(buf, rc, (struct sockaddr*)&from, fromlen, ss);
- if (!rc)
+ if (rc == 0)
{
tr_logAddNamedDbg("UDP", "Unexpected UDP packet");
}
sin.sin_family = AF_INET;
public_addr = tr_sessionGetPublicAddress(ss, TR_AF_INET, &is_default);
- if (public_addr && !is_default)
+ if (public_addr != NULL && !is_default)
{
memcpy(&sin.sin_addr, &public_addr->addr.addr4, sizeof(struct in_addr));
}
tr_dhtInit(ss);
}
- if (ss->udp_event)
+ if (ss->udp_event != NULL)
{
event_add(ss->udp_event, NULL);
}
- if (ss->udp6_event)
+ if (ss->udp6_event != NULL)
{
event_add(ss->udp6_event, NULL);
}
ss->udp_socket = TR_BAD_SOCKET;
}
- if (ss->udp_event)
+ if (ss->udp_event != NULL)
{
event_free(ss->udp_event);
ss->udp_event = NULL;
ss->udp6_socket = TR_BAD_SOCKET;
}
- if (ss->udp6_event)
+ if (ss->udp6_event != NULL)
{
event_free(ss->udp6_event);
ss->udp6_event = NULL;
}
- if (ss->udp6_bound)
+ if (ss->udp6_bound != NULL)
{
free(ss->udp6_bound);
ss->udp6_bound = NULL;
int tr_utpPacket(unsigned char const* buf, size_t buflen, struct sockaddr const* from, socklen_t fromlen, tr_session* ss)
{
- if (!ss->isClosed && !utp_timer)
+ if (!ss->isClosed && utp_timer == NULL)
{
utp_timer = evtimer_new(ss->event_base, timer_callback, ss);
void tr_utpClose(tr_session* session UNUSED)
{
- if (utp_timer)
+ if (utp_timer != NULL)
{
evtimer_del(utp_timer);
utp_timer = NULL;
typedef struct tr_event_handle
{
- uint8_t die;
+ bool die;
tr_pipe_end_t fds[2];
tr_lock* lock;
tr_session* session;
size_t const nwant = sizeof(data);
ev_ssize_t const ngot = piperead(fd, &data, nwant);
- if (!eh->die && (ngot == (ev_ssize_t)nwant))
+ if (!eh->die && ngot == (ev_ssize_t)nwant)
{
dbgmsg("invoking function in libevent thread");
(data.func)(data.user_data);
tr_lockUnlock(e->lock);
- if ((res_1 == -1) || (res_2 == -1))
+ if (res_1 == -1 || res_2 == -1)
{
tr_logAddError("Unable to write to libtransmisison event queue: %s", tr_strerror(errno));
}
struct IGDdatas data;
int port;
char lanaddr[16];
- unsigned int isMapped;
+ bool isMapped;
tr_upnp_state state;
};
void tr_upnpClose(tr_upnp* handle)
{
assert(!handle->isMapped);
- assert((handle->state == TR_UPNP_IDLE) || (handle->state == TR_UPNP_ERR) || (handle->state == TR_UPNP_DISCOVER));
+ assert(handle->state == TR_UPNP_IDLE || handle->state == TR_UPNP_ERR || handle->state == TR_UPNP_DISCOVER);
if (handle->hasDiscovered)
{
proto, NULL);
#endif
- if (err)
+ if (err != 0)
{
tr_logAddNamedDbg(getKey(), "%s Port forwarding failed with error %d (errno %d - %s)", proto, err, errno,
tr_strerror(errno));
UPNP_IGD_INVALID = 3
};
-int tr_upnpPulse(tr_upnp* handle, int port, int isEnabled, int doPortCheck)
+int tr_upnpPulse(tr_upnp* handle, int port, bool isEnabled, bool doPortCheck)
{
int ret;
- if (isEnabled && (handle->state == TR_UPNP_DISCOVER))
+ if (isEnabled && handle->state == TR_UPNP_DISCOVER)
{
struct UPNPDev* devlist;
if (handle->state == TR_UPNP_IDLE)
{
- if (handle->isMapped && (!isEnabled || (handle->port != port)))
+ if (handle->isMapped && (!isEnabled || handle->port != port))
{
handle->state = TR_UPNP_UNMAP;
}
if (isEnabled && handle->isMapped && doPortCheck)
{
- if ((tr_upnpGetSpecificPortMappingEntry(handle, "TCP") != UPNPCOMMAND_SUCCESS) ||
- (tr_upnpGetSpecificPortMappingEntry(handle, "UDP") != UPNPCOMMAND_SUCCESS))
+ if (tr_upnpGetSpecificPortMappingEntry(handle, "TCP") != UPNPCOMMAND_SUCCESS ||
+ tr_upnpGetSpecificPortMappingEntry(handle, "UDP") != UPNPCOMMAND_SUCCESS)
{
tr_logAddNamedInfo(getKey(), _("Port %d isn't forwarded"), handle->port);
handle->isMapped = false;
tr_logAddNamedInfo(getKey(), _("Stopping port forwarding through \"%s\", service \"%s\""), handle->urls.controlURL,
handle->data.first.servicetype);
- handle->isMapped = 0;
+ handle->isMapped = false;
handle->state = TR_UPNP_IDLE;
handle->port = -1;
}
int err_udp = -1;
errno = 0;
- if (!handle->urls.controlURL)
+ if (handle->urls.controlURL == NULL)
{
handle->isMapped = 0;
}
err_tcp = tr_upnpAddPortMapping(handle, "TCP", port, desc);
err_udp = tr_upnpAddPortMapping(handle, "UDP", port, desc);
- handle->isMapped = !err_tcp | !err_udp;
+ handle->isMapped = err_tcp == 0 || err_udp == 0;
}
tr_logAddNamedInfo(getKey(), _("Port forwarding through \"%s\", service \"%s\". (local address: %s:%d)"),
void tr_upnpClose(tr_upnp*);
-int tr_upnpPulse(tr_upnp*, int port, int isEnabled, int doPortCheck);
+int tr_upnpPulse(tr_upnp*, int port, bool isEnabled, bool doPortCheck);
/* @} */
in = "\x92\xE0\xE3\xA4\xAD\xAE \xA1\xEB\xE2\xEC \x81\xAE\xA3\xAE\xAC";
out = tr_utf8clean(in, 17);
check(out != NULL);
- check((strlen(out) == 17) || (strlen(out) == 33));
+ check(strlen(out) == 17 || strlen(out) == 33);
check(tr_utf8_validate(out, TR_BAD_SIZE, NULL));
tr_free(out);
in = "\xF4\x00\x81\x82";
out = tr_utf8clean(in, 4);
check(out != NULL);
- check((strlen(out) == 1) || (strlen(out) == 2));
+ check(strlen(out) == 1 || strlen(out) == 2);
check(tr_utf8_validate(out, TR_BAD_SIZE, NULL));
tr_free(out);
in = "\xF4\x33\x81\x82";
out = tr_utf8clean(in, 4);
check(out != NULL);
- check((strlen(out) == 4) || (strlen(out) == 7));
+ check(strlen(out) == 4 || strlen(out) == 7);
check(tr_utf8_validate(out, TR_BAD_SIZE, NULL));
tr_free(out);
for (i = 0; i < n; ++i)
{
- check_int_eq((i < 5 ? i : i + 1), array[i]);
+ check_int_eq(i < 5 ? i : i + 1, array[i]);
}
tr_removeElementFromArray(array, 0u, sizeof(size_t), n--);
for (i = 0; i < n; ++i)
{
- check_int_eq((i < 4 ? i + 1 : i + 2), array[i]);
+ check_int_eq(i < 4 ? i + 1 : i + 2, array[i]);
}
tr_removeElementFromArray(array, n - 1, sizeof(size_t), n);
for (i = 0; i < n; ++i)
{
- check_int_eq((i < 4 ? i + 1 : i + 2), array[i]);
+ check_int_eq(i < 4 ? i + 1 : i + 2, array[i]);
}
return 0;
struct tm* p = localtime(_clock);
- if (p)
+ if (p != NULL)
{
*(_result) = *p;
}
void* tr_malloc(size_t size)
{
- return size ? malloc(size) : NULL;
+ return size != 0 ? malloc(size) : NULL;
}
void* tr_malloc0(size_t size)
{
- return size ? calloc(1, size) : NULL;
+ return size != 0 ? calloc(1, size) : NULL;
}
void* tr_realloc(void* p, size_t size)
static size_t bufsize = 0;
static char* buf = NULL;
char const* in = str;
- size_t const len = str ? strlen(str) : 0;
+ size_t const len = str != NULL ? strlen(str) : 0;
- if (!buf || (bufsize < len))
+ if (buf == NULL || bufsize < len)
{
bufsize = len * 2 + 1;
buf = tr_renew(char, buf, bufsize);
{
*out++ = *str;
- if ((*str == '%') && isdigit(str[1]))
+ if (*str == '%' && isdigit(str[1]))
{
char const* tmp = str + 1;
}
}
- if ((*str == '%') && (str[1] == '\''))
+ if (*str == '%' && str[1] == '\'')
{
str = str + 1;
}
va_start(vl, first_element);
element = first_element;
- while (element)
+ while (element != NULL)
{
bufLen += strlen(element) + 1;
element = va_arg(vl, char const*);
va_start(vl, first_element);
element = first_element;
- while (element)
+ while (element != NULL)
{
size_t const elementLen = strlen(element);
memcpy(pch, element, elementLen);
{
int64_t free_space;
- if (!dir || !*dir)
+ if (dir == NULL || *dir == '\0')
{
errno = EINVAL;
free_space = -1;
{
out = tr_strdup(in);
}
- else if (in)
+ else if (in != NULL)
{
out = tr_malloc(len + 1);
return memmem(haystack, haystacklen, needle, needlelen);
#else
+
size_t i;
- if (!needlelen)
+ if (needlelen == 0)
{
return haystack;
}
- if (needlelen > haystacklen || !haystack || !needle)
+ if (needlelen > haystacklen || haystack == NULL || needle == NULL)
{
return NULL;
}
int tr_strcmp0(char const* str1, char const* str2)
{
- if (str1 && str2)
+ if (str1 != NULL && str2 != NULL)
{
return strcmp(str1, str2);
}
- if (str1)
+ if (str1 != NULL)
{
return 1;
}
- if (str2)
+ if (str2 != NULL)
{
return -1;
}
size_t pos;
size_t len = strlen(str);
- while (len && isspace(str[len - 1]))
+ while (len != 0 && isspace(str[len - 1]))
{
--len;
}
size_t str_len;
size_t suffix_len;
- if (!str)
+ if (str == NULL)
{
return false;
}
- if (!suffix)
+ if (suffix == NULL)
{
return true;
}
*d = '\0'; /* NUL-terminate dst */
}
- while (*s++)
+ while (*s++ != '\0')
{
}
}
size_t const buflen = inlen * 4 + 10;
char* out = tr_new(char, buflen);
- for (i = 0; !ret && i < encoding_count; ++i)
+ for (i = 0; ret == NULL && i < encoding_count; ++i)
{
#ifdef ICONV_SECOND_ARGUMENT_IS_CONST
char const* inbuf = in;
errno = 0;
a = b = strtol(tmp, &end, 10);
- if (errno || (end == tmp))
+ if (errno != 0 || end == tmp)
{
success = false;
}
char const* pch = end + 1;
b = strtol(pch, &end, 10);
- if (errno || (pch == end))
+ if (errno != 0 || pch == end)
{
success = false;
}
- else if (*end) /* trailing data */
+ else if (*end != '\0') /* trailing data */
{
success = false;
}
walk = str;
- while (walk && *walk && success)
+ while (walk != NULL && *walk != '\0' && success)
{
struct number_range range;
char const* pch = strchr(walk, ',');
- if (pch)
+ if (pch != NULL)
{
success = parseNumberSection(walk, (size_t)(pch - walk), &range);
walk = pch + 1;
{
for (i = n = 0; i < n2; ++i)
{
- if (!n || uniq[n - 1] != sorted[i])
+ if (n == 0 || uniq[n - 1] != sorted[i])
{
uniq[n++] = sorted[i];
}
int const max_precision = (int)log10(1.0 / DBL_EPSILON) - 1;
tr_snprintf(buf, sizeof(buf), "%.*f", max_precision, x);
- if ((pt = strstr(buf, localeconv()->decimal_point)))
+ if ((pt = strstr(buf, localeconv()->decimal_point)) != NULL)
{
- pt[precision ? precision + 1 : 0] = '\0';
+ pt[precision != 0 ? precision + 1 : 0] = '\0';
}
return atof(buf);
void* buf = NULL;
static size_t pageSize = 0;
- if (!pageSize)
+ if (pageSize == 0)
{
#if defined(HAVE_GETPAGESIZE) && !defined(_WIN32)
pageSize = (size_t)getpagesize();
#ifdef HAVE_POSIX_MEMALIGN
- if (!buf)
+ if (buf == NULL)
{
- if (posix_memalign(&buf, pageSize, allocLen))
+ if (posix_memalign(&buf, pageSize, allocLen) != 0)
{
buf = NULL; /* just retry with valloc/malloc */
}
#ifdef HAVE_VALLOC
- if (!buf)
+ if (buf == NULL)
{
buf = valloc(allocLen);
}
#endif
- if (!buf)
+ if (buf == NULL)
{
buf = tr_malloc(allocLen);
}
errno = 0;
val = evutil_strtoll(begin, &endptr, 10);
- if (errno || (endptr != end)) /* incomplete parse */
+ if (errno != 0 || endptr != end) /* incomplete parse */
{
return EILSEQ;
}
- if (val && *(char const*)begin == '0') /* no leading zeroes! */
+ if (val != 0 && *(char const*)begin == '0') /* no leading zeroes! */
{
return EILSEQ;
}
errno = 0;
len = strtoul((char const*)buf, &ulend, 10);
- if (errno || ulend != end)
+ if (errno != 0 || ulend != end)
{
goto err;
}
strbegin = (uint8_t const*)end + 1;
strend = strbegin + len;
- if ((strend < strbegin) || (strend > bufend))
+ if (strend < strbegin || strend > bufend)
{
goto err;
}
{
node = tr_variantListAdd(parent);
}
- else if (*key && tr_variantIsDict(parent))
+ else if (*key != 0 && tr_variantIsDict(parent))
{
node = tr_variantDictAdd(parent, *key);
*key = 0;
err = EILSEQ;
}
- if (err)
+ if (err != 0)
{
break;
}
uint8_t const* end;
tr_variant* v;
- if ((err = tr_bencParseInt(buf, bufend, &end, &val)))
+ if ((err = tr_bencParseInt(buf, bufend, &end, &val)) != 0)
{
break;
}
buf = end;
- if ((v = get_node(&stack, &key, top, &err)))
+ if ((v = get_node(&stack, &key, top, &err)) != NULL)
{
tr_variantInitInt(v, val);
}
++buf;
- if ((v = get_node(&stack, &key, top, &err)))
+ if ((v = get_node(&stack, &key, top, &err)) != NULL)
{
tr_variantInitList(v, 0);
tr_ptrArrayAppend(&stack, v);
++buf;
- if ((v = get_node(&stack, &key, top, &err)))
+ if ((v = get_node(&stack, &key, top, &err)) != NULL)
{
tr_variantInitDict(v, 0);
tr_ptrArrayAppend(&stack, v);
{
++buf;
- if (tr_ptrArrayEmpty(&stack) || (key != 0))
+ if (tr_ptrArrayEmpty(&stack) || key != 0)
{
err = EILSEQ;
break;
uint8_t const* str;
size_t str_len;
- if ((err = tr_bencParseStr(buf, bufend, &end, &str, &str_len)))
+ if ((err = tr_bencParseStr(buf, bufend, &end, &str, &str_len)) != 0)
{
break;
}
buf = end;
- if (!key && !tr_ptrArrayEmpty(&stack) && tr_variantIsDict(tr_ptrArrayBack(&stack)))
+ if (key == 0 && !tr_ptrArrayEmpty(&stack) && tr_variantIsDict(tr_ptrArrayBack(&stack)))
{
key = tr_quark_new(str, str_len);
}
- else if ((v = get_node(&stack, &key, top, &err)))
+ else if ((v = get_node(&stack, &key, top, &err)) != NULL)
{
tr_variantInitStr(v, str, str_len);
}
parent = tr_ptrArrayEmpty(&data->stack) ? NULL : tr_ptrArrayBack(&data->stack);
- if (!parent)
+ if (parent == NULL)
{
node = data->top;
}
{
node = tr_variantListAdd(parent);
}
- else if (tr_variantIsDict(parent) && (data->key != NULL))
+ else if (tr_variantIsDict(parent) && data->key != NULL)
{
node = tr_variantDictAdd(parent, tr_quark_new(data->key, data->keylen));
{
struct json_wrapper_data* data = jsn->data;
- if (data->source)
+ if (data->source != NULL)
{
tr_logAddError("JSON parse failed in %s at pos %zu: %s -- remaining text \"%.16s\"", data->source, jsn->pos,
jsonsl_strerror(error), buf);
{
val <<= 4;
- if (('0' <= *in) && (*in <= '9'))
+ if ('0' <= *in && *in <= '9')
{
val += (*in - '0');
}
- else if (('a' <= *in) && (*in <= 'f'))
+ else if ('a' <= *in && *in <= 'f')
{
val += (*in - 'a') + 10u;
}
- else if (('A' <= *in) && (*in <= 'F'))
+ else if ('A' <= *in && *in <= 'F')
{
val += (*in - 'A') + 10u;
}
data->has_content = true;
data->key = extract_string(jsn, state, &data->keylen, data->keybuf);
}
- else if ((state->type == JSONSL_T_LIST) || (state->type == JSONSL_T_OBJECT))
+ else if (state->type == JSONSL_T_LIST || state->type == JSONSL_T_OBJECT)
{
tr_ptrArrayPop(&data->stack);
}
else if (state->type == JSONSL_T_SPECIAL)
{
- if (state->special_flags & JSONSL_SPECIALf_NUMNOINT)
+ if ((state->special_flags & JSONSL_SPECIALf_NUMNOINT) != 0)
{
char const* begin = jsn->base + state->pos_begin;
data->has_content = true;
tr_variantInitReal(get_node(jsn), strtod(begin, NULL));
}
- else if (state->special_flags & JSONSL_SPECIALf_NUMERIC)
+ else if ((state->special_flags & JSONSL_SPECIALf_NUMERIC) != 0)
{
char const* begin = jsn->base + state->pos_begin;
data->has_content = true;
tr_variantInitInt(get_node(jsn), evutil_strtoll(begin, NULL, 10));
}
- else if (state->special_flags & JSONSL_SPECIALf_BOOLEAN)
+ else if ((state->special_flags & JSONSL_SPECIALf_BOOLEAN) != 0)
{
bool const b = (state->special_flags & JSONSL_SPECIALf_TRUE) != 0;
data->has_content = true;
tr_variantInitBool(get_node(jsn), b);
}
- else if (state->special_flags & JSONSL_SPECIALf_NULL)
+ else if ((state->special_flags & JSONSL_SPECIALf_NULL) != 0)
{
data->has_content = true;
tr_variantInitQuark(get_node(jsn), TR_KEY_NONE);
jsonsl_feed(jsn, vbuf, len);
/* EINVAL if there was no content */
- if (!data.error && !data.has_content)
+ if (data.error == 0 && !data.has_content)
{
data.error = EINVAL;
}
/* maybe set the end ptr */
- if (setme_end)
+ if (setme_end != NULL)
{
*setme_end = ((char const*)vbuf) + jsn->pos;
}
{
static char buf[1024] = { '\0' };
- if (!*buf)
+ if (*buf == '\0')
{
memset(buf, ' ', sizeof(buf));
buf[0] = '\n';
static void jsonChildFunc(struct jsonWalk* data)
{
- if (data->parents && data->parents->data)
+ if (data->parents != NULL && data->parents->data != NULL)
{
struct ParentState* pstate = data->parents->data;
{
int const i = pstate->childIndex++;
- if (!(i % 2))
+ if (i % 2 == 0)
{
evbuffer_add(data->out, ": ", data->doIndent ? 2 : 1);
}
UTF32* u32 = buf;
ConversionResult result = ConvertUTF8toUTF32(&tmp, end, &u32, buf + 1, 0);
- if (((result == conversionOK) || (result == targetExhausted)) && (tmp != it))
+ if ((result == conversionOK || result == targetExhausted) && tmp != it)
{
outwalk += tr_snprintf(outwalk, outend - outwalk, "\\u%04x", (unsigned int)buf[0]);
it = tmp - 1;
jsonPushParent(data, val);
evbuffer_add(data->out, "{", 1);
- if (val->val.l.count)
+ if (val->val.l.count != 0)
{
jsonIndent(data);
}
jsonPushParent(data, val);
evbuffer_add(data->out, "[", 1);
- if (nChildren)
+ if (nChildren != 0)
{
jsonIndent(data);
}
tr_variantWalk(top, &walk_funcs, &data, true);
- if (evbuffer_get_length(buf))
+ if (evbuffer_get_length(buf) != 0)
{
evbuffer_add_printf(buf, "\n");
}
err = tr_bencParseInt(buf, buf + 4, &end, &val);
check_int_eq(0, err);
check_int_eq(64, val);
- check((buf + 4) == end);
+ check(buf + 4 == end);
/* missing 'e' */
end = NULL;
err = tr_bencParseInt(buf, buf + 4, &end, &val);
check_int_eq(0, err);
check_int_eq(-3, val);
- check((buf + 4) == end);
+ check(buf + 4 == end);
/* zero */
tr_snprintf((char*)buf, sizeof(buf), "i0e");
err = tr_bencParseInt(buf, buf + 4, &end, &val);
check_int_eq(0, err);
check_int_eq(0, val);
- check((buf + 3) == end);
+ check(buf + 3 == end);
/* no leading zeroes allowed */
val = 0;
check_uint_eq(0, len);
check(str == NULL);
check(end == NULL);
- check(!len);
+ check(len == 0);
/* good string */
n = tr_snprintf((char*)buf, sizeof(buf), "4:boat");
check_uint_eq(0, len);
check(str == NULL);
check(end == NULL);
- check(!len);
+ check(len == 0);
/* empty string */
n = tr_snprintf((char*)buf, sizeof(buf), "0:");
err = tr_bencParseStr(buf, buf + n, &end, &str, &len);
check_int_eq(0, err);
check_uint_eq(0, len);
- check(!*str);
+ check(*str == '\0');
check(end == buf + 2);
str = NULL;
end = NULL;
if (!isGood)
{
- check(err);
+ check(err != 0);
}
else
{
- check(!err);
+ check(err == 0);
#if 0
fprintf(stderr, "in: [%s]\n", str);
fprintf(stderr, "out:\n%s", tr_variantToStr(&val, TR_VARIANT_FMT_JSON, NULL));
tr_snprintf((char*)buf, sizeof(buf), "i64e");
err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
- check(!err);
+ check(err == 0);
check(tr_variantGetInt(&val, &i));
check_int_eq(64, i);
check(end == buf + 4);
tr_snprintf((char*)buf, sizeof(buf), "li64ei32ei16ee");
err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
- check(!err);
+ check(err == 0);
check(end == buf + strlen((char*)buf));
check(val.val.l.count == 3);
check(tr_variantGetInt(&val.val.l.vals[0], &i));
end = NULL;
tr_snprintf((char*)buf, sizeof(buf), "lllee");
err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
- check(err);
+ check(err != 0);
check(end == NULL);
end = NULL;
tr_snprintf((char*)buf, sizeof(buf), "le");
err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
- check(!err);
+ check(err == 0);
check(end == buf + 2);
saved = tr_variantToStr(&val, TR_VARIANT_FMT_BENC, &len);
check_streq("le", saved);
tr_free(saved);
tr_variantFree(&val);
- if ((err = testString("llleee", true)))
+ if ((err = testString("llleee", true)) != 0)
{
return err;
}
- if ((err = testString("d3:cow3:moo4:spam4:eggse", true)))
+ if ((err = testString("d3:cow3:moo4:spam4:eggse", true)) != 0)
{
return err;
}
- if ((err = testString("d4:spaml1:a1:bee", true)))
+ if ((err = testString("d4:spaml1:a1:bee", true)) != 0)
{
return err;
}
- if ((err = testString("d5:greenli1ei2ei3ee4:spamd1:ai123e3:keyi214eee", true)))
+ if ((err = testString("d5:greenli1ei2ei3ee4:spamd1:ai123e3:keyi214eee", true)) != 0)
{
return err;
}
- if ((err = testString("d9:publisher3:bob17:publisher-webpage15:www.example.com18:publisher.location4:homee", true)))
+ if ((err = testString("d9:publisher3:bob17:publisher-webpage15:www.example.com18:publisher.location4:homee", true)) != 0)
{
return err;
}
- if ((err = testString("d8:completei1e8:intervali1800e12:min intervali1800e5:peers0:e", true)))
+ if ((err = testString("d8:completei1e8:intervali1800e12:min intervali1800e5:peers0:e", true)) != 0)
{
return err;
}
- if ((err = testString("d1:ai0e1:be", false))) /* odd number of children */
+ if ((err = testString("d1:ai0e1:be", false)) != 0) /* odd number of children */
{
return err;
}
- if ((err = testString("", false)))
+ if ((err = testString("", false)) != 0)
{
return err;
}
- if ((err = testString(" ", false)))
+ if ((err = testString(" ", false)) != 0)
{
return err;
}
end = NULL;
tr_snprintf((char*)buf, sizeof(buf), "lld1:bi32e1:ai64eeee");
err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
- check(!err);
+ check(err == 0);
check(end == buf + strlen((char const*)buf));
- check((child = tr_variantListChild(&val, 0)));
- check((child2 = tr_variantListChild(child, 0)));
+ check((child = tr_variantListChild(&val, 0)) != NULL);
+ check((child2 = tr_variantListChild(child, 0)) != NULL);
saved = tr_variantToStr(&val, TR_VARIANT_FMT_BENC, &len);
check_streq("lld1:ai64e1:bi32eeee", saved);
tr_free(saved);
end = NULL;
tr_snprintf((char*)buf, sizeof(buf), "leee");
err = tr_variantFromBencFull(&val, buf, sizeof(buf), NULL, &end);
- check(!err);
+ check(err == 0);
check(end == buf + 2);
saved = tr_variantToStr(&val, TR_VARIANT_FMT_BENC, &len);
check_streq("le", saved);
end = NULL;
tr_snprintf((char*)buf, sizeof(buf), "l1:a1:b1:c");
err = tr_variantFromBencFull(&val, buf, strlen(buf), NULL, &end);
- check(err);
+ check(err != 0);
/* incomplete string */
end = NULL;
tr_snprintf((char*)buf, sizeof(buf), "1:");
err = tr_variantFromBencFull(&val, buf, strlen(buf), NULL, &end);
- check(err);
+ check(err != 0);
return 0;
}
{
char* out;
- for (out = in; in && *in; ++in)
+ for (out = in; in != NULL && *in != '\0'; ++in)
{
if (!isspace(*in))
{
benc_str = "i6e";
expected = "6";
- if ((val = testJSONSnippet(benc_str, expected)))
+ if ((val = testJSONSnippet(benc_str, expected)) != 0)
{
return val;
}
benc_str = "d5:helloi1e5:worldi2ee";
expected = "{\"hello\":1,\"world\":2}";
- if ((val = testJSONSnippet(benc_str, expected)))
+ if ((val = testJSONSnippet(benc_str, expected)) != 0)
{
return val;
}
benc_str = "d5:helloi1e5:worldi2e3:fooli1ei2ei3eee";
expected = "{\"foo\":[1,2,3],\"hello\":1,\"world\":2}";
- if ((val = testJSONSnippet(benc_str, expected)))
+ if ((val = testJSONSnippet(benc_str, expected)) != 0)
{
return val;
}
benc_str = "d5:helloi1e5:worldi2e3:fooli1ei2ei3ed1:ai0eeee";
expected = "{\"foo\":[1,2,3,{\"a\":0}],\"hello\":1,\"world\":2}";
- if ((val = testJSONSnippet(benc_str, expected)))
+ if ((val = testJSONSnippet(benc_str, expected)) != 0)
{
return val;
}
benc_str = "d4:argsd6:statusle7:status2lee6:result7:successe";
expected = "{\"args\":{\"status\":[],\"status2\":[]},\"result\":\"success\"}";
- if ((val = testJSONSnippet(benc_str, expected)))
+ if ((val = testJSONSnippet(benc_str, expected)) != 0)
{
return val;
}
in[depth * 2] = '\0';
err = tr_variantFromBencFull(&val, in, depth * 2, NULL, &end);
check_int_eq(0, err);
- check(end == in + (depth * 2));
+ check(end == in + depth * 2);
saved = tr_variantToStr(&val, TR_VARIANT_FMT_BENC, &len);
check_streq((char*)in, saved);
tr_free(in);
check(tr_variantDictFindBool(&top, key4, &boolVal));
check(boolVal);
check(tr_variantDictFindInt(&top, key1, &intVal));
- check(!intVal);
+ check(intVal == 0);
check(tr_variantDictFindInt(&top, key2, &intVal));
- check(!intVal);
+ check(intVal == 0);
check(tr_variantDictFindInt(&top, key3, &intVal));
- check(intVal);
+ check(intVal != 0);
check(tr_variantDictFindInt(&top, key4, &intVal));
- check(intVal);
+ check(intVal != 0);
tr_variantFree(&top);
return 0;
benc = tr_variantToStr(&top, TR_VARIANT_FMT_BENC, &len);
check_streq("d14:this-is-a-booli1e14:this-is-a-real8:0.50000016:this-is-a-string16:this-is-a-string14:this-is-an-int"
"i1234ee", benc);
- check(!tr_variantFromBencFull(&top2, benc, len, NULL, &end));
+ check(tr_variantFromBencFull(&top2, benc, len, NULL, &end) == 0);
check(end == benc + len);
check(tr_variantIsDict(&top2));
check(tr_variantDictFindInt(&top, key_int, &intVal));
{
tr_variant* ret = NULL;
- if (tr_variantIsList(v) && (i < v->val.l.count))
+ if (tr_variantIsList(v) && i < v->val.l.count)
{
ret = v->val.l.vals + i;
}
{
bool removed = false;
- if (tr_variantIsList(list) && (i < list->val.l.count))
+ if (tr_variantIsList(list) && i < list->val.l.count)
{
removed = true;
tr_variantFree(&list->val.l.vals[i]);
{
bool success = false;
- if (!success && ((success = tr_variantIsInt(v))))
+ if (!success && (success = tr_variantIsInt(v)))
{
- if (setme)
+ if (setme != NULL)
{
*setme = v->val.i;
}
}
- if (!success && ((success = tr_variantIsBool(v))))
+ if (!success && (success = tr_variantIsBool(v)))
{
- if (setme)
+ if (setme != NULL)
{
*setme = v->val.b ? 1 : 0;
}
if (!success && tr_variantIsInt(v))
{
- if ((success = (v->val.i == 0 || v->val.i == 1)))
+ if ((success = v->val.i == 0 || v->val.i == 1))
{
*setme = v->val.i != 0;
}
if (!success && tr_variantGetStr(v, &str, NULL))
{
- if ((success = (strcmp(str, "true") == 0 || strcmp(str, "false") == 0)))
+ if ((success = strcmp(str, "true") == 0 || strcmp(str, "false") == 0))
{
*setme = strcmp(str, "true") == 0;
}
{
bool success = false;
- if (!success && ((success = tr_variantIsReal(v))))
+ if (!success && (success = tr_variantIsReal(v)))
{
*setme = v->val.d;
}
- if (!success && ((success = tr_variantIsInt(v))))
+ if (!success && (success = tr_variantIsInt(v)))
{
*setme = v->val.i;
}
d = strtod(getStr(v), &endptr);
restore_locale(&locale_ctx);
- if ((success = (getStr(v) != endptr) && !*endptr))
+ if ((success = getStr(v) != endptr && *endptr == '\0'))
{
*setme = d;
}
if (needed > v->val.l.alloc)
{
/* scale the alloc size in powers-of-2 */
- size_t n = v->val.l.alloc ? v->val.l.alloc : 8;
+ size_t n = v->val.l.alloc != 0 ? v->val.l.alloc : 8;
while (n < needed)
{
tr_variant* child;
/* see if it already exists, and if so, try to reuse it */
- if ((child = tr_variantDictFind(dict, key)))
+ if ((child = tr_variantDictFind(dict, key)) != NULL)
{
if (!tr_variantIsType(child, type))
{
v = node->v;
node->isVisited = true;
}
- else if (tr_variantIsContainer(node->v) && (node->childIndex < node->v->val.l.count))
+ else if (tr_variantIsContainer(node->v) && node->childIndex < node->v->val.l.count)
{
int const index = node->childIndex++;
v = node->v->val.l.vals + index;
continue;
}
- if (v)
+ if (v != NULL)
{
switch (v->type)
{
int i = 0;
tr_variant const* val;
- while ((val = tr_variantListChild((tr_variant*)src, i++)))
+ while ((val = tr_variantListChild((tr_variant*)src, i++)) != NULL)
{
if (tr_variantIsBool(val))
{
assert(tr_variantIsDict(dict));
- if (tr_variantIsDict(dict) && (n < dict->val.l.count))
+ if (tr_variantIsDict(dict) && n < dict->val.l.count)
{
*key = dict->val.l.vals[n].key;
*val = dict->val.l.vals + n;
static inline bool tr_variantIsType(tr_variant const* b, int type)
{
- return (b != NULL) && (b->type == type);
+ return b != NULL && b->type == type;
}
/***
static inline bool tr_variantIsString(tr_variant const* b)
{
- return (b != NULL) && (b->type == TR_VARIANT_TYPE_STR);
+ return b != NULL && b->type == TR_VARIANT_TYPE_STR;
}
bool tr_variantGetStr(tr_variant const* variant, char const** setme_str, size_t* setme_len);
static inline bool tr_variantIsReal(tr_variant const* v)
{
- return (v != NULL) && (v->type == TR_VARIANT_TYPE_REAL);
+ return v != NULL && v->type == TR_VARIANT_TYPE_REAL;
}
void tr_variantInitReal(tr_variant* initme, double value);
static inline bool tr_variantIsBool(tr_variant const* v)
{
- return (v != NULL) && (v->type == TR_VARIANT_TYPE_BOOL);
+ return v != NULL && v->type == TR_VARIANT_TYPE_BOOL;
}
void tr_variantInitBool(tr_variant* initme, bool value);
static inline bool tr_variantIsInt(tr_variant const* v)
{
- return (v != NULL) && (v->type == TR_VARIANT_TYPE_INT);
+ return v != NULL && v->type == TR_VARIANT_TYPE_INT;
}
void tr_variantInitInt(tr_variant* variant, int64_t value);
static inline bool tr_variantIsList(tr_variant const* v)
{
- return (v != NULL) && (v->type == TR_VARIANT_TYPE_LIST);
+ return v != NULL && v->type == TR_VARIANT_TYPE_LIST;
}
void tr_variantInitList(tr_variant* list, size_t reserve_count);
static inline bool tr_variantIsDict(tr_variant const* v)
{
- return (v != NULL) && (v->type == TR_VARIANT_TYPE_DICT);
+ return v != NULL && v->type == TR_VARIANT_TYPE_DICT;
}
void tr_variantInitDict(tr_variant* initme, size_t reserve_count);
tr_logAddTorDbg(tor, "%s", "verifying torrent...");
tr_torrentSetChecked(tor, 0);
- while (!*stopFlag && (pieceIndex < tor->info.pieceCount))
+ while (!*stopFlag && pieceIndex < tor->info.pieceCount)
{
uint64_t leftInPiece;
uint64_t bytesThisPass;
{
for (;;)
{
- int changed = 0;
+ bool changed = false;
tr_torrent* tor;
struct verify_node* node;
tr_lockLock(getVerifyLock());
stopCurrent = false;
- node = (struct verify_node*)verifyList ? verifyList->data : NULL;
+ node = verifyList != NULL ? verifyList->data : NULL;
if (node == NULL)
{
tr_torrentSetDirty(tor);
}
- if (currentNode.callback_func)
+ if (currentNode.callback_func != NULL)
{
(*currentNode.callback_func)(tor, stopCurrent, currentNode.callback_data);
}
static void task_free(struct tr_web_task* task)
{
- if (task->freebuf)
+ if (task->freebuf != NULL)
{
evbuffer_free(task->freebuf);
}
{
tr_torrent* tor = tr_torrentFindFromId(task->session, task->torrentId);
- if (tor && !tr_bandwidthClamp(&tor->bandwidth, TR_DOWN, nmemb))
+ if (tor != NULL && tr_bandwidthClamp(&tor->bandwidth, TR_DOWN, nmemb) == 0)
{
tr_list_append(&paused_easy_handles, task->curl_easy);
return CURL_WRITEFUNC_PAUSE;
long timeout;
tr_session const* session = task->session;
- if (!session || session->isClosed)
+ if (session == NULL || session->isClosed)
{
timeout = 20L;
}
curl_easy_setopt(e, CURLOPT_WRITEDATA, task);
curl_easy_setopt(e, CURLOPT_WRITEFUNCTION, writeFunc);
- if (((addr = tr_sessionGetPublicAddress(s, TR_AF_INET, &is_default_value))) && !is_default_value)
+ if ((addr = tr_sessionGetPublicAddress(s, TR_AF_INET, &is_default_value)) != NULL && !is_default_value)
{
curl_easy_setopt(e, CURLOPT_INTERFACE, tr_address_to_string(addr));
}
- else if (((addr = tr_sessionGetPublicAddress(s, TR_AF_INET6, &is_default_value))) && !is_default_value)
+ else if ((addr = tr_sessionGetPublicAddress(s, TR_AF_INET6, &is_default_value)) != NULL && !is_default_value)
{
curl_easy_setopt(e, CURLOPT_INTERFACE, tr_address_to_string(addr));
}
task->cookies = tr_strdup(cookies);
task->done_func = done_func;
task->done_func_user_data = done_func_user_data;
- task->response = buffer ? buffer : evbuffer_new();
- task->freebuf = buffer ? NULL : task->response;
+ task->response = buffer != NULL ? buffer : evbuffer_new();
+ task->freebuf = buffer != NULL ? NULL : task->response;
tr_lockLock(session->web->taskLock);
task->next = session->web->tasks;
(void)nfds;
- if (!r_fd_set->fd_count && !w_fd_set->fd_count && !c_fd_set->fd_count)
+ if (r_fd_set->fd_count == 0 && w_fd_set->fd_count == 0 && c_fd_set->fd_count == 0)
{
long int const msec = t->tv_sec * 1000 + t->tv_usec / 1000;
tr_wait_msec(msec);
}
- else if (select(0, r_fd_set->fd_count ? r_fd_set : NULL, w_fd_set->fd_count ? w_fd_set : NULL,
- c_fd_set->fd_count ? c_fd_set : NULL, t) < 0)
+ else if (select(0, r_fd_set->fd_count != 0 ? r_fd_set : NULL, w_fd_set->fd_count != 0 ? w_fd_set : NULL,
+ c_fd_set->fd_count != 0 ? c_fd_set : NULL, t) < 0)
{
char errstr[512];
int const e = EVUTIL_SOCKET_ERROR();
/* try to enable ssl for https support; but if that fails,
* try a plain vanilla init */
- if (curl_global_init(CURL_GLOBAL_SSL))
+ if (curl_global_init(CURL_GLOBAL_SSL) != CURLE_OK)
{
curl_global_init(0);
}
break;
}
- if ((web->close_mode == TR_WEB_CLOSE_WHEN_IDLE) && (web->tasks == NULL))
+ if (web->close_mode == TR_WEB_CLOSE_WHEN_IDLE && web->tasks == NULL)
{
break;
}
tmp = paused_easy_handles;
paused_easy_handles = NULL;
- while ((handle = tr_list_pop_front(&tmp)))
+ while ((handle = tr_list_pop_front(&tmp)) != NULL)
{
curl_easy_pause(handle, CURLPAUSE_CONT);
}
while (mcode == CURLM_CALL_MULTI_PERFORM);
/* pump completed tasks from the multi */
- while ((msg = curl_multi_info_read(multi, &unused)))
+ while ((msg = curl_multi_info_read(multi, &unused)) != NULL)
{
- if ((msg->msg == CURLMSG_DONE) && (msg->easy_handle != NULL))
+ if (msg->msg == CURLMSG_DONE && msg->easy_handle != NULL)
{
double total_time;
struct tr_web_task* task;
curl_easy_getinfo(e, CURLINFO_REQUEST_SIZE, &req_bytes_sent);
curl_easy_getinfo(e, CURLINFO_TOTAL_TIME, &total_time);
task->did_connect = task->code > 0 || req_bytes_sent > 0;
- task->did_timeout = !task->code && (total_time >= task->timeout_secs);
+ task->did_timeout = task->code == 0 && total_time >= task->timeout_secs;
curl_multi_remove_handle(multi, e);
tr_list_remove_data(&paused_easy_handles, e);
curl_easy_cleanup(e);
for (char const* end = str + len; str != end; ++str)
{
- if ((*str == ',') || (*str == '-') || (*str == '.') || (('0' <= *str) && (*str <= '9')) ||
- (('A' <= *str) && (*str <= 'Z')) || (('a' <= *str) && (*str <= 'z')) || ((*str == '/') && (!escape_slashes)))
+ if (*str == ',' || *str == '-' || *str == '.' || ('0' <= *str && *str <= '9') || ('A' <= *str && *str <= 'Z') ||
+ ('a' <= *str && *str <= 'z') || (*str == '/' && !escape_slashes))
{
evbuffer_add_printf(out, "%c", *str);
}
struct connection_succeeded_data* data = vdata;
struct tr_webseed* w = data->webseed;
- if (++w->active_transfers >= w->retry_challenge && w->retry_challenge)
+ if (++w->active_transfers >= w->retry_challenge && w->retry_challenge != 0)
{
/* the server seems to be accepting more connections now */
w->consecutive_failures = w->retry_tickcount = w->retry_challenge = 0;
}
- if (data->real_url && (tor = tr_torrentFindFromId(w->session, w->torrent_id)))
+ if (data->real_url != NULL && (tor = tr_torrentFindFromId(w->session, w->torrent_id)) != NULL)
{
uint64_t file_offset;
tr_file_index_t file_index;
tr_sessionLock(session);
- if (!task->dead && (n_added > 0))
+ if (!task->dead && n_added > 0)
{
uint32_t len;
struct tr_webseed* w = task->webseed;
fire_client_got_piece_data(w, n_added);
len = evbuffer_get_length(buf);
- if (!task->response_code)
+ if (task->response_code == 0)
{
tr_webGetTaskInfo(task->web_task, TR_WEB_GET_CODE, &task->response_code);
}
}
- if ((task->response_code == 206) && (len >= task->block_size))
+ if (task->response_code == 206 && len >= task->block_size)
{
/* once we've got at least one full block, save it */
w->retry_challenge = running_tasks + w->idle_connections + 1;
}
- if (tor && tor->isRunning && !tr_torrentIsSeed(tor) && (want > 0))
+ if (tor != NULL && tor->isRunning && !tr_torrentIsSeed(tor) && want > 0)
{
int i;
int got = 0;
{
tr_block_index_t const blocks_remain = (t->length + tor->blockSize - 1) / tor->blockSize - t->blocks_done;
- if (blocks_remain)
+ if (blocks_remain != 0)
{
fire_client_got_rejs(tor, w, t->block + t->blocks_done, blocks_remain);
}
- if (t->blocks_done)
+ if (t->blocks_done != 0)
{
++w->idle_connections;
}
- else if (++w->consecutive_failures >= MAX_CONSECUTIVE_FAILURES && !w->retry_tickcount)
+ else if (++w->consecutive_failures >= MAX_CONSECUTIVE_FAILURES && w->retry_tickcount == 0)
{
/* now wait a while until retrying to establish a connection */
++w->retry_tickcount;
}
else
{
- if (buf_len && !tr_torrentPieceIsComplete(tor, t->piece_index))
+ if (buf_len != 0 && !tr_torrentPieceIsComplete(tor, t->piece_index))
{
/* on_content_changed() will not write a block if it is smaller than
the torrent's block size, i.e. the torrent's very last block */
evbuffer_add(buf, w->base_url, w->base_url_len);
/* if url ends with a '/', add the torrent name */
- if (w->base_url[w->base_url_len - 1] == '/' && file->name)
+ if (w->base_url[w->base_url_len - 1] == '/' && file->name != NULL)
{
tr_http_escape(buf, file->name, strlen(file->name), false);
}
{
tr_webseed* w = vw;
- if (w->retry_tickcount)
+ if (w->retry_tickcount != 0)
{
++w->retry_tickcount;
}
size_t len;
void* raw = tr_base64_decode(key.toUtf8().constData(), key.toUtf8().size(), &len);
- if (raw)
+ if (raw != nullptr)
{
metainfo.append(static_cast<char const*>(raw), int(len));
tr_free(raw);
QString configDir;
QStringList filenames;
- while ((c = tr_getopt(getUsage(), argc, const_cast<char const**>(argv), opts, &optarg)))
+ while ((c = tr_getopt(getUsage(), argc, const_cast<char const**>(argv), opts, &optarg)) != TR_OPT_DONE)
{
switch (c)
{
{
Torrent* tor = myModel->getTorrentFromId(id);
- if (tor)
+ if (tor != nullptr)
{
if (myPrefs->getBool(Prefs::SHOW_NOTIFICATION_ON_COMPLETE))
{
{
Torrent* tor = myModel->getTorrentFromId(id);
- if (tor && !tor->name().isEmpty())
+ if (tor != nullptr && !tor->name().isEmpty())
{
int const age_secs = tor->dateAdded().secsTo(QDateTime::currentDateTime());
{
PeerItem const* i = dynamic_cast<PeerItem const*>(&other);
QTreeWidget* tw(treeWidget());
- int const column = tw ? tw->sortColumn() : 0;
+ int const column = tw != nullptr ? tw->sortColumn() : 0;
assert(i != nullptr);
{
Torrent const* tor = myModel.getTorrentFromId(id);
- if (tor)
+ if (tor != nullptr)
{
disconnect(tor, SIGNAL(torrentChanged(int)), this, SLOT(onTorrentChanged()));
}
{
Torrent const* tor = myModel.getTorrentFromId(id);
- if (tor)
+ if (tor != nullptr)
{
connect(tor, SIGNAL(torrentChanged(int)), this, SLOT(onTorrentChanged()));
}
{
Torrent const* tor = myModel.getTorrentFromId(id);
- if (tor)
+ if (tor != nullptr)
{
torrents << tor;
}
}
}
- double const d = 100.0 * (sizeWhenDone ? (sizeWhenDone - leftUntilDone) / sizeWhenDone : 1);
+ double const d = 100.0 * (sizeWhenDone != 0 ? (sizeWhenDone - leftUntilDone) / sizeWhenDone : 1);
QString pct = Formatter::percentToString(d);
- if (!haveUnverified && !leftUntilDone)
+ if (haveUnverified == 0 && leftUntilDone == 0)
{
//: Text following the "Have:" label in torrent properties dialog;
//: %1 is amount of downloaded and verified data
string = tr("%1 (100%)").arg(Formatter::sizeToString(haveVerified));
}
- else if (!haveUnverified)
+ else if (haveUnverified == 0)
{
//: Text following the "Have:" label in torrent properties dialog;
//: %1 is amount of downloaded and verified data,
QString const dstr = Formatter::sizeToString(d);
QString const fstr = Formatter::sizeToString(f);
- if (f)
+ if (f != 0)
{
string = tr("%1 (%2 corrupt)").arg(dstr).arg(fstr);
}
}
}
- if (!size)
+ if (size == 0)
{
string = none;
}
}
setIfIdle(ui.ratioCombo, uniform ? ui.ratioCombo->findData(baselineInt) : -1);
- ui.ratioSpin->setVisible(uniform && (baselineInt == TR_RATIOLIMIT_SINGLE));
+ ui.ratioSpin->setVisible(uniform && baselineInt == TR_RATIOLIMIT_SINGLE);
setIfIdle(ui.ratioSpin, baseline.seedRatioLimit());
}
setIfIdle(ui.idleCombo, uniform ? ui.idleCombo->findData(baselineInt) : -1);
- ui.idleSpin->setVisible(uniform && (baselineInt == TR_RATIOLIMIT_SINGLE));
+ ui.idleSpin->setVisible(uniform && baselineInt == TR_RATIOLIMIT_SINGLE);
setIfIdle(ui.idleSpin, baseline.seedIdleLimit());
onIdleLimitChanged();
tr_quark const key = spin->property(PREF_KEY).toInt();
QDoubleSpinBox const* d = qobject_cast<QDoubleSpinBox const*>(spin);
- if (d)
+ if (d != nullptr)
{
mySession.torrentSet(myIds, key, d->value());
}
int const first_dot = host.indexOf(QLatin1Char('.'));
int const last_dot = host.lastIndexOf(QLatin1Char('.'));
- if ((first_dot != -1) && (last_dot != -1) && (first_dot != last_dot))
+ if (first_dot != -1 && last_dot != -1 && first_dot != last_dot)
{
host.remove(0, first_dot + 1);
}
QByteArray const content = reply->readAll();
- if (!reply->error())
+ if (reply->error() == QNetworkReply::NoError)
{
pixmap.loadFromData(content);
}
{
int const column(index.column());
- if ((column != FileTreeModel::COL_PROGRESS) && (column != FileTreeModel::COL_WANTED))
+ if (column != FileTreeModel::COL_PROGRESS && column != FileTreeModel::COL_WANTED)
{
QItemDelegate::paint(painter, option, index);
return;
if (myParent != nullptr)
{
int const pos = row();
- assert((pos >= 0) && "couldn't find child in parent's lookup");
+ assert(pos >= 0 && "couldn't find child in parent's lookup");
myParent->myChildren.removeAt(pos);
myParent->myChildRows.remove(name());
myParent->myFirstUnhashedRow = pos;
{
int i(-1);
- if (myParent)
+ if (myParent != nullptr)
{
i = myParent->getMyChildRows().value(name(), -1);
assert(this == myParent->myChildren[i]);
getSubtreeWantedSize(have, total);
- if (total)
+ if (total != 0)
{
d = have / double(total);
}
if (myName != name)
{
- if (myParent)
+ if (myParent != nullptr)
{
myParent->myFirstUnhashedRow = row();
}
{
int i(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
- if (myIsEditable && (index.column() == COL_NAME))
+ if (myIsEditable && index.column() == COL_NAME)
{
i |= Qt::ItemIsEditable;
}
FileTreeItem* childItem = parentItem->child(row);
- if (childItem)
+ if (childItem != nullptr)
{
i = createIndex(row, column, childItem);
}
QModelIndex FileTreeModel::indexOf(FileTreeItem* item, int column) const
{
- if (!item || item == myRootItem)
+ if (item == nullptr || item == myRootItem)
{
return QModelIndex();
}
item = findItemForFileIndex(fileIndex);
- if (item) // this file is already in the tree, we've added this
+ if (item != nullptr) // this file is already in the tree, we've added this
{
QModelIndex indexWithChangedParents;
ForwardPathIterator filenameIt(filename);
QString const& token = filenameIt.next();
FileTreeItem* child(item->child(token));
- if (!child)
+ if (child == nullptr)
{
added = true;
QModelIndex parentIndex(indexOf(item, 0));
int const childCount = rowCount(index);
- if (!childCount)
+ if (childCount == 0)
{
return;
}
return tr("Unknown");
}
- if (!bytes)
+ if (bytes == 0)
{
return tr("None");
}
return tr("Unknown");
}
- if (!bytes)
+ if (bytes == 0)
{
return tr("None");
}
m = tr("%Ln minute(s)", nullptr, minutes);
s = tr("%Ln second(s)", nullptr, seconds);
- if (days)
+ if (days != 0)
{
- if (days >= 4 || !hours)
+ if (days >= 4 || hours == 0)
{
str = d;
}
str = tr("%1, %2").arg(d).arg(h);
}
}
- else if (hours)
+ else if (hours != 0)
{
- if (hours >= 4 || !minutes)
+ if (hours >= 4 || minutes == 0)
{
str = h;
}
str = tr("%1, %2").arg(h).arg(m);
}
}
- else if (minutes)
+ else if (minutes != 0)
{
- if (minutes >= 4 || !seconds)
+ if (minutes >= 4 || seconds == 0)
{
str = m;
}
{
QIcon icon = QIcon::fromTheme(name);
- if (icon.isNull() && (fallback >= 0))
+ if (icon.isNull() && fallback >= 0)
{
icon = style()->standardIcon(QStyle::StandardPixmap(fallback), 0, this);
}
void MainWindow::onSetPrefs()
{
QVariantList const p = sender()->property(PREF_VARIANTS_KEY).toList();
- assert((p.size() % 2) == 0);
+ assert(p.size() % 2 == 0);
for (int i = 0, n = p.size(); i < n; i += 2)
{
{
tip = tr("Network Error");
}
- else if (!upCount && !downCount)
+ else if (upCount == 0 && downCount == 0)
{
tip = tr("Idle");
}
- else if (downCount)
+ else if (downCount != 0)
{
tip = Formatter::downloadSpeedToString(downSpeed) + QLatin1String(" ") + Formatter::uploadSpeedToString(upSpeed);
}
- else if (upCount)
+ else if (upCount != 0)
{
tip = Formatter::uploadSpeedToString(upSpeed);
}
assert(model == modelIndex.model());
Torrent const* tor(model->data(modelIndex, TorrentModel::TorrentRole).value<Torrent const*>());
- if (tor)
+ if (tor != nullptr)
{
bool const isSelected(selectionModel->isSelected(modelIndex));
bool const isPaused(tor->isPaused());
void MainWindow::trayActivated(QSystemTrayIcon::ActivationReason reason)
{
- if ((reason == QSystemTrayIcon::Trigger) || (reason == QSystemTrayIcon::DoubleClick))
+ if (reason == QSystemTrayIcon::Trigger || reason == QSystemTrayIcon::DoubleClick)
{
if (isMinimized())
{
if (!deleteFiles)
{
- primary_text = (count == 1) ? tr("Remove torrent?") : tr("Remove %Ln torrent(s)?", nullptr, count);
+ primary_text = count == 1 ? tr("Remove torrent?") : tr("Remove %Ln torrent(s)?", nullptr, count);
}
else
{
- primary_text = (count == 1) ? tr("Delete this torrent's downloaded files?") :
+ primary_text = count == 1 ? tr("Delete this torrent's downloaded files?") :
tr("Delete these %Ln torrent(s)' downloaded files?", nullptr, count);
}
if (!incomplete && !connected)
{
- secondary_text = (count == 1) ?
+ secondary_text = count == 1 ?
tr("Once removed, continuing the transfer will require the torrent file or magnet link.") :
tr("Once removed, continuing the transfers will require the torrent files or magnet links.");
}
else if (count == incomplete)
{
- secondary_text = (count == 1) ? tr("This torrent has not finished downloading.") :
+ secondary_text = count == 1 ? tr("This torrent has not finished downloading.") :
tr("These torrents have not finished downloading.");
}
else if (count == connected)
{
- secondary_text = (count == 1) ? tr("This torrent is connected to peers.") :
+ secondary_text = count == 1 ? tr("This torrent is connected to peers.") :
tr("These torrents are connected to peers.");
}
else
{
- if (connected)
+ if (connected != 0)
{
- secondary_text = (connected == 1) ? tr("One of these torrents is connected to peers.") :
+ secondary_text = connected == 1 ? tr("One of these torrents is connected to peers.") :
tr("Some of these torrents are connected to peers.");
}
- if (connected && incomplete)
+ if (connected != 0 && incomplete != 0)
{
secondary_text += QLatin1Char('\n');
}
- if (incomplete)
+ if (incomplete != 0)
{
- secondary_text += (incomplete == 1) ? tr("One of these torrents has not finished downloading.") :
+ secondary_text += incomplete == 1 ? tr("One of these torrents has not finished downloading.") :
tr("Some of these torrents have not finished downloading.");
}
}
QString tip;
QString const url = mySession.getRemoteUrl().host();
- if (!myLastReadTime)
+ if (myLastReadTime == 0)
{
tip = tr("%1 has not responded yet").arg(url);
}
{
tip = tr("%1 is responding").arg(url);
}
- else if (secondsSinceLastRead < (60 * 2))
+ else if (secondsSinceLastRead < 60 * 2)
{
tip = tr("%1 last responded %2 ago").arg(url).arg(Formatter::timeToString(secondsSinceLastRead));
}
{
if (!myNetworkError)
{
- myLastReadTime = time(NULL);
+ myLastReadTime = time(nullptr);
}
}
void MainWindow::dataSendProgress()
{
- myLastSendTime = time(NULL);
+ myLastSendTime = time(nullptr);
}
void MainWindow::onNetworkResponse(QNetworkReply::NetworkError code, QString const& message)
{
bool const hadError = myNetworkError;
- bool const haveError = (code != QNetworkReply::NoError) && (code != QNetworkReply::UnknownContentError);
+ bool const haveError = code != QNetworkReply::NoError && code != QNetworkReply::UnknownContentError;
myNetworkError = haveError;
myErrorMessage = message;
{
// progress bar
tr_metainfo_builder const& b = myBuilder;
- double const denom = b.pieceCount ? b.pieceCount : 1;
+ double const denom = b.pieceCount != 0 ? b.pieceCount : 1;
ui.progressBar->setValue(static_cast<int>((100.0 * b.pieceIndex) / denom));
// progress label
}
int const err = tr_torrentParse(ctor, &myInfo);
- myHaveInfo = !err;
+ myHaveInfo = err == 0;
tr_ctorFree(ctor);
ui.filesView->clear();
tr_file const* file = &myInfo.files[myVerifyFileIndex];
- if (!myVerifyFilePos && !myVerifyFile.isOpen())
+ if (myVerifyFilePos == 0 && !myVerifyFile.isOpen())
{
QFileInfo const fileInfo(myLocalDestination, QString::fromUtf8(file->name));
myVerifyFile.setFileName(fileInfo.absoluteFilePath());
have += f.have;
}
- if (!have) // everything failed
+ if (have == 0) // everything failed
{
// did the user accidentally specify the child directory instead of the parent?
QStringList const tokens = QString::fromUtf8(file->name).split(QLatin1Char('/'));
break;
default:
- assert("unhandled type" && 0);
+ assert(false && "unhandled type");
break;
}
}
break;
default:
- assert("unhandled type" && 0);
+ assert(false && "unhandled type");
break;
}
}
return TR_SCHED_SUN;
default:
- assert(0 && "Invalid day of week");
+ assert(false && "Invalid day of week");
return 0;
}
}
return PrefsDialog::tr("Sunday");
default:
- assert(0 && "Invalid day of week");
+ assert(false && "Invalid day of week");
return QString();
}
}
}
case Prefs::RPC_AUTH_REQUIRED:
- if (mySession)
+ if (mySession != nullptr)
{
tr_sessionSetRPCPasswordEnabled(mySession, myPrefs.getBool(key));
}
break;
case Prefs::RPC_ENABLED:
- if (mySession)
+ if (mySession != nullptr)
{
tr_sessionSetRPCEnabled(mySession, myPrefs.getBool(key));
}
break;
case Prefs::RPC_PASSWORD:
- if (mySession)
+ if (mySession != nullptr)
{
tr_sessionSetRPCPassword(mySession, myPrefs.getString(key).toUtf8().constData());
}
break;
case Prefs::RPC_PORT:
- if (mySession)
+ if (mySession != nullptr)
{
tr_sessionSetRPCPort(mySession, myPrefs.getInt(key));
}
break;
case Prefs::RPC_USERNAME:
- if (mySession)
+ if (mySession != nullptr)
{
tr_sessionSetRPCUsername(mySession, myPrefs.getString(key).toUtf8().constData());
}
break;
case Prefs::RPC_WHITELIST_ENABLED:
- if (mySession)
+ if (mySession != nullptr)
{
tr_sessionSetRPCWhitelistEnabled(mySession, myPrefs.getBool(key));
}
break;
case Prefs::RPC_WHITELIST:
- if (mySession)
+ if (mySession != nullptr)
{
tr_sessionSetRPCWhitelist(mySession, myPrefs.getString(key).toUtf8().constData());
}
{
myRpc.stop();
- if (mySession)
+ if (mySession != nullptr)
{
tr_sessionClose(mySession);
mySession = nullptr;
{
tr_variant const* b(tr_variantDictFind(d, myPrefs.getKey(i)));
- if (!b)
+ if (b == nullptr)
{
continue;
}
setBlocklistSize(i);
}
- if (tr_variantDictFindStr(d, TR_KEY_version, &str, nullptr) && (mySessionVersion != QString::fromUtf8(str)))
+ if (tr_variantDictFindStr(d, TR_KEY_version, &str, nullptr) && mySessionVersion != QString::fromUtf8(str))
{
mySessionVersion = QString::fromUtf8(str);
}
{
QUrl url;
- if (!mySession) // remote session
+ if (mySession == nullptr) // remote session
{
url = myRpc.url();
url.setPath(QLatin1String("/transmission/web/"));
void SqueezeLabel::paintEvent(QPaintEvent* paintEvent)
{
- if (hasFocus() && (textInteractionFlags() & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse)))
+ if (hasFocus() && (textInteractionFlags() & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse)) != 0)
{
return QLabel::paintEvent(paintEvent);
}
default:
std::cerr << __FILE__ << ':' << __LINE__ << "unhandled type: " << tr_quark_get_string(key, nullptr) << std::endl;
- assert(0 && "unhandled type");
+ assert(false && "unhandled type");
}
}
myFiles.clear();
myFiles.reserve(tr_variantListSize(files));
- while ((child = tr_variantListChild(files, i)))
+ while ((child = tr_variantListChild(files, i)) != nullptr)
{
TorrentFile file;
size_t len;
QStringList list;
tr_variant* child;
- while ((child = tr_variantListChild(trackers, i++)))
+ while ((child = tr_variantListChild(trackers, i++)) != nullptr)
{
if (tr_variantDictFindStr(child, TR_KEY_announce, &str, &len))
{
TrackerStatsList trackerStatsList;
int childNum = 0;
- while ((child = tr_variantListChild(trackerStats, childNum++)))
+ while ((child = tr_variantListChild(trackerStats, childNum++)) != nullptr)
{
bool b;
int64_t i;
PeerList peerList;
int childNum = 0;
- while ((child = tr_variantListChild(peers, childNum++)))
+ while ((child = tr_variantListChild(peers, childNum++)) != nullptr)
{
double d;
bool b;
emit torrentChanged(id());
}
- if (!was_seed && isSeed() && (old_verified_size > 0))
+ if (!was_seed && isSeed() && old_verified_size > 0)
{
emit torrentCompleted(id());
}
switch (myPrefs.get<SortMode>(Prefs::SORT_MODE).mode())
{
case SortMode::SORT_BY_QUEUE:
- if (!val)
+ if (val == 0)
{
val = -compare(a->queuePosition(), b->queuePosition());
}
break;
case SortMode::SORT_BY_SIZE:
- if (!val)
+ if (val == 0)
{
val = compare(a->sizeWhenDone(), b->sizeWhenDone());
}
break;
case SortMode::SORT_BY_ID:
- if (!val)
+ if (val == 0)
{
val = compare(a->id(), b->id());
}
break;
case SortMode::SORT_BY_ACTIVITY:
- if (!val)
+ if (val == 0)
{
val = compare(a->downloadSpeed() + a->uploadSpeed(), b->downloadSpeed() + b->uploadSpeed());
}
- if (!val)
+ if (val == 0)
{
val = compare(a->peersWeAreUploadingTo() + a->webseedsWeAreDownloadingFrom(),
b->peersWeAreUploadingTo() + b->webseedsWeAreDownloadingFrom());
// fall through
case SortMode::SORT_BY_STATE:
- if (!val)
+ if (val == 0)
{
val = -compare(a->isPaused(), b->isPaused());
}
- if (!val)
+ if (val == 0)
{
val = compare(a->getActivity(), b->getActivity());
}
- if (!val)
+ if (val == 0)
{
val = -compare(a->queuePosition(), b->queuePosition());
}
- if (!val)
+ if (val == 0)
{
val = compare(a->hasError(), b->hasError());
}
// fall through
case SortMode::SORT_BY_PROGRESS:
- if (!val)
+ if (val == 0)
{
val = compare(a->percentComplete(), b->percentComplete());
}
- if (!val)
+ if (val == 0)
{
val = a->compareSeedRatio(*b);
}
- if (!val)
+ if (val == 0)
{
val = -compare(a->queuePosition(), b->queuePosition());
}
// fall through
case SortMode::SORT_BY_RATIO:
- if (!val)
+ if (val == 0)
{
val = a->compareRatio(*b);
}
break;
case SortMode::SORT_BY_ETA:
- if (!val)
+ if (val == 0)
{
val = a->compareETA(*b);
}
int i = 0;
tr_variant* child;
- while ((child = tr_variantListChild(torrents, i++)))
+ while ((child = tr_variantListChild(torrents, i++)) != nullptr)
{
int64_t intVal;
size_t i(0);
tr_variant* child;
- while ((child = tr_variantListChild(torrents, i++)))
+ while ((child = tr_variantListChild(torrents, i++)) != nullptr)
{
int64_t id;
int const row = index.row();
- if ((0 <= row) && (row < myRows.size()))
+ if (0 <= row && row < myRows.size())
{
TrackerInfo const& trackerInfo = myRows.at(row);
{
TrackerInfo const& inf = myRows.at(i);
- if ((inf.torrentId == torrentId) && (url == inf.st.announce))
+ if (inf.torrentId == torrentId && url == inf.st.announce)
{
return i;
}
{
int n; // number of bytes in a UTF-8 sequence
- for (char const* c = s; *c; c += n)
+ for (char const* c = s; *c != '\0'; c += n)
{
if ((*c & 0x80) == 0x00)
{
tr_ctorSetMetainfoFromFile(ctor, filename.toUtf8().constData());
int const err = tr_torrentParse(ctor, &inf);
- if (err)
+ if (err != 0)
{
ret = ERROR;
}
}
// cleanup
- if (!err)
+ if (err == 0)
{
tr_metainfoFree(&inf);
}
int c;
char const* optarg;
- while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+ while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
{
switch (c)
{
break;
case 's':
- if (optarg)
+ if (optarg != NULL)
{
char* endptr = NULL;
piecesize_kib = strtoul(optarg, &endptr, 10);
- if (endptr && *endptr == 'M')
+ if (endptr != NULL && *endptr == 'M')
{
piecesize_kib *= KiB;
}
tr_formatter_size_init(DISK_K, DISK_K_STR, DISK_M_STR, DISK_G_STR, DISK_T_STR);
tr_formatter_speed_init(SPEED_K, SPEED_K_STR, SPEED_M_STR, SPEED_G_STR, SPEED_T_STR);
- if (parseCommandLine(argc, (char const* const*)argv))
+ if (parseCommandLine(argc, (char const* const*)argv) != 0)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
- if (!infile)
+ if (infile == NULL)
{
fprintf(stderr, "ERROR: No input file or directory specified.\n");
tr_getopt_usage(MY_NAME, getUsage(), options);
tr_free(base);
}
- if (!trackerCount)
+ if (trackerCount == 0)
{
if (isPrivate)
{
int c;
char const* optarg;
- while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+ while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
{
switch (c)
{
tr_variant* tier;
int tierIndex = 0;
- while ((tier = tr_variantListChild(announce_list, tierIndex)))
+ while ((tier = tr_variantListChild(announce_list, tierIndex)) != NULL)
{
tr_variant* node;
int nodeIndex = 0;
- while ((node = tr_variantListChild(tier, nodeIndex)))
+ while ((node = tr_variantListChild(tier, nodeIndex)) != NULL)
{
if (tr_variantGetStr(node, &str, NULL) && strcmp(str, url) == 0)
{
tr_variant* tier;
tr_variant* node;
- if ((tier = tr_variantListChild(announce_list, 0)))
+ if ((tier = tr_variantListChild(announce_list, 0)) != NULL)
{
- if ((node = tr_variantListChild(tier, 0)))
+ if ((node = tr_variantListChild(tier, 0)) != NULL)
{
if (tr_variantGetStr(node, &str, NULL))
{
size_t const inlen = strlen(in);
size_t const outlen = strlen(out);
- while ((walk = strstr(str, in)))
+ while ((walk = strstr(str, in)) != NULL)
{
evbuffer_add(buf, str, walk - str);
evbuffer_add(buf, out, outlen);
tr_variant* announce_list;
bool changed = false;
- if (tr_variantDictFindStr(metainfo, TR_KEY_announce, &str, NULL) && strstr(str, in))
+ if (tr_variantDictFindStr(metainfo, TR_KEY_announce, &str, NULL) && strstr(str, in) != NULL)
{
char* newstr = replaceSubstr(str, in, out);
printf("\tReplaced in \"announce\": \"%s\" --> \"%s\"\n", str, newstr);
tr_variant* tier;
int tierCount = 0;
- while ((tier = tr_variantListChild(announce_list, tierCount++)))
+ while ((tier = tr_variantListChild(announce_list, tierCount++)) != NULL)
{
tr_variant* node;
int nodeCount = 0;
- while ((node = tr_variantListChild(tier, nodeCount++)))
+ while ((node = tr_variantListChild(tier, nodeCount++)) != NULL)
{
- if (tr_variantGetStr(node, &str, NULL) && strstr(str, in))
+ if (tr_variantGetStr(node, &str, NULL) && strstr(str, in) != NULL)
{
char* newstr = replaceSubstr(str, in, out);
printf("\tReplaced in \"announce-list\" tier %d: \"%s\" --> \"%s\"\n", tierCount, str, newstr);
tr_variant* tier;
int tierCount = 0;
- while ((tier = tr_variantListChild(announce_list, tierCount++)))
+ while ((tier = tr_variantListChild(announce_list, tierCount++)) != NULL)
{
tr_variant* node;
char const* str;
int nodeCount = 0;
- while ((node = tr_variantListChild(tier, nodeCount++)))
+ while ((node = tr_variantListChild(tier, nodeCount++)) != NULL)
{
if (tr_variantGetStr(node, &str, NULL) && strcmp(str, url) == 0)
{
tr_logSetLevel(TR_LOG_ERROR);
- if (parseCommandLine(argc, (char const* const*)argv))
+ if (parseCommandLine(argc, (char const* const*)argv) != 0)
{
return EXIT_FAILURE;
}
return EXIT_FAILURE;
}
- if (!add && !deleteme && !replace[0])
+ if (add == NULL && deleteme == NULL && replace[0] == 0)
{
fprintf(stderr, "ERROR: Must specify -a, -d or -r\n");
tr_getopt_usage(MY_NAME, getUsage(), options);
changed = addURL(&top, add);
}
- if (replace[0] && replace[1])
+ if (replace[0] != NULL && replace[1] != NULL)
{
changed |= replaceURL(&top, replace[0], replace[1]);
}
int c;
char const* optarg;
- while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)))
+ while ((c = tr_getopt(getUsage(), argc, argv, options, &optarg)) != TR_OPT_DONE)
{
switch (c)
{
printf(" Hash: %s\n", inf->hashString);
printf(" Created by: %s\n", inf->creator ? inf->creator : "Unknown");
- if (!inf->dateCreated)
+ if (inf->dateCreated == 0)
{
printf(" Created on: Unknown\n");
}
printf(" Created on: %s", asctime(&tm));
}
- if (inf->comment && *inf->comment)
+ if (inf->comment != NULL && *inf->comment != '\0')
{
printf(" Comment: %s\n", inf->comment);
}
tr_http_escape_sha1(escaped, inf->hash);
- url = tr_strdup_printf("%s%cinfo_hash=%s", scrape, strchr(scrape, '?') ? '&' : '?', escaped);
+ url = tr_strdup_printf("%s%cinfo_hash=%s", scrape, strchr(scrape, '?') != NULL ? '&' : '?', escaped);
printf("%s ... ", url);
fflush(stdout);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, TIMEOUT_SECS);
- if ((res = curl_easy_perform(curl)))
+ if ((res = curl_easy_perform(curl)) != CURLE_OK)
{
printf("error: %s\n", curl_easy_strerror(res));
}
bool matched = false;
char const* begin = (char const*)evbuffer_pullup(buf, -1);
- if (!tr_variantFromBenc(&top, begin, evbuffer_get_length(buf)))
+ if (tr_variantFromBenc(&top, begin, evbuffer_get_length(buf)) == 0)
{
if (tr_variantDictFindDict(&top, TR_KEY_files, &files))
{
tr_formatter_size_init(DISK_K, DISK_K_STR, DISK_M_STR, DISK_G_STR, DISK_T_STR);
tr_formatter_speed_init(SPEED_K, SPEED_K_STR, SPEED_M_STR, SPEED_G_STR, SPEED_T_STR);
- if (parseCommandLine(argc, (char const* const*)argv))
+ if (parseCommandLine(argc, (char const* const*)argv) != 0)
{
return EXIT_FAILURE;
}
}
/* make sure the user specified a filename */
- if (!filename)
+ if (filename == NULL)
{
fprintf(stderr, "ERROR: No .torrent file specified.\n");
tr_getopt_usage(MY_NAME, getUsage(), options);
err = tr_torrentParse(ctor, &inf);
tr_ctorFree(ctor);
- if (err)
+ if (err != TR_PARSE_OK)
{
fprintf(stderr, "Error parsing .torrent file \"%s\"\n", filename);
return EXIT_FAILURE;