-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgptandformat.cpp
More file actions
304 lines (279 loc) · 12.2 KB
/
gptandformat.cpp
File metadata and controls
304 lines (279 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#include "gptandformat.h"
#define WAITING_TIME 6000
GPTandFormat::GPTandFormat(QObject *parent, Common *common) :
QThread(parent)
{
this->comm = common;
}
void GPTandFormat::deviceAndFileSystemToFormat(QString device, QString fileSystem)
{
this->dev = device;
this->fs = fileSystem;
}
int GPTandFormat::formatThisDeviceUsingThisFS(QString device, QString fileSystem)
{
QString dev;
dev = this->prepareDevice(device);
QString formatCommand = "mkfs."+fileSystem.toLower();
QStringList strings;
QStringList commands;
QString fs;
QStringList paramsToFormat;
if (fileSystem.contains("NTFS")){
fs = "0700\n";
paramsToFormat << "-v" << "-f";
emit log("[user] Formatar com NTFS");
}
else{
fs = "8300\n";
if (fileSystem.contains("XFS")){
paramsToFormat << "-f";
emit log("[user] Formatar com XFS");
}
else{
paramsToFormat << "-v";
emit log("[user] Formatar com EXTn");
}
}
QProcess formatDisk;
QStringList params;
int status = 1;
params << dev;
strings << ".*help\\): " << ".*Proceed\\? \\(Y/N\\): " << ".*Command \\(\\? for help\\): " << ".*Partition number \\(1-128, default 1\\): ";
strings << " " << " " << " ";
strings << ".*Command \\(\\? for help\\): " << ".*Do you want to proceed\\? \\(Y/N\\): ";
commands << "o\n" << "y\n" << "n\n" << "1\n" << "\n" << "\n" << fs << "w\n" << "y\n";
formatDisk.start("gdisk",params); //"gdisk /dev/sdX", sem digito, tratado no prepareDevice
if (!formatDisk.waitForReadyRead(WAITING_TIME)){
QStringList msgs;
emit log("[warning] Processo finalizado inesperadamente");
msgs << tr("O processo finalizou inesperadamente logo após ser iniciado. Informe o suporte.");
msgs << tr("Processo finalizado com erro");
msgs << " ";
emit signalRunMessageBox(msgs);
msgs.clear();
return -1;
}
QString t = formatDisk.readAllStandardOutput();
if (t.isEmpty()){
QStringList msgs;
emit log("[warning] Falha no processo de controle do particionamento");
msgs << tr("Houve falha na intercomunicação com o processo de controle do particionamento.");
msgs << tr("Processo finalizado com erro");
msgs << " ";
emit signalRunMessageBox(msgs);
msgs.clear();
return -1;
}
QRegExp rx;
int percent = 1;
rx.setPattern("GPT\\sfdisk\\s\\(gdisk\\)\\sversion\\s\\d{1,}\\.?\\d{0,}\\.?\\d{0,}\n\n$");
if (t.contains(rx)){
rx.setPattern("Your\\sanswer:\\s");
while (!t.contains(rx)){
formatDisk.waitForReadyRead(WAITING_TIME);
t = formatDisk.readAllStandardOutput();
}
formatDisk.write("2\n");
formatDisk.waitForReadyRead(WAITING_TIME);
t = formatDisk.readAllStandardOutput();
}
for (int i=0;i<commands.length();i++){
if (i>3 && i<7){
status = formatDisk.write(commands.at(i).toUtf8());
if (status < 0){
QStringList msgs;
msgs << tr("O processo falhou no passo ")+QString::number(i)+tr(". Informe ao suporte.");
emit log("[warning] " + msgs.at(0).toUtf8());
msgs << tr("Falha durante execução");
msgs << tr("Você pode tentar outra mídia, ou então preparar essa mídia previamente ao uso, descartando a opção formatar.");
emit signalRunMessageBox(msgs);
msgs.clear();
return status;
}
if (!formatDisk.waitForReadyRead(WAITING_TIME)){
QStringList msgs;
msgs << tr("O processo finalizou inesperadamente no passo ")+QString::number(i)+tr(", ao aguardar para o próximo passo. Informe ao suporte.");
emit log("[warning] " + msgs.at(0).toUtf8());
msgs << tr("Processo finalizado com erro");
msgs << tr("Você pode tentar outra mídia, ou então preparar essa mídia previamente ao uso, descartando a opção formatar.");
emit signalRunMessageBox(msgs);
msgs.clear();
return -1;
}
t = formatDisk.readAllStandardOutput();
if (t.isEmpty()){
QStringList msgs;
msgs << tr("O processo finalizou inesperadamente no passo ")+QString::number(i)+tr(", ao aguardar para o próximo passo. Informe ao suporte.");
emit log("[warning] " + msgs.at(0).toUtf8());
msgs << tr("Falha do processo em segundo plano");
msgs << tr("Você pode tentar outra mídia, ou então preparar essa mídia previamente ao uso, descartando a opção formatar.");
emit signalRunMessageBox(msgs);
msgs.clear();
return -1;
}
}
else if (i<4 || i>6){
rx.setPattern(strings.at(i));
rx.indexIn(t);
QString result = rx.capturedTexts().last();
if (result.length() < 2){
QString regex = strings.at(i);
QString msgToUser = tr("Ocorreu um erro no passo ")+QString::number(i)+tr(" aguardando pela seguinte porção de bytes:\n");
emit log("[warning] " + msgToUser.toUtf8());
msgToUser += regex + "\n";
msgToUser += tr("A resposta obtida foi:\n");
msgToUser += t;
QStringList msgs;
msgs << tr("Ocorreu um erro inesperado. Veja informações nos detalhes.");
msgs << tr("Erro durante operação");
msgs << msgToUser;
emit signalRunMessageBox(msgs);
msgs.clear();
return -1;
}
status = formatDisk.write(commands.at(i).toUtf8());
if (status < 0){
QStringList msgs;
msgs << tr("O processo falhou no passo ")+QString::number(i)+tr(". Informe ao suporte.");
emit log("[warning] " + msgs.at(0).toUtf8());
msgs << tr("Falha durante execução");
msgs << tr("Você pode tentar outra mídia, ou então preparar essa mídia previamente ao uso, descartando a opção formatar.");
emit signalRunMessageBox(msgs);
msgs.clear();
return status;
}
if (!formatDisk.waitForReadyRead(WAITING_TIME)){
QStringList msgs;
msgs << tr("O processo finalizou inesperadamente no passo ")+QString::number(i)+tr(", ao aguardar para o próximo passo. Informe ao suporte.");
emit log("[warning] " + msgs.at(0).toUtf8());
msgs << tr("Processo finalizado com erro");
msgs << tr("Você pode tentar outra mídia, ou então preparar essa mídia previamente ao uso, descartando a opção formatar.");
emit signalRunMessageBox(msgs);
msgs.clear();
return -1;
}
t = formatDisk.readAllStandardOutput();
if (t.isEmpty()){
QStringList msgs;
msgs << tr("Houve falha na intercomunicação com o processo de controle do particionamento.");
emit log("[warning] " + msgs.at(0).toUtf8());
msgs << tr("Processo finalizado com erro");
msgs << tr("Você pode tentar outra mídia, ou então preparar essa mídia previamente ao uso, descartando a opção formatar.");
emit signalRunMessageBox(msgs);
msgs.clear();
return -1;
}
}
emit signalSetProgressBarValNow(percent);
}
formatDisk.close();
//O disco de perícia deve conter apenas 1 partição, exceto se opte por não, mas é incomum,
//portanto agora é presumida sua formatação.
int thereIsANewPartition = this->isTherePartition(dev);
if (thereIsANewPartition != 0){
return -1;
}
QProcess formatThisNewerPartition;
QRegExp digits("(\\d)");
QString newDevice = dev.remove(digits) + "1";
if (!QFile::exists(newDevice)){
QStringList msgs;
msgs << tr("Por alguma razão o dispositivo não foi criado. Tente repetir o processo ou reinserir a mídia de destino.");
emit log("[warning] " + msgs.at(0).toUtf8());
msgs << tr("Dispositivo inexistente");
msgs << tr("A primeira fase do processo consiste na recriação da tabela de partições com uma única partição do tipo escolhido. O erro ocorreu na segunda fase, que é validação do dispositivo, isto é, se ele foi criado pelo sistema operacional.");
emit signalRunMessageBox(msgs);
msgs.clear();
return -1;
}
paramsToFormat << newDevice;
formatThisNewerPartition.setProcessChannelMode(QProcess::MergedChannels);
formatThisNewerPartition.start(formatCommand,paramsToFormat);
QString line;
QRegExp rxPercent("(\\d{1,}/\\d{1,})");
if (formatCommand.contains(QRegExp("ext\\d"))){
while (formatThisNewerPartition.waitForReadyRead(15000)){
line = formatThisNewerPartition.readAllStandardOutput();
rxPercent.indexIn(line);
QString resultOfParsing = rxPercent.capturedTexts().last();
if (resultOfParsing.contains(rxPercent) && !resultOfParsing.contains("0/239")){
emit signalStatusLabel(resultOfParsing);
percent = resultOfParsing.split("/").at(0).toInt()*100/resultOfParsing.split("/").at(1).toInt();
emit signalSetProgressBarValNow(percent);
}
else{
emit signalStatusLabel(tr("Um momento..."));
}
}
}
else if (formatCommand.contains(QRegExp("ntfs"))){
while (formatThisNewerPartition.waitForReadyRead(15000)){
line = formatThisNewerPartition.readAllStandardOutput();
emit signalStatusLabel(line);
}
}
else if (formatCommand.contains("xfs")){
emit signalStatusLabel(tr("Aguardando retorno do programa..."));
QStringList msgs;
msgs << tr("Esse sistema de arquivos só devolverá informações ao final da operação, mas não se preocupe. Você será informado sobre qualquer anomalia");
msgs << tr("Sistema de arquivos silencioso");
msgs << " ";
emit signalRunMessageBox(msgs);
while (formatThisNewerPartition.waitForReadyRead(15000)){
line = formatThisNewerPartition.readAllStandardOutput();
emit signalStatusLabel(line);
}
}
emit signalSetProgressBarValNow(100);
formatThisNewerPartition.close();
return 4;
}
int GPTandFormat::isTherePartition(QString device)
{
//-1 - erro, 0 - ok, 1 - nao validado
QProcess readPartition;
QRegExp partValidate(".*\\s{,3}[1-128]\\s{,15}\\d\\s{,15}\\d\\s{,15}\\d\\.?\\d?\\s.*\\s{,15}\\d.*");
QStringList params;
params << "-l" << device;
readPartition.start("gdisk",params);
if (!readPartition.waitForFinished(WAITING_TIME)){
QStringList msgs;
msgs << tr("Ocorreu algum erro na tentativa de leitura das partições do dispositivo indicado.");
emit log("[warning] " + msgs.at(0).toUtf8());
msgs << tr("Erro na leitura do dispositivo");
QString longMsg = tr("Esse erro não significa que a mídia é inválida, porém se utilizada, uma nova ");
longMsg += tr("tabela de partições será gerada sem validar previamente o disco. Se você considerar ");
longMsg += tr("isso um problema, experimente outra mídia de destino.");
msgs << longMsg;
emit signalRunMessageBox(msgs);
msgs.clear();
return -1;
}
QString t = readPartition.readAllStandardOutput();
readPartition.close();
partValidate.indexIn(t);
QString result = partValidate.capturedTexts().last();
if (result.contains(t)){
return 0;
}
return 1;
}
QString GPTandFormat::prepareDevice(QString device){
QRegExp rx("\\d{1,}");
if (device.contains(rx)){
device = device.remove(rx);
}
if (!device.contains("/dev/")){
return "/dev/"+device;
}
else{
return device;
}
}
void GPTandFormat::run(){
int result = this->formatThisDeviceUsingThisFS(this->dev,this->fs);
if (result == 4){
emit sucess();
}
}